Files

62 KiB
Raw Permalink 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 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 (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 /mason: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).
  • Version: package.json version (semver; features bump minor, fixes bump patch), read via APP_VERSION (src/server/version.ts). It shows at the bottom of the sidebar and in /api/health ({"status":"ok","version":…}). Tag the release commit v<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=0 only. On the production Authentik, prompt=login did not force it, and sending both made max_age ineffective too.
    • The auth.login audit records authTime (ID token auth_time), loginStartedAt and reauthenticated (auth_time not earlier than the login click, 60 s skew allowed).
    • Logins are not rejected on auth_time yet: the first strict version rejected every production login and was reverted.
    • Company logout follows the vibe platform contract 〈登出公司帳號〉.
      • vibe.yaml declares auth.post_logout_path: /api/auth/logged-out (POST_LOGOUT_PATH; both must match). The platform then registers that URI and the vibe-rp-logout invalidation flow.
      • The OIDC login stores the ID token in sessions.id_token, server-side only.
      • /api/auth/logout reads it (sessionIdToken), ends the local session (auth.logout records companyLogout), then redirects to companyLogoutUrl (discovery end_session_endpoint with id_token_hint and post_logout_redirect_uri).
      • /api/auth/logged-out redirects 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=local says 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_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).
  • 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 follows department_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) is departmentMembersAt(db, departmentId, "YYYY-MM-DD"), based on user_department_history.

