Co-Authored-By: Claude Opus 5.5 <[email protected]>
62 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 reimbursement of work-related AI subscriptions (each person up to 50% of what they paid; when a department exceeds its monthly cap the cap is shared equally) (ChatGPT / Claude / Gemini / other), with manager review, monthly department settlement, and HR/finance final approval (the approved list is exported for payroll).
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/archive/2026-10-20-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 a per-machine Gitea personal access token stored in the system credential helper (wincred), set up with /mason:gitea-access; the old git-credential-oauth browser login was removed 2026-11-11. Never print the token: no git credential fill). 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 mason (formerly vibe-deploy) containerize template — don't hand-edit it; re-run /mason: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): closing the browser hangs, so the run also stalls right after any failed test (the worker restarts). Use --reporter=list to see each result as it lands, look in test-results/ for failures, and kill leftover node …playwright… processes before the next run (stopped runs keep their workers alive).
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/mason: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).- Version:
package.jsonversion(semver; features bump minor, fixes bump patch), read viaAPP_VERSION(src/server/version.ts). It shows at the bottom of the sidebar and in/api/health({"status":"ok","version":…}). Tag the release commitv<version>and push the tag.
Authentication & authorization
- Login is company Authentik OIDC only (
AUTH_MODE=oidc, default), with forced re-authentication (always re-enter credentials). Logout also signs out of the company account (user decision 2026-10-14, replacing the earlier local-only logout), so the next login always asks for the password.- Re-authentication is requested with
max_age=0only. On the production Authentik,prompt=logindid not force it, and sending both mademax_ageineffective too. - The
auth.loginaudit recordsauthTime(ID tokenauth_time),loginStartedAtandreauthenticated(auth_timenot earlier than the login click, 60 s skew allowed). - Logins are not rejected on
auth_timeyet: the first strict version rejected every production login and was reverted. - Company logout follows the vibe platform contract 〈登出公司帳號〉.
vibe.yamldeclaresauth.post_logout_path: /api/auth/logged-out(POST_LOGOUT_PATH; both must match). The platform then registers that URI and thevibe-rp-logoutinvalidation flow.- The OIDC login stores the ID token in
sessions.id_token, server-side only. /api/auth/logoutreads it (sessionIdToken), ends the local session (auth.logoutrecordscompanyLogout), then redirects tocompanyLogoutUrl(discoveryend_session_endpointwithid_token_hintandpost_logout_redirect_uri)./api/auth/logged-outredirects to/login?logout=company.- Without an ID token (sessions from before this change) or an end-session endpoint, only the local session ends, and
/login?logout=localsays the company account was not signed out. - Never build Authentik flow URLs by hand.
- Already-open sessions in other company systems are not ended (no back-channel logout).
- The vibe platform injects
OIDC_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.
- Re-authentication is requested with
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). - Personal data visibility (identity-access「資料範圍控制」; HR Sync does not limit who can see whom, so the app enforces it):
- Employee: only self. Department level shows totals only.
- Department manager: cases and members belonging to departments in
department_managers. Scope followsdepartment_managers, not the role: someone with the manager role but no assignment sees no department. HR secondary managers have no manager role. - Cases are attributed by the case's own department, so cases from before a transfer stay with the old department's manager.
- Admin: company-wide applications and settlements (including the approved-list export). Sysadmin: accounts and settings.
- Per-person full-time status is never shown. The headcount snapshot's base-date member list (admin / sysadmin only) marks non-full-time people (interns, part-timers) as plain 「不計入」 with no reason.
- Every new page, export or API that shows personal data needs a cross-scope case in
tests/e2e/visibility.spec.ts.
- Org data lives in
src/server/org/(departments, accounts, roster CSV import). Department membership on a date (for headcount snapshots) isdepartmentMembersAt(db, departmentId, "YYYY-MM-DD"), based onuser_department_history.
HR Sync (登入時同步姓名、部門與主管)
- Code in
src/server/hr-sync/:token.ts: RFC 8693 token exchange (exchangeHrSyncToken).client.ts: theHrDirectoryinterface plus a fetch implementation for 3 fixed endpoints, with Zod-validated responses.snapshot.ts:fetchHrSnapshot, which runs the queries (plus the user's transfer events) in parallel with a 5 s shared timeout.apply.ts:applyHrSnapshot/recordHrSyncFailure.login.ts: the production fetcher. It attaches the roster query to the snapshot as a non-enumerableroster(attachRoster), so the token never shows up in logs or serialization.employment.ts: full-time status history (hr_employment_history, keyed by employee number).roster.ts: the daily roster sync.divisions.ts:resolveDivision. A system department is an HR unit whoselevelNameis 「部」 (DIVISION_LEVEL_NAME). An employee's unit walks upupperDeptCodeto the nearest 部, or stays itself when no 部 is above it.departments.ts:syncHrDepartments, the roster sync's department step.- Wired into
completeOidcLoginvia itshrSyncoption (set by the callback route).
- Enabled only when
hrSyncConfigured(env):AUTH_MODE=oidc, OIDC configured, and the platform injectedRESOURCE_SERVERSwithhr-sync. That happens only whenvibe.yamldeclaresauth.resource_servers.hr-sync. Invalid JSON only warns. There is no other switch. When enabled, the authorization request addsoffline_access. The refresh token is never stored. - Syncs at login, on the server, for the logged-in employee number from the ID token:
- The HR token is used for this login's sync and, at most once a day, for the roster sync below; then it is discarded. Deactivated accounts and dev login never call HR Sync.
- The snapshot is fetched outside the transaction. It is applied inside
provisionOnLogin's transaction throughafterProvision, in a savepoint, before the session is created. - Any failure (token, query, timeout, bad response, write) still completes the login and records
hr_sync.failed(stage + reason only). A token exchange rejected by Authentik also records the OAuthcode(record-token-exchange-error:oauthErrorCodekeeps only the RFC 6749 / 8693 standard codes, anything else isother, nevererror_description); per the HR Sync manualinvalid_grantmeans the user is inhr-sync-deny(no token at all, not even self data) andinvalid_targetmeans the site's provider is not registered with HR Sync. - Queries that succeed but return unusable data record
hr_sync.incomplete「HR 同步資料不完整」 insideapplyHrSnapshot(record-hr-sync-gaps, after the 2026-11-16 case of a new hire stuck on 待指派部門 with no audit trail):reasons=name_missing(profile without a name),not_active(+status, e.g.NOT_YET_HIRED),no_organization,unit_not_in_tree(+deptCode), plushrDate(the assignment'sdate, i.e. HR SynccoverageTo). Department reasons are judged only when both the assignment and the organization tree were fetched (failures are already inhr_sync.failed). Codes only, never names or response content. Behavior is unchanged.
- Daily roster sync (
runRosterSyncIfDue): the callback route runs it withafter()once the response is sent, using the token from that login.- Runs only if today (Asia/Taipei) has no succeeded run.
claimRosterSyncwrites arunningrow inhr_roster_syncs; arunningrow older than 10 minutes counts as abandoned. - Exception: 「下次登入時重新同步名冊」 on
/admin/settings(headcount tab).requestRosterResyncstores_meta.roster_resync_requested(real time, not system time, and requester) and recordshr_sync.roster_resync_requested.- The request counts as pending until a run succeeds that started after it (
rosterResyncStatus). While it is pending, the next company login runs the sync even if today already succeeded. - It is refused when HR Sync isn't configured.
- Fetches the current roster and organization tree, plus the roster and tree on the 1st of this month and last month (30 s shared timeout). Those dates are snapshot base dates: this month's 1st → last card month, last month's 1st → the card month before (
rebase-headcount-snapshot). - Departments step (one transaction,
syncHrDepartments):- Creates every active 部, renames on HR change, and syncs managers. It never reactivates a department an admin deactivated, and never changes type.
- Cleans up group-level departments: HR-managed departments whose code resolves to another department. Members move with the same effective date (a correction, not a transfer). Cases not yet in a submitted settlement move too (
application.department_corrected). Managers are removed and the department is deactivated (department.hr_deactivated). - A department with a non-
opensettlement is skipped and listed in the summary audit. - A tree with no 部 fails with stage
departments, and nothing is changed.
- Writes full-time history (
employeeGroupCode === "1"). The first record starts at the HR hire date, later changes start today. No record = not full-time. Snapshots read it on the base date (fullTimeOn,exclude-part-time-from-headcount, user decision 2026-11-02: interns and part-timers don't count) — never the roster'semployeeGroupCode, which is the group at query time even for dated queries. With no history rows at all (hasEmploymentDatafalse: dev, e2e, never synced) nobody is excluded. - Creates or updates snapshots with
syncSnapshotsFromHr(tx, audit, cardMonth, rosterOnBaseDate, tree): ACTIVE on the base date, unit resolved to the department through that day's tree (group members count toward their 部). Locked or manually adjusted snapshots are never overwritten. Departments without a code in that roster are skipped. The earlier card month is processed first.- It also stores the 1-day member list in
headcount_snapshot_members(same conditions as the count; a DB trigger rejects writes for a locked snapshot):counted(== the count; ACTIVE and full-time on the base date),excluded(ACTIVE, not full-time; shown without a reason),suspended,offboarded(onlyleaveDate≥ the 1st of the card month). Non-ACTIVE people without a unit fall back to last month's list. A list-only change recordsheadcount.snapshot_members_updated(counts only, no names).listMonthSnapshotsreturnsmembers(local snapshots listdepartmentMembersAtlive; an HR snapshot without a list is null → 「此快照沒有名單紀錄」).
- It also stores the 1-day member list in
- Employment status step (
syncEmploymentStatus,src/server/hr-sync/employment-status.ts, stageemployment_status, after snapshots, current roster): storesusers.hr_status/hr_status_sincefor existing accounts. SUSPENDED / OFFBOARDED + active →deactivateUser(…, hrDeactivated=true)(sessions deleted, department history null fromsuspendedSince/leaveDate, clamped to [last history date, today]) andaccount.hr_deactivated. ACTIVE + inactive +hr_deactivated→activateUser(original department from today) andaccount.hr_reactivated. Manually deactivated accounts are never re-enabled;setAccountActiverefuses to enable an account whose HR status is SUSPENDED / OFFBOARDED (HR_INACTIVE_ACCOUNT_ERROR)./admin/accountsshows HR 狀態 and 「由 HR 停用」. - Each step is its own transaction. A failure stops the run (finished steps are kept) and is recorded in the row (stage + reason, plus
failure_datefor the 1st-of-month roster / tree queries, which share one stage)./admin/settings(headcount tab) shows it viarosterSyncFailureText(src/lib/hr-sync-failure.ts; codes only, never HR response content). Failures write no audit. Success writes onehr_sync.roster_syncedsummary audit, not one per person. - Per-person full-time status is never shown on any page.
- Runs only if today (Asia/Taipei) has no succeeded run.
- HR wins:
- HR name over the ID token name.
- ACTIVE assignment → the unit's 部 (
resolveDivisionover/organizations) → department bydepartments.code, auto-created (type general; admins set 研發) / renamed / reactivated and markedhr_managed. If the organization query failed, the department is left unchanged. Moving between groups inside one 部 is not a transfer. A transfer writesuser_department_historyfrom the HRhr.employee.transferredeffective date (transferEffectiveDate: only events whose new unit resolves to the new department and old unit to a different one; not before the user's last history row and not after today, otherwise today), and setsusers.hr_synced_at. Non-ACTIVE or no organization → department untouched. /organizationsprimary supervisors only (HierachyRelationshipName「主要」, per the HR Sync API manual; secondary ones are ignored) replacedepartment_managersof every activehr_manageddepartment that is its own unit (a 部, or a unit with no 部 above it). Group leaders are not department managers. Unknown employee numbers become not-yet-logged-in users. The manager role is granted, and removed when no longer a manager anywhere.- Audit actor is 「系統(HR 同步)」 (
hrSyncAuditContext). No change → no audit.
- Read-only in admin (services reject too):
hr_manageddepartments: name, code and managers (HR_MANAGED_DEPARTMENT_ERROR). Type and active stay editable.- Users with
hr_synced_at: department (HR_SYNCED_DEPARTMENT_ERROR). - HR managers' manager role (
HR_MANAGER_ROLE_ERROR). - Roster import skips their department column (
hrSkippedin the preview).
- No HR query entry points. Only the callback route (login + roster sync) and the settings page and its actions (roster sync status and resync request only) may import
@/server/hr-sync/*fromsrc/app.client,tokenandsnapshotare server-only (entrypoints.test.tsenforces this).- No page, action or route lets a user name an employee, department or date to query HR.
- Stored HR fields: name, ACTIVE assignment → department (code, name), primary supervisors, and the roster's employee number / name / status / department code / employee group / hire date / leave date / suspended-since (full-time history, snapshot member lists and account status only). Everything else is dropped by the Zod schemas in
client.ts.
- Tests inject a fake
fetchSnapshot/HrDirectory/HrRosterSource. E2E should not inserthr_employment_historyrows (the e2e DB is shared; simulate withmarkSnapshotFromHr/insertRosterSync). E2E (dev login) simulates synced data withcreateHrSyncedTeam()(tests/e2e/db.ts). - HR Sync endpoints and response fields: the API manual in the
hr-syncskill of MoonShineVFX/mason (skills/hr-sync/:references/api-contract.md,references/hr-sync-openapi.json). The copy in the vibe-deploy plugin (moonshine-skills) is kept only for compatibility and no longer maintained.
Audit trail (操作紀錄)
- 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, deadlines, platforms, attachment limits; the subsidy ratio and rounding still live in the parameters). Read them from versioned parameters:
getEffectiveRuleVersion(db, at)/requireEffectiveRuleVersion(src/server/rules/params.ts); the schema and defaults are 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. - Snapshot base date (
rebase-headcount-snapshot, user decision 2026-10-30): card month M uses the 1st of month M+1 at 00:00 (snapshotBaseDate/baseDateReached/capPendingMessageinsrc/domain/deadlines.ts) — employees apply in the following month, so people who left by the end of M no longer count. Before the base date no snapshot can be created (ensureMonthSnapshots/createDepartmentSnapshotfail with 「YYYY/MM/01 名冊確定後計算」), and the review cap preview, dashboardQuotaCard(message) and settlement show that text. Only people full-time on the base date count (hr_employment_history; interns / part-timers excluded, nobody excluded while there is no history at all). A one-time startup steprebaseHeadcountSnapshots(_metaheadcount_base_next_month) deleted unlocked, unadjusted snapshots whose base date had not arrived (headcount.snapshot_removed). - Department cap:
getDepartmentCap(db, departmentId, month, tz)is read-only and returns 「尚未建立人數快照」 when missing — callensureMonthSnapshotsfirst where a snapshot must exist (settlement). Snapshots count members at 00:00 on the base date (fromuser_department_history;localHeadcount). Snapshots have asource(local/hr); the daily HR roster sync replaces unlocked, unadjusted ones with the HR count. - Settlement submit/return must call
setSnapshotLocked(tx, audit, departmentId, month, locked)inside its transaction. - An initial parameter version is created by
ensureDefaultRuleVersionat startup and in seed. - Personal cap 50% (2026-10-20 rule correction, replacing the 2026-10-14 full subsidy):
subsidyRatePercentis 50, roundingfloor.ensureHalfSubsidyVersion(startup and seed, right afterensureDefaultRuleVersion) adds a 50% / floor version as 「系統」 when the effective one differs, so older settlements keep their 100% (or earlier 50%) snapshot.- The settings page has no ratio or rounding fields.
saveParamsActioncarries over the predecessor's values (withCarriedOverRate) and ignores the form.
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. - No estimated subsidy is shown anywhere for employees: before settlement the amount reads 「月結後確認」.
applications.department_idis the department the applicant belonged to on the snapshot base date (the 1st of the month after the card month).- No current-month claims: a card month M application can be submitted only from the 1st of M+1 (
deadlinesFor(...).start,submissionOpensAt;submitApplicationreturns 「此筆刷卡日期屬於 YYYY/MM,YYYY/MM/01 起才能送出。」). Drafts can be saved any time; the form shows 「可送出期間」 and disables 送出 before the start.- Rule:
attributedDepartment(src/domain/attribution.ts), falling back to the department on the card date, then the current one. History comes fromdepartmentHistoryOf. - Recomputed on create, save and submit while editable; fixed once submitted, and never follows later transfers.
applyTransitionnotifies and lock-checks the post-patch department.- The form shows the same attribution live. Deleting a never-submitted draft is a soft delete (
deleted_at); deleted drafts don't exist for queries (getApplicationDetail,getApplicationAccess).
- Rule:
- Withdraw:
withdrawBlocker(lifecycle.ts: not yet reviewed and settlement not locked) decides the detail button;withdrawableIdsbatches the same check for the 「我的申請」 list, which has a 「撤回修改」 action per row (WithdrawButton). The detail page has one 「撤回並修改」 button (page header) and a text-only hint below the status explaining how to edit before review (clarify-edit-after-submit, user decision 2026-11-13: colleagues thought submitted cases could not be edited). A successful withdraw navigates to/applications/:id/editwith a 「修改後請再按「送出」」 toast; audit and timeline labels stay 「撤回」.ConfirmDialog.onConfirmmay return an error string (shown in the dialog) and thrown errors are shown too. - New application form: the first upload creates the draft once (
ensureApplicationIdkeeps the id and the in-flight request in refs); 儲存草稿/送出 are disabled while anyFileUploaderreports busy (onBusyChange). - 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). - Attachment retention (
attachment-retention, user decision 2026-11-12):runAttachmentRetention(src/server/attachments/retention.ts,startRetentionScheduler: startup + hourly, idempotent, ≤ 50 department-months per run) deletes the files of every case of a (department, card month) once its settlement isfinalized(or legacypaid) and the Taipei finalized date + 3 months is reached; a month with no settleable case (only rejected / withdrawn / drafts) and no submitted-or-later settlement goes on the 1st of M+5. Open / submitted settlements or still-pending cases block it. Rules and constants insrc/lib/attachment-retention.ts(a policy, not a rule param). Uses real time (realNow()), so system clock adjustments never purge early. Rows stay (attachments.purged_at; sha256 kept for duplicate detection); files are removed after the commit; oneattachment.retention_purgedaudit per department-month (actor 「系統(附件保存期限)」). Purged attachments return 404 fromauthorizeAttachmentRead,FilePreviewshows 「附件已依保存期限刪除(日期)」, and storage usage lists them separately (attachments.purged). - 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). PassexpectedStatustoapplyTransitionfrom UI actions so races return 「案件狀態已變更,請重新整理」. After the employee deadline of the case's card month (system time),returnis refused (returnBlockedReason, checked inreviewApplication's guard) and the review UI hides 退回補件 with that message: the employee could not resubmit anyway. - Review UI (
/department/review):- Desktop default
?view=list: a table (review-table.tsx, ≥ xl) with row expansion, attachment previews and in-row approve / return / reject.- Return and reject use
ReasonDialog; reject adds itsconfirmStep. - Rows can be ticked for batch approve. 「已勾選 N 筆」 and 「批次核准」 sit top-left, on the checkbox side.
DataTable sticky={{ first, last }}pins the checkbox + 申請人 columns left and the 操作 column right while scrolling sideways (view-only tabs pin 申請人 only).
- Return and reject use
?view=detail: the two-column workbench, where?id=selects a case. A bare?id=also opens it. The right detail pane is sticky under the top bar and scrolls on its own (keyed by the case id, so it resets to the top).- Card-month filter
?month=YYYY-MM|all(reviewQueueMonths;listReviewQueue/reviewQueueCountstake the month): default is the earliest month with cases in the current tab, or the case's month for a bare?id=; tab counts, list, batch approve and cap summaries follow the month; links keep it. - Narrow screens: a card list, plus
/department/review/:id. - Above the lists, and in the detail: 部門額度試算 per (department, card month).
reviewCapPreview/reviewCapPreviewscover pending + approved + pending-settlement cases, using the settlement calculation (equal share, current adjustments) with the current params (read-only; creates a missing snapshot once the base date has passed; before that it shows 「YYYY/MM/01 名冊確定後計算」).- Shown with
ReviewCapSummaryandMoneyDisplay kind="preview"「試算」. A submitted month shows final amounts. - 已核准, 待審 and 合計 are personal-cap sums (each case × 50%, floored per case), so 已核准 + 待審 = 合計. 合計 is
totalEligible, not affected by adjustments, the same base as 超出 (user decisions 2026-10-16 / 2026-10-20). Each case's 試算 is ≤ 50% of that case. When over, 合計 and the 超出 amount turntext-danger.
- Desktop default
- 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(= the personal cap,Allocation.personalCap): each case × ratio, rounded per case, then summed (655 + 655 → 327 + 327 = 654; user decision 2026-10-20). Per-case rounding keeps every split total consistent.shareWithinCap(equal share, user decision 2026-10-15, replacing the spec's pro-rata §7.4):- 超額 is judged on the personal-cap total Σ cap (
totalEligible, user decision 2026-10-20), never on adjusted amounts;overAmount= cap total − department cap. With the 100% ratio this was the paid total. - Internally the split uses Σ (override ?? personal cap): at or under the cap everyone gets it (same result, since overrides ≤ personal cap).
- Over the cap: overridden people keep their override; the rest split
cap − Σ overridesequally, each capped at their own personal cap (smaller ones take their cap, the rest is re-split). - Leftover yuan (
remainder+1) go by employee number ascending (order), so the total == cap.
- 超額 is judged on the personal-cap total Σ cap (
- 個人可補助 == 最終補助 now (no second proportional step).
systemEligibleof an overridden person = the result with only their own override removed. overridesExceedCap(Σ overrides > cap, e.g. the cap shrank later) blocks submit withOVERRIDES_EXCEED_CAP_MESSAGE;overridesExceedPaid(an override > that person's personal cap, left from before the limit) blocks withOVERRIDES_EXCEED_PAID_MESSAGEand marks the row 「超過個人上限」.splitAcrossApplications(final, amounts, rate): per-case final amounts, split in proportion to each case's own cap; every case ≤ its cap, and at or under the cap each case gets exactly its 50%.- 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. For a stored open trial it also computes the live data: 支付金額 is always live, rows whose paid total changed (or new applicants,newApplicant) arestale, andneedsRecalcshows the 「請按「重新計算」」 prompt (also when the trial's ratio or rounding differs from the effective version); 個人可補助 stays the trial value until recalculation.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.
- Manual adjustment of 個人可補助 (
adjustEligible, department pageAdjustEligible, open settlements only, reason required):- Stored append-only in
settlement_eligible_overrides; the latest row per (department, month, user) wins, andamountnull means restored. calculatepasses it tocalculateSettlementaseligibleOverride, so it survives recalculation and is used at submit.- An override must be ≤ that person's personal cap (
adjustOverPaidMessage), and the sum of all overrides ≤ the cap (adjustOverCapMessage); restoring is never limited. - Allocations keep
system_eligible.AllocationTableshows 「已調整」, the system value and the reason, also on the admin detail (read-only). - The audit action is
settlement.eligible_adjusted. - The quota block shows four stats: 計算人數|月上限|補助合計|超額 (no 「每人額度」, no 「可補助總額」; the admin detail keeps 每人額度 in its parameter snapshot). 補助合計 is the personal-cap total (
totalEligible, live for an open trial; user decision 2026-10-20); 超額 = 補助合計 − cap and turnstext-dangerwhen it is > 0. The paid total appears only in the allocation table's total row, which starts with 「核准人數 N 人」 (add-approved-count: the number of allocation rows, i.e. people with approved cases that month, new applicants included; also on the admin detail). 「支付金額(當月合計)」 is the person's sum of approved cases. AllocationTableand the department CSV preview have a 「個人上限(50%)」 column (settlement_allocations.personal_cap; rows from before it are null and show 「—」).- The department CSV preview (
department/settlement/export/route.ts) and the admin approved list share one settlement sheet (unify-settlement-sheet, user decision 2026-10-29):SETTLEMENT_SHEET_COLUMNS/departmentSheetRows/sheetCellsinsrc/lib/settlement-sheet.ts— 刷卡月份, 發放月份 (card month + 2), 部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例 (final ÷ cap), 最終補助, 尾差調整, then a 「部門合計」 row (format from the user, 2026-10-22). The preview usesdisplaycells (NT$ text, same as the page); new applicants leave the calculated columns blank.
- Stored append-only in
- The allocation table's 「占月上限」 column (page, admin detail, CSV) is final ÷ cap (
capShareBp, computed at display time; 「—」 when the cap is 0). The storedshare_bpis final ÷ cap too (not shown). - 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: the system clock is pinned to the 10th of the current month (see System clock), so
monthsAgo(1)is inside the submission window (1st–20th) with its snapshot base date passed,monthsAgo(2)is always past the submission deadline, and the current month cannot be submitted and has no cap. Control the cap withsetHeadcount(departmentId, month, n)before opening the page.insertPendingApplicationtakescardDate(defaultclaimDate(5), last month) /twdAmount/status. - Admin side (
src/server/settlement/company.ts,payouts.ts; pages/admin/settlements,/admin/settlements/:departmentId/:month,/admin/settlements/export). Admin role only; the services also check it.- Overdue forced submit (
force-submit-overdue-settlement, user decision 2026-10-30): after the manager deadline an admin can 「代為提交」 next to the 「逾期未提交」 badge on the/admin/settlementsoverview (force-submit-button.tsx; moved from the detail page, user decision 2026-10-30;forceSubmitSettlementmodeadmin, reason required,ReasonDialog+confirmStep); when the rule paramautoSubmit.enabled(default off,graceDays0–10, default 3, read from the version effective now) is on, the hourly settlement scheduler (runAutoSubmit,auto-submit.ts) submits overdue departments with at least one non-draft case in the previous 1–2 card months after deadline + grace days (modeauto, actorSYSTEM_ACTOR, label 「系統(自動提交)」). Both sharesubmitInTxwith the manager submit: pending-review / needs-revision cases first go through theoverdue_rejecttransition (actor admin or system, system comment) and stay rejected after a later return; overrides over the cap/personal cap block (auto skips the department and sendsreminder.auto_submit_failedonce a day per month).submission_mode/submission_reasonondepartment_settlementsandsettlement_submissions; managers getsettlement.force_submitted; auditssettlement.proxy_submitted/settlement.auto_submitted. Managers' own submit is still blocked by unreviewed cases. - Settlement status:
open → submitted → finalized. Final approval is the end (remove-payout-management, user decision 2026-10-28): no payout tracking, nopaidtransition, no corrections. A return goessubmitted → openand unlocks the snapshot; a finalized settlement can't be returned or corrected. - Every submit appends a
settlement_submissionsversion. Versions are append-only; return info is written once. finalizeSettlementmoves cases tofinalizedand notifies applicants (final amount, expected payout month = card month + 2, pay item 「其他獎金」). It creates no payout records.- Multi-step settlement writes use
abortableTransaction+SettlementAbort(src/server/settlement/transaction.ts), so a mid-way failure rolls everything back. - 「匯出核定名單」 on
/admin/settlements(approvedSheetRowsinpayouts.ts): the same settlement sheet for every finalized (or legacypaid) department of the selected card month, sorted by name, each with all its members (including 0) and its 「部門合計」 row (from the storedgetSettlementView), then one 「全公司合計」 row (share blank).numericcells: Excel (exceljs) number cells formatted"NT$"#,##0/0.00%, totals bold; CSV plain integers. No 薪資名目 column (always 其他獎金). Columns are documented indocs/operations/payout-export.md(a test keeps them in sync). Auditpayout.exported(「匯出核定名單」,rows= member rows).
- Overdue forced submit (
- Legacy data from the removed payout management and settlement corrections:
paidcases/settlements still show 「已發放」 and stay read-only;payout_recordsandsettlement_correctionskeep their rows and triggers (still inBUSINESS_TABLES) but nothing reads or writes them; their status/type enums, thepaytransition action (timeline label only), thepayout.paidnotification type and the old audit actions stay only so old rows still display. - Dialogs that need a reason use
ReasonDialog(src/components/ui/reason-dialog.tsx).
Data reset (清除業務資料)
/admin/settings?tab=maintenanceis visible to sysadmins only;clearBusinessDataActionchecksrequireRole("sysadmin").- Double confirmation (
confirm-clear-business-data, user decision 2026-10-29): the dialog (ReasonDialogwithcanConfirm) needs a reason and the typed phraseCLEAR_CONFIRM_PHRASE(「清除業務資料」,src/lib/data-reset.ts).clearBusinessDataWithBackupchecks both again (clearConfirmationError) before backing up; the reason is thedata.business_clearedaudit comment. clearBusinessDataWithBackup(src/server/maintenance/clear-business-data.ts):- Backs up first, to
<dirname(DATABASE_PATH)>/backups/(inside the persisted volume). A failed backup means nothing is cleared. clearBusinessDatathen runs one transaction overBUSINESS_TABLES(applications, attachments, transitions, notifications, settlements and their allocations / submissions / eligible overrides, legacy payouts and corrections, headcount snapshots and adjustments):- reads the tables' trigger SQL from
sqlite_master, drops the triggers, deletes the rows (defer_foreign_keysfor the payout ↔ correction cycle), recreates the triggers; - records
data.business_cleared.
- reads the tables' trigger SQL from
- Attachment files are deleted only after the commit.
- Backs up first, to
- Kept: accounts and roles, departments and managers, department history, rule versions, HR employment and roster syncs, audit log, sessions.
- A new business table must be added to
BUSINESS_TABLES, or it survives a clear. - Storage usage (same tab,
storageUsageinsrc/server/maintenance/storage-usage.ts, computed live): disk free/total viastatfson the database directory (「剩餘空間不足」 belowDISK_LOW_RATIO15%, checked only when the page renders, no background alert), database + WAL, active / stale / purged attachments, pre-clear backups (deletable one at a time,data.backup_deleted), and a 6-month 「每月新增附件」 bar chart (monthly: this month so far + the 5 before, Taipei upload month, including later superseded / purged files, zeros kept;monthly-additions-chart.tsx, server-rendered, no chart library). No average or yearly estimate (user decision 2026-11-13).
System clock (系統時間)
- Business "now" = real time + an offset a sysadmin sets on
/admin/settings?tab=clock(for pilot testing deadlines and settlements; works in production too). The offset lives in_metakeyclock_offset, is read on every call (no cache) and survives restarts; time keeps moving after an adjustment. 「同步」 clears the offset. Both need a reason and recordsystem.clock_adjusted/system.clock_synced. src/server/clock.ts:appNow()is the business now.realNow()andsystemTimeAt(real)are for code that needs both.setClock/syncClockare the writes (±366 days).
- New code takes "now" from
appNow()oraudit.now, nevernew Date()/Date.now().src/server/clock-usage.test.tsenforces this. Its allowlist uses real time on purpose: login / logout / session (current-user.ts), backups, the HR roster daily check, seed,ensureHalfSubsidyVersion, and the form-state key inapplications/actions.ts. auditContextForgivesnow(system time) andrealNow.recordAuditwritesoccurred_atas real time and, when they differ,simulated_atas system time (/admin/audit-logshows 「系統時間 …」). Contexts rebuilt from another context must carryrealNowover (seesystemContextin the settlement service). The schedulers pass both.- While adjusted,
(app)/layout.tsxpassesclockNoticetoAppFrame. Every page then shows 「系統時間已調整為 …(真實時間 …)」, and sysadmins also get a link to the tab. - Clearing business data keeps the offset.
- E2E: the
pin-clocksetup project (tests/e2e/pin-clock.setup.ts,pinSystemClockindb.ts) sets the offset to the 10th of the current month at 12:00 Taipei before thechromiumproject, and its teardown clears it. Test code usestoday()(the pinned system date) andclaimDate()(last month, submittable) fromdb.ts;monthsAgofollows the real month (unchanged by the pin).tests/e2e/clock.spec.tsruns in its own Playwright project (clock) after all other tests and clears the offset before and after (clearClockOffset). No spec may set it otherwise.
Duplicate detection & notifications
- Duplicate detection:
- The pure rule is
findDuplicates(src/domain/duplicates.ts). Server side lives insrc/server/applications/duplicates.ts. - Rule (user decision 2026-10-20): same applicant and (platform + card date + TWD amount all equal → reason
fields, or the Invoice file content equal →invoice). Card statements are not compared: one statement often lists several subscriptions. Old flags may carryattachment(any file equal); they are shown as 「附件相同」 and never recomputed. - Texts live in
src/lib/duplicates.ts(DUPLICATE_WARNING,DUPLICATE_REASON_LABELS); the dialog and the 「疑似重複」 notice list each matched case's reasons. 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*. - 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. - Pending-review notifications follow the case:
- When a case leaves
pending_review(approve, return, reject, withdraw…),notifyTransitioncallsclearPendingReview, which marks every recipient's unread pending-review notification for that case as read. Nothing is deleted. clearStalePendingReviewsruns once at startup and is idempotent.- After a review, the review UI dispatches
notifications:changed, so the bell updates without a page change.
- When a case leaves
- Zulip direct messages (
zulip-notifications+zulip-reject-and-settlement-reminder, user decisions 2026-11-11): onlyapplication.pending_review,application.returned,application.rejectedandreminder.settlement_open(CHAT_NOTIFICATION_TYPES) are also sent as Zulip DMs, to the recipient's account email, by an incoming-webhook bot.notifications.chat_status(NULL = pending) /chat_attempts/chat_atmake the table the outbox; no audit for these technical fields.runChatDispatch(src/server/notifications/zulip.ts) runs at startup and every minute (startChatScheduler), after the business transaction: rows from the last 24 h only (no backlog), pending reviews already read (case reviewed) and recipients without email / inactive areskipped, the rest are merged per (recipient, type) into one message — reviews list applicant + case number (first 10), returns / rejections carry the latestreturn/reject|expire_reject|overdue_rejectcomment in full (@neutralized), settlement reminders list one line per department from the notification's own title and body. No amounts. Network errors / 429 / 5xx retry up to 3 times, thenfailed;400 Invalid email→skipped. Failures only log.- Config:
ZULIP_SITE,ZULIP_BOT_EMAIL,ZULIP_API_KEY(+APP_URLfor links;zulipConfigured) — all required invibe.yaml, values in.env.deploy; missing → no scheduler, a startup warning, in-app only.ZULIP_DELIVERY=dry-run(local only, never invibe.yaml) logs instead of sending. Never print the API key.
- 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).reminder.settlement_open: the day after the employee deadline (default the 21st, derived from params), managers of unsubmitted departments with at least one submitted case (pending review / needs revision / approved / pending settlement) in that card month get 「{部門} {月} 月結請於 {截止日} 前提交」 with the three counts. The 3- and 1-dayreminder.manager_deadlinestay in-app only.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. The employee and manager cards show the previous card month (quotaMonth, the month being applied for now; the current month's cap is only known from the 1st of next month —rebase-headcount-snapshot). Its 「參考」 tag and explanation are built in; never show a bare "remaining quota". - Show case amounts through
SubsidyAmount: 「月結後確認」 before submission (no estimate), 最終 after. The employee section has no month estimate. The admin 「全公司預估補助」 stays.
UI (app-shell)
- 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
/helprenders the 主管 / 管理端 sections only for users with any role besides employee (show-help-by-role).- 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, duplicate-detection, notifications, dashboard, hr-sync, system-clock 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 from the 1st to the 20th of the following month (no current-month claims); department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
- Personal amount: 支付金額 = sum of the month's approved TWD amounts; the personal cap is 50% of it, floored per case (rule corrected 2026-10-20; settlements between 2026-10-14 and then used 100%). TWD amount from the card statement is the basis; foreign-currency amount is reference only.
- Department monthly cap = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a monthly snapshot taken on the 1st of the month after the card month (active full-time staff; interns and part-timers don't count), not live headcount. Unused quota does not carry over.
- Over cap → equal share (user decision 2026-10-15, replacing the spec document's pro-rata): adjusted people keep their adjusted amount, the rest split
cap − adjusted totalequally, nobody above their own personal cap; leftover yuan go by employee number. The total never exceeds the cap (paid 900/1,700 → caps 450/850, with cap 1,000 → 450/550). Submitted settlements keep their stored results. - Approval ≠ payout. Managers review work purpose only; amounts are settled at month end across all approved cases. UI must never make the quota look first-come-first-served, and must not show employees an amount before settlement (「月結後確認」), only 「最終」 after.
- Statuses: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 (end; legacy rows may be 已發放); plus 撤回. Return/reject require a comment.
- Locking & audit: after a department head submits settlement, data is locked; changes go through an admin return before final approval; after final approval nothing changes. Never overwrite history. Snapshots, parameters and settlement results must be versioned/retained; every state transition logs actor and time.
- Rule parameters (per-person quota, deadlines, platforms, attachment limits) are admin-configurable, not hard-coded. The ratio (50%) and rounding (floor) are versioned but not editable.
Roles
Employee, department manager/head (own department only), admin / HR-finance (all departments, final approval, approved-list export for payroll; 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|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) require a confirm dialog. Planned shared components: StatusBadge, MoneyDisplay, MonthPicker, FileUploader, FilePreview, ReviewTimeline, QuotaCard, ConfirmDialog, EmptyState, ErrorSummary.