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]>
28 KiB
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(stagesdeps→test→build→runtime; Next.jsoutput: "standalone", runs asnodeUID 1000, port 3000, HEALTHCHECK hits/api/health),.dockerignore,compose.yaml(local container check only,AUTH_MODE=dev),vibe.yaml(port, health path,persistenceat/app/data,auth.mode: oidc, required secret names). - App name
aisubsidy→https://aisubsidy-vibe.moonshine-studio.net. Runtime secrets (vibe.yamlenvironment.required):SESSION_SECRET,APP_URL,BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS— values live in the developer's local.envand are handed to the Deployment API by/vibe-deploy:deploy-site; never commit them. Adding a new required env var means updatingvibe.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 inoidcmode → login disabled + warning. Keep new config degrading the same way instead of exiting. - Migrations run on startup (
src/instrumentation.ts→migrateOnStartup); the image has notsx. Migration SQL is copied into the image explicitly (standalone tracing doesn't include it). /api/healthmust stay public (excluded insrc/proxy.ts).
Authentication & authorization
- Login is company Authentik OIDC only (
AUTH_MODE=oidc, default), withprompt=login(always re-enter credentials) and local-only logout (doesn't sign out of other company systems) — both user decisions. The vibe platform injectsOIDC_ISSUER/OIDC_CLIENT_ID/OIDC_CLIENT_SECRET(reserved names — never put them in the repo);APP_URLbuilds the redirect URI${APP_URL}/api/auth/callback/authentik. No passwords anywhere. AUTH_MODE=devenables/login/dev(log in by employee number) for local dev and e2e. Startup refusesAUTH_MODE=devwhenOIDC_ISSUERis present; inoidcmode/login/devand its action return 404. Never key behavior offNODE_ENVfor 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_NOSgrants sysadmin on login. - Every page must start with
await requireRouteAccess("<route pattern>")(src/server/auth/current-user.ts); the pattern must exist inROUTE_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.tsonly redirects requests without a session cookie. - Every Server Action / Route Handler must call
requireRole(...)itself — actions can be invoked directly. Denials useforbidden()→src/app/forbidden.tsx(HTTP 403;experimental.authInterruptsis on). - Application queries must go through
scopeApplications(user, managedDepartmentIds(db, user))(src/server/auth/scope.ts); review permission throughcanReview(only managers of the application's department; self-review allowed but flagged 「主管自行審核」). Creating an application must callrequireDepartment(user). - Org data lives in
src/server/org/(departments, accounts, roster CSV import). Department membership on a date (for headcount snapshots) isdepartmentMembersAt(db, departmentId, "YYYY-MM-DD"), based onuser_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 awithTransactiontx (type-enforced), so the business write and the record succeed or fail together.audit_logsis append-only — DB triggers reject UPDATE/DELETE. before/afterhold only the fields relevant to the action (usechangedFieldsinsrc/server/org/diff.ts); skip the record when nothing changed. Never put tokens or secrets in them.- New action: add
"<target>.<verb>": "中文標籤"toAUDIT_ACTIONS(and a new target type toAUDIT_TARGET_TYPESif needed) insrc/lib/audit-actions.ts— the/admin/audit-logfilters are generated from it. - Server services take an
AuditContextparameter; in Server Actions build it withawait auditContextFor(user)(src/server/audit/action-context.ts, current user + request IP viarequestIp). - Tests:
seedAuditActor(db)+testAuditContext()andexpectAudit(db, action, targetId)/auditRows(...)fromsrc/server/testing/audit.ts. /admin/audit-logis for sysadmins and admins withusers.can_view_audit_log(granted on/admin/accounts); route rules support such flags viagrantsinROUTE_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 insrc/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 insrc/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 — callensureMonthSnapshotsfirst where a snapshot must exist (settlement). Snapshots count members at 00:00 on the 1st (fromuser_department_history). - Settlement submit/return must call
setSnapshotLocked(tx, audit, departmentId, month, locked)inside its transaction. - An initial parameter version is created by
ensureDefaultRuleVersionat startup and in seed.
Applications & attachments
- Application state changes go only through
applyTransition(tx, audit, …)(src/server/applications/lifecycle.ts) insidewithTransaction: it re-reads the status, checks the transition table, actor role and comment, runs an optionalguard, then writes status +application_transitions(timeline, append-only) + audit. New transitions (approve/return/reject, settlement…) are added toTRANSITIONSinsrc/lib/application-lifecycle.tsplus an audit action — never updateapplications.statusdirectly. - 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 recordsrule_version_id; estimates use that version (estimateFor). applications.department_idis 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 marksuperseded_atand keep the file,attachmentCompleteness,authorizeAttachmentRead). Files live underATTACHMENTS_DIRwith random keys and are served only byGET /api/attachments/:id(same 404 for missing/unauthorized). UI:FileUploader/FilePreview(seedocs/ui-guide.md). - Review (
src/server/applications/review.ts,reviewer.ts): reviewers are the managers of the application's department (resolveReviewers/reviewDecision, same data ascanReview); a department without a manager has no reviewer — cases wait and/admin/departmentslists them (user decision: admins never review). Review UI:/department/review(desktop list + detail via?id=) and/department/review/:id(mobile). PassexpectedStatustoapplyTransitionfrom UI actions so races return 「案件狀態已變更,請重新整理」. - E2E: create isolated users with
createEmployee(), or a department with its own manager viacreateTeam(), and ready-to-review cases withinsertPendingApplication()(tests/e2e/db.ts); states from later changes can be simulated there. Shared form steps live intests/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:prepareSettlementMonthpromotes cases and lazily creates snapshots as 「系統」.getSettlementViewreturns the stored result, or a live preview that is not written.recalculateSettlementoverwrites the open trial and records audit.submitCheckandsubmitSettlement: one transaction that recalculates, writes snapshots, moves casessettle→ submitted withfinal_amount, callssetSnapshotLocked, and setsis_late.- Settlements use the rule version effective at calculation time and store it.
- Approved → pending settlement is time-based:
promoteApprovedToPendingSettlementis idempotent. TheSYSTEM_ACTORtransitionpromoteruns it.- Triggers: page open, approve after the deadline (
promoteIfDuein the same transaction), and an hourly timer (startBackgroundJobsinsrc/instrumentation.ts). - After the deadline,
needs_revisioncases can beexpire_rejected. The reason is required.
- Locking after submit:
isSettlementLocked(src/server/settlement/lock.ts) is checked inapplyTransitionand 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-
opensettlements. Onlystatusmay change.
- E2E:
monthsAgo(2)is always past the submission deadline. Control the cap withsetHeadcount(departmentId, month, n)before opening the page.insertPendingApplicationtakescardDate/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 goessubmitted → openand unlocks the snapshot. - Every submit appends a
settlement_submissionsversion. Versions are append-only; return info is written once. finalizeSettlementcreatespayout_records. Only people with final > 0 get one.payoutMonth= card month + 2. Pay item is fixed 「其他獎金」.markPayoutsPaidmoves cases topaid. When all records are paid, the settlement becomespaid.- Payout items leave
pendingonly 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 status:
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 insrc/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 afailedpayout 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_recordsrow (kind,correction_id). Payout list totals count onlypending+paid. - A settlement becomes
paidthroughsettleIfComplete: 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 withPAYOUT_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 insrc/server/applications/duplicates.ts. submitApplicationchecks inside its transaction. If unconfirmed, it returnsduplicatesand writes nothing. The UI showsDuplicateDialogand resubmits withconfirmDuplicate=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.
- The pure rule is
- Notifications (
src/server/notifications/): in-app only, no email.- Event notifications are written inside the business transaction:
applyTransitioncallsnotifyTransition.- The settlement services call
notifySettlement*/notifyPayoutPaid. - New events go in
events.ts, plus a type inNOTIFICATION_TYPES(src/lib/notifications.ts).
- Only the recipient can read a notification.
/notifications/:idmarks it read, then redirects. It returns 404 for anyone else. - The top-bar bell polls the
notificationSummaryserver 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.
- Event notifications are written inside the business transaction:
- Route Handlers must return
new Response(..., { status: 404 }). Don't callnotFound()there: it breaks the response instead of returning 404.
Dashboard
/dashboardis 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:resolveCurrentCycleandquotaReference.quotaReferencereuses the settlementpersonalEligible. - 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.mdbefore building pages. Logged-in pages live undersrc/app/(app)/(shared frame: topbar, role-based sidebar); don't render<main>; start withPageHeader; 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 fromsrc/lib/application-status.ts); shared components insrc/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 usepillClass(active). - Page headers:
PageHeader size="hero"+illustrationonly 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 insrc/lib/platform-display.ts), always next to the text name.
- Buttons: always
- Decorative images:
- Cropped from the mockups by
scripts/crop-mockup-images.tsintopublic/images/, shown viaIllustration. To upgrade, replace the files with higher-resolution ones under the same names. public/images/is excluded from the login redirect insrc/proxy.ts. The Dockerfile copiespublic/into the runtime image (standalone output doesn't).
- Cropped from the mockups by
- 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/*,nextornext/*— enforced by ESLintno-restricted-imports.src/server/— server-only:env.ts(Zod-validated env, fails fast on startup viasrc/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 fromindex.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 withtsx; import./load-envfirst so.envis loaded like Next.js does.- Unit/integration tests live next to the code as
*.test.ts; e2e tests intests/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.