HR Sync (登入時同步姓名、部門與主管)

  • Code in src/server/hr-sync/:
    • token.ts: RFC 8693 token exchange (exchangeHrSyncToken).
    • client.ts: the HrDirectory interface 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-enumerable roster (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 whose levelName is 「部」 (DIVISION_LEVEL_NAME). An employee's unit walks up upperDeptCode to the nearest 部, or stays itself when no 部 is above it.
    • departments.ts: syncHrDepartments, the roster sync's department step.
    • Wired into completeOidcLogin via its hrSync option (set by the callback route).
  • Enabled only when hrSyncConfigured(env): AUTH_MODE=oidc, OIDC configured, and the platform injected RESOURCE_SERVERS with hr-sync. That happens only when vibe.yaml declares auth.resource_servers.hr-sync. Invalid JSON only warns. There is no other switch. When enabled, the authorization request adds offline_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 through afterProvision, 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 OAuth code (record-token-exchange-error: oauthErrorCode keeps only the RFC 6749 / 8693 standard codes, anything else is other, never error_description); per the HR Sync manual invalid_grant means the user is in hr-sync-deny (no token at all, not even self data) and invalid_target means the site's provider is not registered with HR Sync.
    • Queries that succeed but return unusable data record hr_sync.incomplete 「HR 同步資料不完整」 inside applyHrSnapshot (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), plus hrDate (the assignment's date, i.e. HR Sync coverageTo). Department reasons are judged only when both the assignment and the organization tree were fetched (failures are already in hr_sync.failed). Codes only, never names or response content. Behavior is unchanged.
  • Daily roster sync (runRosterSyncIfDue): the callback route runs it with after() once the response is sent, using the token from that login.
    • Runs only if today (Asia/Taipei) has no succeeded run. claimRosterSync writes a running row in hr_roster_syncs; a running row older than 10 minutes counts as abandoned.
    • Exception: 「下次登入時重新同步名冊」 on /admin/settings (headcount tab).
      • requestRosterResync stores _meta.roster_resync_requested (real time, not system time, and requester) and records hr_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-open settlement 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's employeeGroupCode, which is the group at query time even for dated queries. With no history rows at all (hasEmploymentData false: 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 (only leaveDate ≥ the 1st of the card month). Non-ACTIVE people without a unit fall back to last month's list. A list-only change records headcount.snapshot_members_updated (counts only, no names). listMonthSnapshots returns members (local snapshots list departmentMembersAt live; an HR snapshot without a list is null → 「此快照沒有名單紀錄」).
    • Employment status step (syncEmploymentStatus, src/server/hr-sync/employment-status.ts, stage employment_status, after snapshots, current roster): stores users.hr_status / hr_status_since for existing accounts. SUSPENDED / OFFBOARDED + active → deactivateUser(…, hrDeactivated=true) (sessions deleted, department history null from suspendedSince / leaveDate, clamped to [last history date, today]) and account.hr_deactivated. ACTIVE + inactive + hr_deactivated → activateUser (original department from today) and account.hr_reactivated. Manually deactivated accounts are never re-enabled; setAccountActive refuses to enable an account whose HR status is SUSPENDED / OFFBOARDED (HR_INACTIVE_ACCOUNT_ERROR). /admin/accounts shows 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_date for the 1st-of-month roster / tree queries, which share one stage). /admin/settings (headcount tab) shows it via rosterSyncFailureText (src/lib/hr-sync-failure.ts; codes only, never HR response content). Failures write no audit. Success writes one hr_sync.roster_synced summary audit, not one per person.
    • Per-person full-time status is never shown on any page.
  • HR wins:
    • HR name over the ID token name.
    • ACTIVE assignment → the unit's 部 (resolveDivision over /organizations) → department by departments.code, auto-created (type general; admins set 研發) / renamed / reactivated and marked hr_managed. If the organization query failed, the department is left unchanged. Moving between groups inside one 部 is not a transfer. A transfer writes user_department_history from the HR hr.employee.transferred effective 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 sets users.hr_synced_at. Non-ACTIVE or no organization → department untouched.
    • /organizations primary supervisors only (HierachyRelationshipName 「主要」, per the HR Sync API manual; secondary ones are ignored) replace department_managers of every active hr_managed department 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_managed departments: 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 (hrSkipped in 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/* from src/app. client, token and snapshot are server-only (entrypoints.test.ts enforces 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 insert hr_employment_history rows (the e2e DB is shared; simulate with markSnapshotFromHr / insertRosterSync). E2E (dev login) simulates synced data with createHrSyncedTeam() (tests/e2e/db.ts).
  • HR Sync endpoints and response fields: the API manual in the hr-sync skill 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 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, 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 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.
  • 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 / capPendingMessage in src/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 / createDepartmentSnapshot fail with 「YYYY/MM/01 名冊確定後計算」), and the review cap preview, dashboard QuotaCard (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 step rebaseHeadcountSnapshots (_meta headcount_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 — call ensureMonthSnapshots first where a snapshot must exist (settlement). Snapshots count members at 00:00 on the base date (from user_department_history; localHeadcount). Snapshots have a source (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 ensureDefaultRuleVersion at startup and in seed.
  • Personal cap 50% (2026-10-20 rule correction, replacing the 2026-10-14 full subsidy):
    • subsidyRatePercent is 50, rounding floor. ensureHalfSubsidyVersion (startup and seed, right after ensureDefaultRuleVersion) 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. saveParamsAction carries 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) 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.
  • No estimated subsidy is shown anywhere for employees: before settlement the amount reads 「月結後確認」.
  • applications.department_id is 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; submitApplication returns 「此筆刷卡日期屬於 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 from departmentHistoryOf.
    • Recomputed on create, save and submit while editable; fixed once submitted, and never follows later transfers.
    • applyTransition notifies 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).
  • Withdraw: withdrawBlocker (lifecycle.ts: not yet reviewed and settlement not locked) decides the detail button; withdrawableIds batches 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/edit with a 「修改後請再按「送出」」 toast; audit and timeline labels stay 「撤回」. ConfirmDialog.onConfirm may return an error string (shown in the dialog) and thrown errors are shown too.
  • New application form: the first upload creates the draft once (ensureApplicationId keeps the id and the in-flight request in refs); 儲存草稿/送出 are disabled while any FileUploader reports 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 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).
  • 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 is finalized (or legacy paid) 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 in src/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; one attachment.retention_purged audit per department-month (actor 「系統(附件保存期限)」). Purged attachments return 404 from authorizeAttachmentRead, FilePreview shows 「附件已依保存期限刪除(日期)」, 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 as canReview); a department without a manager has no reviewer — cases wait and /admin/departments lists them (user decision: admins never review). Pass expectedStatus to applyTransition from UI actions so races return 「案件狀態已變更,請重新整理」. After the employee deadline of the case's card month (system time), return is refused (returnBlockedReason, checked in reviewApplication'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 its confirmStep.
      • 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).
    • ?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 / reviewQueueCounts take 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 / reviewCapPreviews cover 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 ReviewCapSummary and MoneyDisplay 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 turn text-danger.
  • 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 (= 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 − Σ overrides equally, 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.
    • 個人可補助 == 最終補助 now (no second proportional step). systemEligible of an overridden person = the result with only their own override removed.
    • overridesExceedCap (Σ overrides > cap, e.g. the cap shrank later) blocks submit with OVERRIDES_EXCEED_CAP_MESSAGE; overridesExceedPaid (an override > that person's personal cap, left from before the limit) blocks with OVERRIDES_EXCEED_PAID_MESSAGE and 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:
    • prepareSettlementMonth promotes cases and lazily creates snapshots as 「系統」.
    • getSettlementView returns 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) are stale, and needsRecalc shows the 「請按「重新計算」」 prompt (also when the trial's ratio or rounding differs from the effective version); 個人可補助 stays the trial value until recalculation.
    • 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.
  • Manual adjustment of 個人可補助 (adjustEligible, department page AdjustEligible, open settlements only, reason required):
    • Stored append-only in settlement_eligible_overrides; the latest row per (department, month, user) wins, and amount null means restored.
    • calculate passes it to calculateSettlement as eligibleOverride, 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. AllocationTable shows 「已調整」, 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 turns text-danger when 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.
    • AllocationTable and 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 / sheetCells in src/lib/settlement-sheet.ts — 刷卡月份, 發放月份 (card month + 2), 部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例 (final ÷ cap), 最終補助, 尾差調整, then a 「部門合計」 row (format from the user, 2026-10-22). The preview uses display cells (NT$ text, same as the page); new applicants leave the calculated columns blank.
  • The allocation table's 「占月上限」 column (page, admin detail, CSV) is final ÷ cap (capShareBp, computed at display time; 「—」 when the cap is 0). The stored share_bp is final ÷ cap too (not shown).
  • 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: 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 with setHeadcount(departmentId, month, n) before opening the page. insertPendingApplication takes cardDate (default claimDate(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/settlements overview (force-submit-button.tsx; moved from the detail page, user decision 2026-10-30; forceSubmitSettlement mode admin, reason required, ReasonDialog + confirmStep); when the rule param autoSubmit.enabled (default off, graceDays 0–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 (mode auto, actor SYSTEM_ACTOR, label 「系統(自動提交)」). Both share submitInTx with the manager submit: pending-review / needs-revision cases first go through the overdue_reject transition (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 sends reminder.auto_submit_failed once a day per month). submission_mode / submission_reason on department_settlements and settlement_submissions; managers get settlement.force_submitted; audits settlement.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, no paid transition, no corrections. A return goes submitted → open and unlocks the snapshot; a finalized settlement can't be returned or corrected.
    • Every submit appends a settlement_submissions version. Versions are append-only; return info is written once.
    • finalizeSettlement moves cases to finalized and 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 (approvedSheetRows in payouts.ts): the same settlement sheet for every finalized (or legacy paid) department of the selected card month, sorted by name, each with all its members (including 0) and its 「部門合計」 row (from the stored getSettlementView), then one 「全公司合計」 row (share blank). numeric cells: Excel (exceljs) number cells formatted "NT$"#,##0 / 0.00%, totals bold; CSV plain integers. No 薪資名目 column (always 其他獎金). Columns are documented in docs/operations/payout-export.md (a test keeps them in sync). Audit payout.exported (「匯出核定名單」, rows = member rows).
  • Legacy data from the removed payout management and settlement corrections: paid cases/settlements still show 「已發放」 and stay read-only; payout_records and settlement_corrections keep their rows and triggers (still in BUSINESS_TABLES) but nothing reads or writes them; their status/type enums, the pay transition action (timeline label only), the payout.paid notification 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=maintenance is visible to sysadmins only; clearBusinessDataAction checks requireRole("sysadmin").
  • Double confirmation (confirm-clear-business-data, user decision 2026-10-29): the dialog (ReasonDialog with canConfirm) needs a reason and the typed phrase CLEAR_CONFIRM_PHRASE (「清除業務資料」, src/lib/data-reset.ts). clearBusinessDataWithBackup checks both again (clearConfirmationError) before backing up; the reason is the data.business_cleared audit 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.
    • clearBusinessData then runs one transaction over BUSINESS_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_keys for the payout ↔ correction cycle), recreates the triggers;
      • records data.business_cleared.
    • Attachment files are deleted only after the commit.
  • 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, storageUsage in src/server/maintenance/storage-usage.ts, computed live): disk free/total via statfs on the database directory (「剩餘空間不足」 below DISK_LOW_RATIO 15%, 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 _meta key clock_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 record system.clock_adjusted / system.clock_synced.
  • src/server/clock.ts:
    • appNow() is the business now.
    • realNow() and systemTimeAt(real) are for code that needs both.
    • setClock / syncClock are the writes (±366 days).
  • New code takes "now" from appNow() or audit.now, never new Date() / Date.now(). src/server/clock-usage.test.ts enforces 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 in applications/actions.ts.
  • auditContextFor gives now (system time) and realNow. recordAudit writes occurred_at as real time and, when they differ, simulated_at as system time (/admin/audit-log shows 「系統時間 …」). Contexts rebuilt from another context must carry realNow over (see systemContext in the settlement service). The schedulers pass both.
  • While adjusted, (app)/layout.tsx passes clockNotice to AppFrame. Every page then shows 「系統時間已調整為 …(真實時間 …)」, and sysadmins also get a link to the tab.
  • Clearing business data keeps the offset.
  • E2E: the pin-clock setup project (tests/e2e/pin-clock.setup.ts, pinSystemClock in db.ts) sets the offset to the 10th of the current month at 12:00 Taipei before the chromium project, and its teardown clears it. Test code uses today() (the pinned system date) and claimDate() (last month, submittable) from db.ts; monthsAgo follows the real month (unchanged by the pin). tests/e2e/clock.spec.ts runs 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 in src/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 carry attachment (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.
    • 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*.
      • 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.
    • Pending-review notifications follow the case:
      • When a case leaves pending_review (approve, return, reject, withdraw…), notifyTransition calls clearPendingReview, which marks every recipient's unread pending-review notification for that case as read. Nothing is deleted.
      • clearStalePendingReviews runs once at startup and is idempotent.
      • After a review, the review UI dispatches notifications:changed, so the bell updates without a page change.
    • Zulip direct messages (zulip-notifications + zulip-reject-and-settlement-reminder, user decisions 2026-11-11): only application.pending_review, application.returned, application.rejected and reminder.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_at make 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 are skipped, the rest are merged per (recipient, type) into one message — reviews list applicant + case number (first 10), returns / rejections carry the latest return / reject|expire_reject|overdue_reject comment 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, then failed; 400 Invalid email → skipped. Failures only log.
      • Config: ZULIP_SITE, ZULIP_BOT_EMAIL, ZULIP_API_KEY (+ APP_URL for links; zulipConfigured) — all required in vibe.yaml, values in .env.deploy; missing → no scheduler, a startup warning, in-app only. ZULIP_DELIVERY=dry-run (local only, never in vibe.yaml) logs instead of sending. Never print the API key.
    • 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).
      • 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-day reminder.manager_deadline stay 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.
  • 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. 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.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).
  • /help renders 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/*, 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, 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 total equally, 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.