From e600048c3d91e8aa167a4971a3219495f21382ae Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?pkgsp50777=5F=E6=A5=8A=E8=88=92=E8=AB=A0?=
Date: Wed, 11 Nov 2026 16:51:29 +0800
Subject: [PATCH] =?UTF-8?q?zulip-notifications:=20=E5=BE=85=E5=AF=A9=20(in?=
=?UTF-8?q?cl.=20resubmits)=20and=20=E9=80=80=E5=9B=9E=E8=A3=9C=E4=BB=B6?=
=?UTF-8?q?=20notifications=20are=20also=20sent=20as=20Zulip=20direct=20me?=
=?UTF-8?q?ssages=20to=20the=20recipient's=20account=20email=20via=20an=20?=
=?UTF-8?q?incoming-webhook=20bot=20(user=20decision=202026-11-11:=20only?=
=?UTF-8?q?=20these=20two).=20notifications=20gets=20chat=5Fstatus=20/=20c?=
=?UTF-8?q?hat=5Fattempts=20/=20chat=5Fat=20as=20the=20outbox;=20a=20per-m?=
=?UTF-8?q?inute=20dispatcher=20(after=20the=20business=20transaction)=20m?=
=?UTF-8?q?erges=20each=20recipient's=20pending=20rows=20into=20one=20mess?=
=?UTF-8?q?age:=20reviews=20list=20applicant=20+=20case=20number=20(first?=
=?UTF-8?q?=2010),=20returns=20include=20the=20full=20manager=20comment=20?=
=?UTF-8?q?with=20@=20mentions=20neutralized;=20no=20amounts.=20Already-re?=
=?UTF-8?q?viewed=20cases,=20recipients=20without=20email=20or=20inactive,?=
=?UTF-8?q?=20and=20rows=20older=20than=2024=20h=20are=20skipped;=20transi?=
=?UTF-8?q?ent=20failures=20retry=203=20times,=20failures=20only=20log.=20?=
=?UTF-8?q?ZULIP=5FSITE=20/=20ZULIP=5FBOT=5FEMAIL=20/=20ZULIP=5FAPI=5FKEY?=
=?UTF-8?q?=20added=20to=20vibe.yaml=20(values=20in=20.env.deploy);=20miss?=
=?UTF-8?q?ing=20config=20keeps=20the=20site=20running=20with=20in-app=20n?=
=?UTF-8?q?otifications=20only;=20ZULIP=5FDELIVERY=3Ddry-run=20for=20local?=
=?UTF-8?q?=20use.=20Help=20page=20and=20CLAUDE.md=20updated;=20change=20a?=
=?UTF-8?q?rchived=20into=20notifications?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.env.example | 8 +
CLAUDE.md | 4 +
.../.openspec.yaml | 2 +
.../2026-11-11-zulip-notifications/design.md | 57 +
.../proposal.md | 33 +
.../specs/notifications/spec.md | 24 +
.../2026-11-11-zulip-notifications/tasks.md | 22 +
openspec/specs/notifications/spec.md | 23 +
src/app/(app)/help/page.tsx | 7 +
src/lib/notifications.ts | 11 +
.../0027_fluffy_valeria_richards.sql | 3 +
.../db/migrations/meta/0027_snapshot.json | 3022 +++++++++++++++++
src/server/db/migrations/meta/_journal.json | 7 +
src/server/db/schema/notifications.ts | 9 +-
src/server/env.test.ts | 17 +-
src/server/env.ts | 12 +
src/server/notifications/scheduler.ts | 28 +-
src/server/notifications/zulip.test.ts | 251 ++
src/server/notifications/zulip.ts | 244 ++
src/server/startup.ts | 11 +-
vibe.yaml | 4 +
21 files changed, 3795 insertions(+), 4 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-11-zulip-notifications/.openspec.yaml
create mode 100644 openspec/changes/archive/2026-11-11-zulip-notifications/design.md
create mode 100644 openspec/changes/archive/2026-11-11-zulip-notifications/proposal.md
create mode 100644 openspec/changes/archive/2026-11-11-zulip-notifications/specs/notifications/spec.md
create mode 100644 openspec/changes/archive/2026-11-11-zulip-notifications/tasks.md
create mode 100644 src/server/db/migrations/0027_fluffy_valeria_richards.sql
create mode 100644 src/server/db/migrations/meta/0027_snapshot.json
create mode 100644 src/server/notifications/zulip.test.ts
create mode 100644 src/server/notifications/zulip.ts
diff --git a/.env.example b/.env.example
index b80adad..ca11110 100644
--- a/.env.example
+++ b/.env.example
@@ -21,3 +21,11 @@ APP_URL=
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS=
# OIDC_ISSUER、OIDC_CLIENT_ID、OIDC_CLIENT_SECRET 由 vibe 平台部署時注入(保留字),
# 不要寫在這裡或任何進版控的檔案。
+
+# Zulip 機器人(chat.moonshine.tw 的傳入 webhook bot):待審與退回通知同時私訊本人。
+# 三個都有(且有 APP_URL)才發送;正式環境的值放 .env.deploy,由 /mason:deploy-site 交給平台。
+ZULIP_SITE=
+ZULIP_BOT_EMAIL=
+ZULIP_API_KEY=
+# 本機測試不想真的發給同事時設 dry-run(只寫 log)。不要列進 vibe.yaml。
+# ZULIP_DELIVERY=dry-run
diff --git a/CLAUDE.md b/CLAUDE.md
index dc6d4c0..6e07fb9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -266,6 +266,10 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- 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`, user decision 2026-11-11): only `application.pending_review` and `application.returned` (`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 carry the latest `return` comment in full (`@` neutralized). 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).
- `startBackgroundJobs` (`src/server/startup.ts`) runs them at startup and hourly, from 08:00 Asia/Taipei.
diff --git a/openspec/changes/archive/2026-11-11-zulip-notifications/.openspec.yaml b/openspec/changes/archive/2026-11-11-zulip-notifications/.openspec.yaml
new file mode 100644
index 0000000..2a7773d
--- /dev/null
+++ b/openspec/changes/archive/2026-11-11-zulip-notifications/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-11
diff --git a/openspec/changes/archive/2026-11-11-zulip-notifications/design.md b/openspec/changes/archive/2026-11-11-zulip-notifications/design.md
new file mode 100644
index 0000000..6732028
--- /dev/null
+++ b/openspec/changes/archive/2026-11-11-zulip-notifications/design.md
@@ -0,0 +1,57 @@
+## Context
+
+站內通知在狀態轉移的同一交易內寫入(`notifyTransition` → `notify`)。Zulip 是外部 HTTP 呼叫,不能放在 SQLite 的 `BEGIN IMMEDIATE` 交易裡(會拖住寫鎖,失敗也不該回滾業務)。公司一般員工只能建**傳入 webhook bot**:可以用 email 私訊,不能查詢使用者(mason `zulip-notify`,公司 Zulip 12.2 實測)。
+
+## Goals / Non-Goals
+
+- Goals:待審與退回兩種通知私訊到 Zulip;同一人多則合併;失敗不影響業務;本機與 e2e 不會真的發給同事。
+- Non-Goals:其他通知類型、頻道訊息、使用者自訂開關、在 Zulip 裡回覆操作。
+
+## Decisions
+
+### Z1 通知表當待發佇列(outbox)
+
+`notifications` 加三欄:`chat_status`(NULL=待發、`sent`、`skipped`、`failed`、`dry_run`)、`chat_attempts`(整數,預設 0)、`chat_at`(最後處理時間)。不另建表:一則站內通知對應最多一次 Zulip 發送,收件人、類型、案件都在同一列。
+
+- 只有 `application.pending_review`、`application.returned` 會被派送;其他類型永遠是 NULL 且不處理。
+- **不補發舊通知**:派送只處理 `created_at` 在 24 小時內的列,上線時累積的舊通知自然排除,也避免停機很久後一次送出過時訊息。
+- 派送狀態是技術性欄位,不寫操作紀錄(同已讀標記)。`notifications` 已在 `BUSINESS_TABLES`,清除業務資料會一起清掉。
+
+### Z2 每分鐘派送與合併
+
+`startBackgroundJobs` 加每分鐘的 `runChatDispatch`(啟動時也跑一次)。每次:
+
+1. 取待發列(`chat_status` NULL、`chat_attempts` < 3、類型符合、24 小時內)。
+2. 待審通知已標為已讀(案件已審或已撤回)→ 標 `skipped`,不發。
+3. 依(收件人、類型)分組,每組組成一則訊息、發一次;結果寫回組內每一列。
+4. 收件人沒有 email 或帳號已停用 → `skipped`。
+
+一分鐘的間隔就是合併的窗口:月初同時送出的多筆會落在同一則。不另設延遲。
+
+### Z3 訊息內容
+
+訊息是 Markdown,開頭標明「AI 補助申請系統」,連結用 `APP_URL` 組成絕對網址(沒有 `APP_URL` 視同未設定)。
+
+- 待審(部長):`你有 N 筆待審案件`,每筆一行「申請人 · 案件編號」(重送的標「補件重送」),最後 `[前往審核](APP_URL/department/review)`。N > 10 時只列前 10 筆並註明其餘筆數。
+- 退回(員工):`你有 N 筆申請被退回補件`,每筆案件編號+主管意見全文(引用區塊),最後連到該案件;多筆時連到 `/applications`。
+- 意見全文從該案件最新一筆 `return` 轉移的 comment 取得(站內通知的內文是截短版)。
+- 不含金額與平台費用。使用者輸入的文字把 `@` 換成全形 `@`,避免觸發提及;換行保留。
+
+### Z4 發送與設定
+
+`src/server/notifications/zulip.ts`:`POST {ZULIP_SITE}/api/v1/messages`,Basic auth(bot email + API key),`type=private`、`to=["email"]`,5 秒逾時。回傳 `sent | dry_run | skipped | failed`。
+
+- 三個 `ZULIP_*` 缺任一 → 整個派送不跑(啟動時印一次警告),站內通知照舊。
+- `ZULIP_DELIVERY=dry-run` → 只 `console.info` 收件人與內容,標 `dry_run`。沒設時照常發送(**不**依 `NODE_ENV` 判斷,與本專案慣例一致;本機與 e2e 沒有 `ZULIP_*` 本來就不會發)。`ZULIP_DELIVERY` 不列進 `vibe.yaml`。
+- `400 Invalid email` → `skipped`(對方沒登入過 Zulip),不重試;`401` → `failed` 並記警告(金鑰錯或 bot 停用);網路錯誤、逾時、`429`、5xx → `chat_attempts + 1`,下一分鐘再試,滿 3 次標 `failed`。
+- log 不印 API key,也不印訊息全文以外的個資;`console.error` 只印收件人帳號 id 與錯誤代碼。
+
+### Z5 時間
+
+24 小時窗口與 `chat_at` 用 `appNow()`(`created_at` 也是系統時間)。
+
+## Risks / Trade-offs
+
+- 最多延遲約 1 分鐘;可接受,換來合併。
+- 單一實例部署,排程不會重複派送;若同一則在發送後、寫回前程式中斷,可能重發一次,可接受。
+- bot 屬於建立它的人:離職時要重建 bot、更新 `.env.deploy` 並 redeploy(寫進說明)。
diff --git a/openspec/changes/archive/2026-11-11-zulip-notifications/proposal.md b/openspec/changes/archive/2026-11-11-zulip-notifications/proposal.md
new file mode 100644
index 0000000..1c00210
--- /dev/null
+++ b/openspec/changes/archive/2026-11-11-zulip-notifications/proposal.md
@@ -0,0 +1,33 @@
+## Why
+
+部長與員工目前只能在系統的鈴鐺看到「有新的待審案件」與「申請待補件」,不登入就不知道有事要處理。公司的即時通訊是 Zulip(`https://chat.moonshine.tw`),帳號與公司登入是同一個 email。使用者 2026-11-11 決定:這兩種通知同時用 Zulip 機器人私訊本人,退回意見要寫進訊息,部長同時有多筆待審時合併成一則。
+
+## What Changes
+
+- 站內通知「有新的待審案件/補件已重新送出」(`application.pending_review`)與「申請待補件」(`application.returned`)產生時,同時排入 Zulip 私訊,收件人是同一個人帳號上的公司 email。其他通知類型不發 Zulip。
+- **合併**:背景工作每分鐘處理一次待發的 Zulip 通知,同一收件人、同一類型的多則合併成一則:
+ - 部長:「你有 N 筆待審案件」,附申請人與案件編號清單與前往審核的連結。
+ - 員工:每筆被退回的案件編號與**主管意見全文**,附查看並補件的連結。
+- 發送在案件交易**提交之後**、由背景工作進行:Zulip 失敗、逾時或沒設定都不影響送出與退回。暫時性失敗最多重試 3 次,之後只記 log。
+- 待發期間案件已被審核(待審通知已標為已讀)就不發,避免通知過時的事。
+- 訊息不含金額;使用者輸入的意見會中和 Zulip 的 `@` 提及語法。
+- 新增環境變數 `ZULIP_SITE`、`ZULIP_BOT_EMAIL`、`ZULIP_API_KEY`(三者都有才發送)與只在本機用的 `ZULIP_DELIVERY=send|dry-run`(`dry-run` 只寫 log)。沒有設定時網站照常啟動、不發 Zulip。`vibe.yaml` 的 `environment.required` 加上三個名稱,值放 `.env.deploy`,由 `/mason:deploy-site` 交給平台。
+- 收件人沒有 email(名冊匯入、從未登入)或 Zulip 找不到這個人時略過,站內通知不受影響。
+
+## Capabilities
+
+### New Capabilities
+
+(無)
+
+### Modified Capabilities
+
+- `notifications`:新增「待審與退回通知同步私訊 Zulip」需求。
+
+## Impact
+
+- 資料:`notifications` 加上 Zulip 發送狀態欄位(migration);上線前已存在的通知不補發。
+- 程式:新增 `src/server/notifications/zulip.ts`(發送、訊息組成)與每分鐘的派送排程(`startBackgroundJobs`);`src/server/env.ts` 加四個選填變數;`vibe.yaml`。
+- 部署:使用者在 Zulip 建傳入 webhook 機器人,把金鑰寫進 `.env.deploy`;第一次部署前要先設值。
+- 說明頁(`/help`)提到會收到 Zulip 私訊。
+- 不改權限:收件人與站內通知完全相同(部門主管、申請人本人)。
diff --git a/openspec/changes/archive/2026-11-11-zulip-notifications/specs/notifications/spec.md b/openspec/changes/archive/2026-11-11-zulip-notifications/specs/notifications/spec.md
new file mode 100644
index 0000000..bac5267
--- /dev/null
+++ b/openspec/changes/archive/2026-11-11-zulip-notifications/specs/notifications/spec.md
@@ -0,0 +1,24 @@
+## ADDED Requirements
+
+### Requirement: 待審與退回通知同步私訊 Zulip
+系統產生「待審案件」(含補件重送)或「申請待補件」站內通知時,SHALL 另以公司 Zulip 機器人私訊同一位收件人,收件人以其帳號上的公司 email 對應 Zulip 帳號;其他通知類型 MUST NOT 發送 Zulip。同一收件人同類型的多則待發通知 SHALL 合併為一則訊息。退回補件的訊息 MUST 包含主管意見全文;訊息 MUST NOT 包含金額。Zulip 發送 MUST 在業務交易提交後進行,發送失敗、逾時或未設定機器人 MUST NOT 影響案件操作與站內通知。待發期間案件已離開待主管審核時,該則待審通知 MUST NOT 發送。收件人沒有 email 或 Zulip 找不到該人時,系統 SHALL 略過該則。
+
+#### Scenario: 部長收到合併的待審私訊
+- **WHEN** 設計部三位員工在同一分鐘內各送出一筆申請
+- **THEN** 設計部部長在 Zulip 收到一則「你有 3 筆待審案件」私訊,列出三筆申請人與案件編號並附前往審核的連結
+
+#### Scenario: 員工收到含意見的退回私訊
+- **WHEN** 主管退回一筆案件並填寫意見「請補上刷卡帳單」
+- **THEN** 申請人在 Zulip 收到私訊,內容含案件編號、意見「請補上刷卡帳單」與查看案件的連結,不含金額
+
+#### Scenario: 已審案件不再通知
+- **WHEN** 員工送出案件後,部長在 Zulip 派送前就核准了該案件
+- **THEN** 部長不會收到該案件的 Zulip 待審私訊
+
+#### Scenario: Zulip 失敗不影響操作
+- **WHEN** 主管退回案件時 Zulip 無法連線
+- **THEN** 退回成功、申請人照常收到站內通知,Zulip 私訊稍後重試,重試失敗只記錄於系統日誌
+
+#### Scenario: 其他通知不發 Zulip
+- **WHEN** 主管核准一筆案件
+- **THEN** 申請人收到站內通知,但不會收到 Zulip 私訊
diff --git a/openspec/changes/archive/2026-11-11-zulip-notifications/tasks.md b/openspec/changes/archive/2026-11-11-zulip-notifications/tasks.md
new file mode 100644
index 0000000..b148f1a
--- /dev/null
+++ b/openspec/changes/archive/2026-11-11-zulip-notifications/tasks.md
@@ -0,0 +1,22 @@
+# Tasks
+
+## 1. 設定與資料
+
+- [x] 1.1 `src/server/env.ts` 加選填 `ZULIP_SITE`(url)、`ZULIP_BOT_EMAIL`、`ZULIP_API_KEY`、`ZULIP_DELIVERY`(`send|dry-run`);缺值不影響啟動,只警告;`.env.example` 補註解範例(不含值)。
+- [x] 1.2 `notifications` 加 `chat_status`、`chat_attempts`、`chat_at`,`npm run db:generate` 產生 migration。
+- [x] 1.3 `vibe.yaml` `environment.required` 加三個 `ZULIP_*` 名稱;CLAUDE.md 記錄 Zulip 通知。
+
+## 2. 發送與派送
+
+- [x] 2.1 `src/server/notifications/zulip.ts`:`sendZulipDirect`(Basic auth、5 秒逾時、結果分類 Z4,可注入 fetch)與訊息組成(Z3:合併、前 10 筆、意見全文、`@` 中和、無金額)。
+- [x] 2.2 `runChatDispatch(db, sender, now)`:取待發列、已讀待審標 `skipped`、依收件人+類型分組發送、寫回狀態與重試次數(Z1、Z2)。
+- [x] 2.3 `startBackgroundJobs` 加每分鐘排程(啟動時跑一次;未設定 `ZULIP_*` 不啟動並印一次警告)。
+
+## 3. 測試與說明
+
+- [x] 3.1 單元測試:合併成一則、24 小時外與其他類型不發、已審案件不發、無 email 略過、`dry-run` 不呼叫 fetch、`400 Invalid email` 略過、5xx 重試滿 3 次為 `failed`、退回意見全文與 `@` 中和、訊息不含金額。
+- [x] 3.2 `/help` 說明待審與退回會同時收到 Zulip 私訊(沒登入過 Zulip 的人收不到)。
+
+## 4. 驗證
+
+- [x] 4.1 `npm run lint`、`format:check`、`typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `notifications.spec.ts`、`review.spec.ts` 照舊通過。
diff --git a/openspec/specs/notifications/spec.md b/openspec/specs/notifications/spec.md
index 064c55c..b63bc3d 100644
--- a/openspec/specs/notifications/spec.md
+++ b/openspec/specs/notifications/spec.md
@@ -130,3 +130,26 @@
#### Scenario: 部門被跳過
- **WHEN** 2026/11/29 自動提交時行銷部因手動調整超過月上限被跳過
- **THEN** 管理端收到「2026/10 月結自動提交失敗(1 個部門)」通知,列出行銷部與原因;當天之後的排程不再重複通知
+
+### Requirement: 待審與退回通知同步私訊 Zulip
+系統產生「待審案件」(含補件重送)或「申請待補件」站內通知時,SHALL 另以公司 Zulip 機器人私訊同一位收件人,收件人以其帳號上的公司 email 對應 Zulip 帳號;其他通知類型 MUST NOT 發送 Zulip。同一收件人同類型的多則待發通知 SHALL 合併為一則訊息。退回補件的訊息 MUST 包含主管意見全文;訊息 MUST NOT 包含金額。Zulip 發送 MUST 在業務交易提交後進行,發送失敗、逾時或未設定機器人 MUST NOT 影響案件操作與站內通知。待發期間案件已離開待主管審核時,該則待審通知 MUST NOT 發送。收件人沒有 email 或 Zulip 找不到該人時,系統 SHALL 略過該則。
+
+#### Scenario: 部長收到合併的待審私訊
+- **WHEN** 設計部三位員工在同一分鐘內各送出一筆申請
+- **THEN** 設計部部長在 Zulip 收到一則「你有 3 筆待審案件」私訊,列出三筆申請人與案件編號並附前往審核的連結
+
+#### Scenario: 員工收到含意見的退回私訊
+- **WHEN** 主管退回一筆案件並填寫意見「請補上刷卡帳單」
+- **THEN** 申請人在 Zulip 收到私訊,內容含案件編號、意見「請補上刷卡帳單」與查看案件的連結,不含金額
+
+#### Scenario: 已審案件不再通知
+- **WHEN** 員工送出案件後,部長在 Zulip 派送前就核准了該案件
+- **THEN** 部長不會收到該案件的 Zulip 待審私訊
+
+#### Scenario: Zulip 失敗不影響操作
+- **WHEN** 主管退回案件時 Zulip 無法連線
+- **THEN** 退回成功、申請人照常收到站內通知,Zulip 私訊稍後重試,重試失敗只記錄於系統日誌
+
+#### Scenario: 其他通知不發 Zulip
+- **WHEN** 主管核准一筆案件
+- **THEN** 申請人收到站內通知,但不會收到 Zulip 私訊
diff --git a/src/app/(app)/help/page.tsx b/src/app/(app)/help/page.tsx
index ad0b9f9..23edbb7 100644
--- a/src/app/(app)/help/page.tsx
+++ b/src/app/(app)/help/page.tsx
@@ -43,6 +43,13 @@ export default async function HelpPage() {
第一次以公司帳號登入時系統會自動建立帳號。部門與部門主管依人資資料於登入時更新;人事異動後尚未反映時,請重新登入,仍不正確請洽系統管理員。
+
+
+ 通知會出現在右上角的鈴鐺。主管有新的待審案件、或申請被退回補件時,也會同時收到公司 Zulip
+ 的私訊(主管意見會寫在訊息裡,短時間內多筆會合併成一則);尚未登入過 Zulip
+ 的人只會收到站內通知。
+
+
-
diff --git a/src/lib/notifications.ts b/src/lib/notifications.ts
index ea5f555..26af602 100644
--- a/src/lib/notifications.ts
+++ b/src/lib/notifications.ts
@@ -19,6 +19,17 @@ export const NOTIFICATION_TYPES = [
] as const;
export type NotificationType = (typeof NOTIFICATION_TYPES)[number];
+/** 同時私訊 Zulip 的通知類型(zulip-notifications,使用者決定 2026-11-11:只有這兩種)。 */
+export const CHAT_NOTIFICATION_TYPES = [
+ "application.pending_review",
+ "application.returned",
+] as const satisfies readonly NotificationType[];
+export type ChatNotificationType = (typeof CHAT_NOTIFICATION_TYPES)[number];
+
+/** Zulip 派送結果。NULL(欄位)=待發。 */
+export const CHAT_STATUSES = ["sent", "skipped", "failed", "dry_run"] as const;
+export type ChatStatus = (typeof CHAT_STATUSES)[number];
+
/** 期限提醒的提前天數(design N3:常數組態,截止日本身讀制度參數)。 */
export const EMPLOYEE_REMINDER_DAYS = [5, 1] as const;
export const MANAGER_REMINDER_DAYS = [3, 1] as const;
diff --git a/src/server/db/migrations/0027_fluffy_valeria_richards.sql b/src/server/db/migrations/0027_fluffy_valeria_richards.sql
new file mode 100644
index 0000000..b25d5c8
--- /dev/null
+++ b/src/server/db/migrations/0027_fluffy_valeria_richards.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `notifications` ADD `chat_status` text;--> statement-breakpoint
+ALTER TABLE `notifications` ADD `chat_attempts` integer DEFAULT 0 NOT NULL;--> statement-breakpoint
+ALTER TABLE `notifications` ADD `chat_at` text;
\ No newline at end of file
diff --git a/src/server/db/migrations/meta/0027_snapshot.json b/src/server/db/migrations/meta/0027_snapshot.json
new file mode 100644
index 0000000..0089e67
--- /dev/null
+++ b/src/server/db/migrations/meta/0027_snapshot.json
@@ -0,0 +1,3022 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "5751c698-6ea0-4ece-96e0-7c8cd897e03f",
+ "prevId": "885a1379-0d03-4cad-9f03-b5dd73ee5c4e",
+ "tables": {
+ "_meta": {
+ "name": "_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "department_managers": {
+ "name": "department_managers",
+ "columns": {
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "department_managers_user_idx": {
+ "name": "department_managers_user_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "department_managers_department_id_departments_id_fk": {
+ "name": "department_managers_department_id_departments_id_fk",
+ "tableFrom": "department_managers",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "department_managers_user_id_users_id_fk": {
+ "name": "department_managers_user_id_users_id_fk",
+ "tableFrom": "department_managers",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "department_managers_department_id_user_id_pk": {
+ "columns": [
+ "department_id",
+ "user_id"
+ ],
+ "name": "department_managers_department_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "departments": {
+ "name": "departments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "code": {
+ "name": "code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "hr_managed": {
+ "name": "hr_managed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "departments_code_unique": {
+ "name": "departments_code_unique",
+ "columns": [
+ "code"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_department_history": {
+ "name": "user_department_history",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effective_from": {
+ "name": "effective_from",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "user_department_history_user_idx": {
+ "name": "user_department_history_user_idx",
+ "columns": [
+ "user_id",
+ "effective_from"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "user_department_history_user_id_users_id_fk": {
+ "name": "user_department_history_user_id_users_id_fk",
+ "tableFrom": "user_department_history",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "user_department_history_department_id_departments_id_fk": {
+ "name": "user_department_history_department_id_departments_id_fk",
+ "tableFrom": "user_department_history",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "employee_no": {
+ "name": "employee_no",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "first_login_at": {
+ "name": "first_login_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "can_view_audit_log": {
+ "name": "can_view_audit_log",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hr_synced_at": {
+ "name": "hr_synced_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hr_status": {
+ "name": "hr_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hr_status_since": {
+ "name": "hr_status_since",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hr_deactivated": {
+ "name": "hr_deactivated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "users_employee_no_unique": {
+ "name": "users_employee_no_unique",
+ "columns": [
+ "employee_no"
+ ],
+ "isUnique": true
+ },
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "users_department_id_departments_id_fk": {
+ "name": "users_department_id_departments_id_fk",
+ "tableFrom": "users",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_user_idx": {
+ "name": "sessions_user_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_roles": {
+ "name": "user_roles",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_roles_user_id_role_pk": {
+ "columns": [
+ "user_id",
+ "role"
+ ],
+ "name": "user_roles_user_id_role_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "audit_logs": {
+ "name": "audit_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "occurred_at": {
+ "name": "occurred_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_label": {
+ "name": "actor_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "before_json": {
+ "name": "before_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "after_json": {
+ "name": "after_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "comment": {
+ "name": "comment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ip": {
+ "name": "ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "simulated_at": {
+ "name": "simulated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "audit_logs_target_idx": {
+ "name": "audit_logs_target_idx",
+ "columns": [
+ "target_type",
+ "target_id"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_occurred_idx": {
+ "name": "audit_logs_occurred_idx",
+ "columns": [
+ "occurred_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_actor_idx": {
+ "name": "audit_logs_actor_idx",
+ "columns": [
+ "actor_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "audit_logs_actor_user_id_users_id_fk": {
+ "name": "audit_logs_actor_user_id_users_id_fk",
+ "tableFrom": "audit_logs",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "headcount_adjustments": {
+ "name": "headcount_adjustments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "snapshot_id": {
+ "name": "snapshot_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "before": {
+ "name": "before",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "after": {
+ "name": "after",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_label": {
+ "name": "actor_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "headcount_adjustments_snapshot_idx": {
+ "name": "headcount_adjustments_snapshot_idx",
+ "columns": [
+ "snapshot_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "headcount_adjustments_snapshot_id_headcount_snapshots_id_fk": {
+ "name": "headcount_adjustments_snapshot_id_headcount_snapshots_id_fk",
+ "tableFrom": "headcount_adjustments",
+ "tableTo": "headcount_snapshots",
+ "columnsFrom": [
+ "snapshot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "headcount_adjustments_actor_user_id_users_id_fk": {
+ "name": "headcount_adjustments_actor_user_id_users_id_fk",
+ "tableFrom": "headcount_adjustments",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "headcount_snapshot_members": {
+ "name": "headcount_snapshot_members",
+ "columns": {
+ "snapshot_id": {
+ "name": "snapshot_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "employee_no": {
+ "name": "employee_no",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "headcount_snapshot_members_snapshot_id_headcount_snapshots_id_fk": {
+ "name": "headcount_snapshot_members_snapshot_id_headcount_snapshots_id_fk",
+ "tableFrom": "headcount_snapshot_members",
+ "tableTo": "headcount_snapshots",
+ "columnsFrom": [
+ "snapshot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "headcount_snapshot_members_snapshot_id_employee_no_pk": {
+ "columns": [
+ "snapshot_id",
+ "employee_no"
+ ],
+ "name": "headcount_snapshot_members_snapshot_id_employee_no_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "headcount_snapshots": {
+ "name": "headcount_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "month": {
+ "name": "month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headcount": {
+ "name": "headcount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "computed_headcount": {
+ "name": "computed_headcount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked": {
+ "name": "locked",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'local'"
+ },
+ "created_by_label": {
+ "name": "created_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "headcount_snapshots_department_month_unique": {
+ "name": "headcount_snapshots_department_month_unique",
+ "columns": [
+ "department_id",
+ "month"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "headcount_snapshots_department_id_departments_id_fk": {
+ "name": "headcount_snapshots_department_id_departments_id_fk",
+ "tableFrom": "headcount_snapshots",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "rule_versions": {
+ "name": "rule_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "params_json": {
+ "name": "params_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "effective_at": {
+ "name": "effective_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by_label": {
+ "name": "created_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "rule_versions_effective_idx": {
+ "name": "rule_versions_effective_idx",
+ "columns": [
+ "effective_at",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "rule_versions_created_by_users_id_fk": {
+ "name": "rule_versions_created_by_users_id_fk",
+ "tableFrom": "rule_versions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "application_transitions": {
+ "name": "application_transitions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "from_status": {
+ "name": "from_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "to_status": {
+ "name": "to_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_label": {
+ "name": "actor_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "comment": {
+ "name": "comment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "occurred_at": {
+ "name": "occurred_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "application_transitions_application_idx": {
+ "name": "application_transitions_application_idx",
+ "columns": [
+ "application_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "application_transitions_application_id_applications_id_fk": {
+ "name": "application_transitions_application_id_applications_id_fk",
+ "tableFrom": "application_transitions",
+ "tableTo": "applications",
+ "columnsFrom": [
+ "application_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "application_transitions_actor_user_id_users_id_fk": {
+ "name": "application_transitions_actor_user_id_users_id_fk",
+ "tableFrom": "application_transitions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "applications": {
+ "name": "applications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "applicant_id": {
+ "name": "applicant_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'draft'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ },
+ "application_no": {
+ "name": "application_no",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "platform": {
+ "name": "platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "platform_other": {
+ "name": "platform_other",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan_name": {
+ "name": "plan_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "twd_amount": {
+ "name": "twd_amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "foreign_amount_cents": {
+ "name": "foreign_amount_cents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "card_date": {
+ "name": "card_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "application_month": {
+ "name": "application_month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "outcome_url": {
+ "name": "outcome_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "declared_at": {
+ "name": "declared_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ever_submitted": {
+ "name": "ever_submitted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "rule_version_id": {
+ "name": "rule_version_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "submitted_at": {
+ "name": "submitted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "final_amount": {
+ "name": "final_amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duplicate_of_json": {
+ "name": "duplicate_of_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duplicate_confirmed_by": {
+ "name": "duplicate_confirmed_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duplicate_confirmed_at": {
+ "name": "duplicate_confirmed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "applications_application_no_unique": {
+ "name": "applications_application_no_unique",
+ "columns": [
+ "application_no"
+ ],
+ "isUnique": true
+ },
+ "applications_applicant_idx": {
+ "name": "applications_applicant_idx",
+ "columns": [
+ "applicant_id"
+ ],
+ "isUnique": false
+ },
+ "applications_department_idx": {
+ "name": "applications_department_idx",
+ "columns": [
+ "department_id"
+ ],
+ "isUnique": false
+ },
+ "applications_month_idx": {
+ "name": "applications_month_idx",
+ "columns": [
+ "application_month",
+ "department_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "applications_applicant_id_users_id_fk": {
+ "name": "applications_applicant_id_users_id_fk",
+ "tableFrom": "applications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "applicant_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "applications_department_id_departments_id_fk": {
+ "name": "applications_department_id_departments_id_fk",
+ "tableFrom": "applications",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "applications_rule_version_id_rule_versions_id_fk": {
+ "name": "applications_rule_version_id_rule_versions_id_fk",
+ "tableFrom": "applications",
+ "tableTo": "rule_versions",
+ "columnsFrom": [
+ "rule_version_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "applications_duplicate_confirmed_by_users_id_fk": {
+ "name": "applications_duplicate_confirmed_by_users_id_fk",
+ "tableFrom": "applications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "duplicate_confirmed_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "attachments": {
+ "name": "attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "application_id": {
+ "name": "application_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "storage_key": {
+ "name": "storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha256": {
+ "name": "sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploaded_by": {
+ "name": "uploaded_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploaded_at": {
+ "name": "uploaded_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "superseded_at": {
+ "name": "superseded_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "attachments_storage_key_unique": {
+ "name": "attachments_storage_key_unique",
+ "columns": [
+ "storage_key"
+ ],
+ "isUnique": true
+ },
+ "attachments_application_idx": {
+ "name": "attachments_application_idx",
+ "columns": [
+ "application_id"
+ ],
+ "isUnique": false
+ },
+ "attachments_active_kind_unique": {
+ "name": "attachments_active_kind_unique",
+ "columns": [
+ "application_id",
+ "kind"
+ ],
+ "isUnique": true,
+ "where": "\"attachments\".\"superseded_at\" IS NULL"
+ }
+ },
+ "foreignKeys": {
+ "attachments_application_id_applications_id_fk": {
+ "name": "attachments_application_id_applications_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "applications",
+ "columnsFrom": [
+ "application_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "attachments_uploaded_by_users_id_fk": {
+ "name": "attachments_uploaded_by_users_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "users",
+ "columnsFrom": [
+ "uploaded_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "department_settlements": {
+ "name": "department_settlements",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "month": {
+ "name": "month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "rule_version_id": {
+ "name": "rule_version_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rate_percent": {
+ "name": "rate_percent",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rounding_mode": {
+ "name": "rounding_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_type": {
+ "name": "department_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "quota_per_person": {
+ "name": "quota_per_person",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headcount": {
+ "name": "headcount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cap": {
+ "name": "cap",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total_eligible": {
+ "name": "total_eligible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "final_total": {
+ "name": "final_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_over_cap": {
+ "name": "is_over_cap",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calculated_at": {
+ "name": "calculated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "submitted_by": {
+ "name": "submitted_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "submitted_by_label": {
+ "name": "submitted_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "submitted_at": {
+ "name": "submitted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_late": {
+ "name": "is_late",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "submission_mode": {
+ "name": "submission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'manager'"
+ },
+ "submission_reason": {
+ "name": "submission_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finalized_by": {
+ "name": "finalized_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finalized_by_label": {
+ "name": "finalized_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finalized_at": {
+ "name": "finalized_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_by": {
+ "name": "returned_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_by_label": {
+ "name": "returned_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_at": {
+ "name": "returned_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "return_reason": {
+ "name": "return_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "paid_at": {
+ "name": "paid_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "department_settlements_department_month_unique": {
+ "name": "department_settlements_department_month_unique",
+ "columns": [
+ "department_id",
+ "month"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "department_settlements_department_id_departments_id_fk": {
+ "name": "department_settlements_department_id_departments_id_fk",
+ "tableFrom": "department_settlements",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "department_settlements_rule_version_id_rule_versions_id_fk": {
+ "name": "department_settlements_rule_version_id_rule_versions_id_fk",
+ "tableFrom": "department_settlements",
+ "tableTo": "rule_versions",
+ "columnsFrom": [
+ "rule_version_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "department_settlements_submitted_by_users_id_fk": {
+ "name": "department_settlements_submitted_by_users_id_fk",
+ "tableFrom": "department_settlements",
+ "tableTo": "users",
+ "columnsFrom": [
+ "submitted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "department_settlements_finalized_by_users_id_fk": {
+ "name": "department_settlements_finalized_by_users_id_fk",
+ "tableFrom": "department_settlements",
+ "tableTo": "users",
+ "columnsFrom": [
+ "finalized_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "department_settlements_returned_by_users_id_fk": {
+ "name": "department_settlements_returned_by_users_id_fk",
+ "tableFrom": "department_settlements",
+ "tableTo": "users",
+ "columnsFrom": [
+ "returned_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "payout_records": {
+ "name": "payout_records",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "settlement_id": {
+ "name": "settlement_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "charge_month": {
+ "name": "charge_month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payout_month": {
+ "name": "payout_month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pay_item": {
+ "name": "pay_item",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'original'"
+ },
+ "correction_id": {
+ "name": "correction_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_reason": {
+ "name": "failure_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "marked_by": {
+ "name": "marked_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "marked_by_label": {
+ "name": "marked_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "marked_at": {
+ "name": "marked_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "payout_records_original_unique": {
+ "name": "payout_records_original_unique",
+ "columns": [
+ "settlement_id",
+ "user_id"
+ ],
+ "isUnique": true,
+ "where": "\"payout_records\".\"kind\" = 'original'"
+ },
+ "payout_records_settlement_user_idx": {
+ "name": "payout_records_settlement_user_idx",
+ "columns": [
+ "settlement_id",
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "payout_records_month_idx": {
+ "name": "payout_records_month_idx",
+ "columns": [
+ "payout_month",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "payout_records_settlement_id_department_settlements_id_fk": {
+ "name": "payout_records_settlement_id_department_settlements_id_fk",
+ "tableFrom": "payout_records",
+ "tableTo": "department_settlements",
+ "columnsFrom": [
+ "settlement_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "payout_records_user_id_users_id_fk": {
+ "name": "payout_records_user_id_users_id_fk",
+ "tableFrom": "payout_records",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "payout_records_department_id_departments_id_fk": {
+ "name": "payout_records_department_id_departments_id_fk",
+ "tableFrom": "payout_records",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "payout_records_marked_by_users_id_fk": {
+ "name": "payout_records_marked_by_users_id_fk",
+ "tableFrom": "payout_records",
+ "tableTo": "users",
+ "columnsFrom": [
+ "marked_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settlement_allocations": {
+ "name": "settlement_allocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "settlement_id": {
+ "name": "settlement_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "paid_total": {
+ "name": "paid_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "personal_cap": {
+ "name": "personal_cap",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "personal_eligible": {
+ "name": "personal_eligible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "system_eligible": {
+ "name": "system_eligible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "share_bp": {
+ "name": "share_bp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "final_amount": {
+ "name": "final_amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "remainder_adjustment": {
+ "name": "remainder_adjustment",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "settlement_allocations_settlement_user_unique": {
+ "name": "settlement_allocations_settlement_user_unique",
+ "columns": [
+ "settlement_id",
+ "user_id"
+ ],
+ "isUnique": true
+ },
+ "settlement_allocations_user_idx": {
+ "name": "settlement_allocations_user_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "settlement_allocations_settlement_id_department_settlements_id_fk": {
+ "name": "settlement_allocations_settlement_id_department_settlements_id_fk",
+ "tableFrom": "settlement_allocations",
+ "tableTo": "department_settlements",
+ "columnsFrom": [
+ "settlement_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_allocations_user_id_users_id_fk": {
+ "name": "settlement_allocations_user_id_users_id_fk",
+ "tableFrom": "settlement_allocations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settlement_corrections": {
+ "name": "settlement_corrections",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "settlement_id": {
+ "name": "settlement_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "charge_month": {
+ "name": "charge_month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payout_month": {
+ "name": "payout_month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source_payout_id": {
+ "name": "source_payout_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by_label": {
+ "name": "created_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cancelled_by": {
+ "name": "cancelled_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancelled_by_label": {
+ "name": "cancelled_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancelled_at": {
+ "name": "cancelled_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_reason": {
+ "name": "cancel_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "settlement_corrections_settlement_user_idx": {
+ "name": "settlement_corrections_settlement_user_idx",
+ "columns": [
+ "settlement_id",
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "settlement_corrections_settlement_id_department_settlements_id_fk": {
+ "name": "settlement_corrections_settlement_id_department_settlements_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "department_settlements",
+ "columnsFrom": [
+ "settlement_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_corrections_user_id_users_id_fk": {
+ "name": "settlement_corrections_user_id_users_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_corrections_department_id_departments_id_fk": {
+ "name": "settlement_corrections_department_id_departments_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_corrections_source_payout_id_payout_records_id_fk": {
+ "name": "settlement_corrections_source_payout_id_payout_records_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "payout_records",
+ "columnsFrom": [
+ "source_payout_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_corrections_created_by_users_id_fk": {
+ "name": "settlement_corrections_created_by_users_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_corrections_cancelled_by_users_id_fk": {
+ "name": "settlement_corrections_cancelled_by_users_id_fk",
+ "tableFrom": "settlement_corrections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "cancelled_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settlement_eligible_overrides": {
+ "name": "settlement_eligible_overrides",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "department_id": {
+ "name": "department_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "month": {
+ "name": "month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by_label": {
+ "name": "created_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "settlement_eligible_overrides_lookup_idx": {
+ "name": "settlement_eligible_overrides_lookup_idx",
+ "columns": [
+ "department_id",
+ "month",
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "settlement_eligible_overrides_department_id_departments_id_fk": {
+ "name": "settlement_eligible_overrides_department_id_departments_id_fk",
+ "tableFrom": "settlement_eligible_overrides",
+ "tableTo": "departments",
+ "columnsFrom": [
+ "department_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_eligible_overrides_user_id_users_id_fk": {
+ "name": "settlement_eligible_overrides_user_id_users_id_fk",
+ "tableFrom": "settlement_eligible_overrides",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_eligible_overrides_created_by_users_id_fk": {
+ "name": "settlement_eligible_overrides_created_by_users_id_fk",
+ "tableFrom": "settlement_eligible_overrides",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settlement_submissions": {
+ "name": "settlement_submissions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "settlement_id": {
+ "name": "settlement_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rule_version_id": {
+ "name": "rule_version_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rate_percent": {
+ "name": "rate_percent",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rounding_mode": {
+ "name": "rounding_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "department_type": {
+ "name": "department_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "quota_per_person": {
+ "name": "quota_per_person",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headcount": {
+ "name": "headcount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cap": {
+ "name": "cap",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total_eligible": {
+ "name": "total_eligible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "final_total": {
+ "name": "final_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_over_cap": {
+ "name": "is_over_cap",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_late": {
+ "name": "is_late",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "submitted_by": {
+ "name": "submitted_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "submitted_by_label": {
+ "name": "submitted_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "submitted_at": {
+ "name": "submitted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "submission_mode": {
+ "name": "submission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'manager'"
+ },
+ "submission_reason": {
+ "name": "submission_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "allocations_json": {
+ "name": "allocations_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "returned_by_label": {
+ "name": "returned_by_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_at": {
+ "name": "returned_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "return_reason": {
+ "name": "return_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "settlement_submissions_version_unique": {
+ "name": "settlement_submissions_version_unique",
+ "columns": [
+ "settlement_id",
+ "version"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "settlement_submissions_settlement_id_department_settlements_id_fk": {
+ "name": "settlement_submissions_settlement_id_department_settlements_id_fk",
+ "tableFrom": "settlement_submissions",
+ "tableTo": "department_settlements",
+ "columnsFrom": [
+ "settlement_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_submissions_rule_version_id_rule_versions_id_fk": {
+ "name": "settlement_submissions_rule_version_id_rule_versions_id_fk",
+ "tableFrom": "settlement_submissions",
+ "tableTo": "rule_versions",
+ "columnsFrom": [
+ "rule_version_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "settlement_submissions_submitted_by_users_id_fk": {
+ "name": "settlement_submissions_submitted_by_users_id_fk",
+ "tableFrom": "settlement_submissions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "submitted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "notifications": {
+ "name": "notifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "recipient_id": {
+ "name": "recipient_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "href": {
+ "name": "href",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_key": {
+ "name": "target_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dedupe_date": {
+ "name": "dedupe_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_status": {
+ "name": "chat_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "chat_attempts": {
+ "name": "chat_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "chat_at": {
+ "name": "chat_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "notifications_recipient_idx": {
+ "name": "notifications_recipient_idx",
+ "columns": [
+ "recipient_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "notifications_reminder_unique": {
+ "name": "notifications_reminder_unique",
+ "columns": [
+ "recipient_id",
+ "type",
+ "target_key",
+ "dedupe_date"
+ ],
+ "isUnique": true,
+ "where": "\"notifications\".\"dedupe_date\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "notifications_recipient_id_users_id_fk": {
+ "name": "notifications_recipient_id_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "recipient_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hr_employment_history": {
+ "name": "hr_employment_history",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "employee_no": {
+ "name": "employee_no",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_full_time": {
+ "name": "is_full_time",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "effective_from": {
+ "name": "effective_from",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
+ }
+ },
+ "indexes": {
+ "hr_employment_history_employee_idx": {
+ "name": "hr_employment_history_employee_idx",
+ "columns": [
+ "employee_no",
+ "effective_from"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hr_roster_syncs": {
+ "name": "hr_roster_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "triggered_by": {
+ "name": "triggered_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sync_date": {
+ "name": "sync_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "employees": {
+ "name": "employees",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "employment_changes": {
+ "name": "employment_changes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "snapshot_changes": {
+ "name": "snapshot_changes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_stage": {
+ "name": "failure_stage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_reason": {
+ "name": "failure_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_date": {
+ "name": "failure_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hr_roster_syncs_date_idx": {
+ "name": "hr_roster_syncs_date_idx",
+ "columns": [
+ "sync_date",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/src/server/db/migrations/meta/_journal.json b/src/server/db/migrations/meta/_journal.json
index e22353c..8942a72 100644
--- a/src/server/db/migrations/meta/_journal.json
+++ b/src/server/db/migrations/meta/_journal.json
@@ -190,6 +190,13 @@
"when": 1793534658268,
"tag": "0026_kind_wendigo",
"breakpoints": true
+ },
+ {
+ "idx": 27,
+ "version": "6",
+ "when": 1794386314823,
+ "tag": "0027_fluffy_valeria_richards",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/src/server/db/schema/notifications.ts b/src/server/db/schema/notifications.ts
index 66e5be6..3c30cff 100644
--- a/src/server/db/schema/notifications.ts
+++ b/src/server/db/schema/notifications.ts
@@ -1,6 +1,6 @@
import { sql } from "drizzle-orm";
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
-import { NOTIFICATION_TYPES } from "@/lib/notifications";
+import { CHAT_STATUSES, NOTIFICATION_TYPES } from "@/lib/notifications";
import { users } from "./org-directory";
/**
@@ -24,6 +24,13 @@ export const notifications = sqliteTable(
dedupeDate: text("dedupe_date"),
readAt: text("read_at"),
createdAt: text("created_at").notNull(),
+ /**
+ * Zulip 私訊派送狀態(zulip-notifications):NULL=待發(只有待審與退回兩種會被派送)、
+ * sent/skipped/failed/dry_run。技術欄位,不寫操作紀錄。
+ */
+ chatStatus: text("chat_status", { enum: CHAT_STATUSES }),
+ chatAttempts: integer("chat_attempts").notNull().default(0),
+ chatAt: text("chat_at"),
},
(t) => [
index("notifications_recipient_idx").on(t.recipientId, t.id),
diff --git a/src/server/env.test.ts b/src/server/env.test.ts
index ae1867e..a394d07 100644
--- a/src/server/env.test.ts
+++ b/src/server/env.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { EnvError, hrSyncConfigured, oidcConfigured, parseEnv } from "./env";
+import { EnvError, hrSyncConfigured, oidcConfigured, parseEnv, zulipConfigured } from "./env";
const secret = "x".repeat(32);
const dev = { SESSION_SECRET: secret, AUTH_MODE: "dev" };
@@ -22,11 +22,26 @@ describe("parseEnv", () => {
BACKUP_KEEP: 14,
AUTH_MODE: "dev",
BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS: [],
+ ZULIP_DELIVERY: "send",
resourceServers: {},
warnings: [],
});
});
+ it("Zulip 要 ZULIP_SITE、ZULIP_BOT_EMAIL、ZULIP_API_KEY 與 APP_URL 都有才算設定;缺值不警告", () => {
+ const zulip = {
+ ZULIP_SITE: "https://chat.example.tw",
+ ZULIP_BOT_EMAIL: "bot@chat.example.tw",
+ ZULIP_API_KEY: "k",
+ };
+ expect(zulipConfigured(parseEnv(dev))).toBe(false);
+ expect(zulipConfigured(parseEnv({ ...dev, ...zulip }))).toBe(false);
+ const env = parseEnv({ ...dev, ...zulip, APP_URL: "https://app.example.tw" });
+ expect(zulipConfigured(env)).toBe(true);
+ expect(env.warnings).toEqual([]);
+ expect(() => parseEnv({ ...dev, ZULIP_DELIVERY: "maybe" })).toThrow(EnvError);
+ });
+
it("缺少 SESSION_SECRET(或空字串)時隨機產生並提出警告", () => {
for (const source of [{ AUTH_MODE: "dev" }, { AUTH_MODE: "dev", SESSION_SECRET: "" }]) {
const env = parseEnv(source);
diff --git a/src/server/env.ts b/src/server/env.ts
index de31c73..610a644 100644
--- a/src/server/env.ts
+++ b/src/server/env.ts
@@ -33,6 +33,13 @@ const envSchema = z
// 宣告 auth.resource_servers 時由平台注入(保留字)的 JSON;格式在 parseEnv 另外驗證,
// 格式錯誤只警告並視為未設定,不阻擋啟動。
RESOURCE_SERVERS: z.string().optional(),
+ // Zulip 機器人(傳入 webhook bot),待審與退回通知同時私訊(zulip-notifications)。
+ // 三者都有才發送;缺值時網站照常運作、只發站內通知。值放 .env.deploy,不進版控。
+ ZULIP_SITE: z.url().optional(),
+ ZULIP_BOT_EMAIL: z.string().min(1).optional(),
+ ZULIP_API_KEY: z.string().min(1).optional(),
+ // 只在本機用:dry-run 時只把收件人與內容寫進 log,不呼叫 Zulip。不列進 vibe.yaml。
+ ZULIP_DELIVERY: z.enum(["send", "dry-run"]).default("send"),
})
.superRefine((env, ctx) => {
if (env.AUTH_MODE === "dev") {
@@ -104,6 +111,11 @@ function parseResourceServers(raw: string | undefined, warnings: string[]): Env[
return parsed.data;
}
+/** Zulip 私訊所需的設定是否齊全(連結用 APP_URL 組成,所以也要有 APP_URL)。 */
+export function zulipConfigured(env: Env): boolean {
+ return Boolean(env.ZULIP_SITE && env.ZULIP_BOT_EMAIL && env.ZULIP_API_KEY && env.APP_URL);
+}
+
/** 公司登入所需的設定是否齊全;不齊全時 oidc 模式不允許任何人登入。 */
export function oidcConfigured(env: Env): boolean {
return Boolean(env.OIDC_ISSUER && env.OIDC_CLIENT_ID && env.OIDC_CLIENT_SECRET && env.APP_URL);
diff --git a/src/server/notifications/scheduler.ts b/src/server/notifications/scheduler.ts
index fefae60..1ef278d 100644
--- a/src/server/notifications/scheduler.ts
+++ b/src/server/notifications/scheduler.ts
@@ -1,8 +1,9 @@
import { instantToLocalDateTime } from "@/domain/calendar";
import { REMINDER_HOUR } from "@/lib/notifications";
-import { realNow, systemTimeAt } from "@/server/clock";
+import { appNow, realNow, systemTimeAt } from "@/server/clock";
import type { Db } from "@/server/db/client";
import { runDailyReminders, type ReminderRun } from "./reminders";
+import { runChatDispatch, type ZulipSender } from "./zulip";
const HOUR = 60 * 60 * 1000;
@@ -48,3 +49,28 @@ export function startReminderScheduler(db: Db, timeZone: string): NodeJS.Timeout
timer.unref();
return timer;
}
+
+const MINUTE = 60 * 1000;
+
+/**
+ * Zulip 私訊派送(zulip-notifications):啟動時跑一次,之後每分鐘一次;一分鐘也是合併窗口。
+ * 上一輪還沒結束(Zulip 慢)時跳過這一輪。錯誤只記錄不丟出。
+ */
+export function startChatScheduler(db: Db, sender: ZulipSender, appUrl: string): NodeJS.Timeout {
+ let running = false;
+ const run = async () => {
+ if (running) return;
+ running = true;
+ try {
+ await runChatDispatch(db, sender, appUrl, appNow(db));
+ } catch (error) {
+ console.error("[zulip] 派送失敗", error instanceof Error ? error.message : error);
+ } finally {
+ running = false;
+ }
+ };
+ void run();
+ const timer = setInterval(() => void run(), MINUTE);
+ timer.unref();
+ return timer;
+}
diff --git a/src/server/notifications/zulip.test.ts b/src/server/notifications/zulip.test.ts
new file mode 100644
index 0000000..4b1d6e3
--- /dev/null
+++ b/src/server/notifications/zulip.test.ts
@@ -0,0 +1,251 @@
+import { eq } from "drizzle-orm";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { applicationTransitions, applications, notifications, users } from "@/server/db/schema";
+import { parseEnv } from "@/server/env";
+import { insertApplication, seedApplicationFixture } from "@/server/testing/applications";
+import { createTestDatabase, type TestDatabase } from "@/server/testing/test-db";
+import {
+ CHAT_MAX_ATTEMPTS,
+ quoteUserText,
+ runChatDispatch,
+ zulipSenderFromEnv,
+ type SendOutcome,
+ type ZulipSender,
+} from "./zulip";
+
+const APP = "https://app.example.tw";
+const NOW = new Date("2026-11-11T08:00:00Z");
+let t: TestDatabase;
+let f: ReturnType;
+
+/** 記錄每次發送的假發送器;outcome 可依次指定。 */
+function fakeSender(...outcomes: SendOutcome[]) {
+ const sent: { email: string; content: string }[] = [];
+ const sender: ZulipSender = {
+ send: async (email, content) => {
+ sent.push({ email, content });
+ return outcomes.shift() ?? "sent";
+ },
+ };
+ return { sender, sent };
+}
+
+function setEmail(userId: number, email: string | null) {
+ t.db.update(users).set({ email }).where(eq(users.id, userId)).run();
+}
+
+function caseFor(applicantId: number, no: string) {
+ const id = insertApplication(t.db, {
+ applicantId,
+ departmentId: f.design,
+ status: "pending_review",
+ });
+ t.db.update(applications).set({ applicationNo: no }).where(eq(applications.id, id)).run();
+ return id;
+}
+
+function addNotification(
+ recipientId: number,
+ type: "application.pending_review" | "application.returned" | "application.approved",
+ applicationId: number,
+ opts: { title?: string; createdAt?: string; readAt?: string } = {},
+) {
+ return t.db
+ .insert(notifications)
+ .values({
+ recipientId,
+ type,
+ title: opts.title ?? "有新的待審案件",
+ body: "王小明:AS-1(ChatGPT NT$1,000)",
+ href: `/applications/${applicationId}`,
+ targetKey: String(applicationId),
+ createdAt: opts.createdAt ?? "2026-11-11T07:59:00.000Z",
+ readAt: opts.readAt ?? null,
+ })
+ .returning({ id: notifications.id })
+ .get().id;
+}
+
+function addReturn(applicationId: number, comment: string) {
+ t.db
+ .insert(applicationTransitions)
+ .values({
+ applicationId,
+ action: "return",
+ fromStatus: "pending_review",
+ toStatus: "needs_revision",
+ actorLabel: "設計主管",
+ comment,
+ occurredAt: "2026-11-11T07:58:00.000Z",
+ })
+ .run();
+}
+
+const status = (id: number) =>
+ t.db.select().from(notifications).where(eq(notifications.id, id)).get()!;
+
+beforeEach(() => {
+ t = createTestDatabase();
+ f = seedApplicationFixture(t.db);
+ setEmail(f.designManager.id, "manager@moonshine.tw");
+ setEmail(f.applicant.id, "applicant@moonshine.tw");
+ setEmail(f.colleague.id, "colleague@moonshine.tw");
+});
+afterEach(() => t.cleanup());
+
+describe("Zulip 派送", () => {
+ it("同一部長的多則待審合併成一則,列出申請人與案件編號,不含金額", async () => {
+ const a = caseFor(f.applicant.id, "AS-2026-0001");
+ const b = caseFor(f.colleague.id, "AS-2026-0002");
+ const n1 = addNotification(f.designManager.id, "application.pending_review", a);
+ const n2 = addNotification(f.designManager.id, "application.pending_review", b, {
+ title: "補件已重新送出,待審核",
+ });
+ const { sender, sent } = fakeSender();
+
+ expect(await runChatDispatch(t.db, sender, APP, NOW)).toBe(2);
+ expect(sent).toHaveLength(1);
+ expect(sent[0].email).toBe("manager@moonshine.tw");
+ expect(sent[0].content).toContain("你有 2 筆待審案件");
+ expect(sent[0].content).toContain("王小明 · AS-2026-0001");
+ expect(sent[0].content).toContain("同事 · AS-2026-0002(補件重送)");
+ expect(sent[0].content).toContain(`(${APP}/department/review)`);
+ expect(sent[0].content).not.toMatch(/NT\$/);
+ expect([status(n1).chatStatus, status(n2).chatStatus]).toEqual(["sent", "sent"]);
+
+ // 已處理的不再發
+ expect(await runChatDispatch(t.db, sender, APP, NOW)).toBe(0);
+ expect(sent).toHaveLength(1);
+ });
+
+ it("退回私訊含主管意見全文,@ 提及被中和,連到該案件", async () => {
+ const a = caseFor(f.applicant.id, "AS-2026-0003");
+ addReturn(a, "第一次意見");
+ addReturn(a, "請補上刷卡帳單\n並找 @**林坤靜** 確認");
+ addNotification(f.applicant.id, "application.returned", a, { title: "申請待補件" });
+ const { sender, sent } = fakeSender();
+
+ await runChatDispatch(t.db, sender, APP, NOW);
+ expect(sent).toHaveLength(1);
+ expect(sent[0].email).toBe("applicant@moonshine.tw");
+ expect(sent[0].content).toContain("1 筆申請被主管退回補件");
+ expect(sent[0].content).toContain("> 請補上刷卡帳單\n> 並找 @**林坤靜** 確認");
+ expect(sent[0].content).not.toContain("第一次意見");
+ expect(sent[0].content).toContain(`(${APP}/applications/${a})`);
+ });
+
+ it("已審核(待審通知已讀)、沒有 email、已停用的收件人略過不發", async () => {
+ const a = caseFor(f.applicant.id, "AS-2026-0004");
+ const read = addNotification(f.designManager.id, "application.pending_review", a, {
+ readAt: "2026-11-11T07:59:30.000Z",
+ });
+ setEmail(f.rndManager.id, null);
+ const noEmail = addNotification(f.rndManager.id, "application.pending_review", a);
+ t.db.update(users).set({ active: false }).where(eq(users.id, f.colleague.id)).run();
+ const inactive = addNotification(f.colleague.id, "application.returned", a);
+ const { sender, sent } = fakeSender();
+
+ await runChatDispatch(t.db, sender, APP, NOW);
+ expect(sent).toHaveLength(0);
+ for (const id of [read, noEmail, inactive]) expect(status(id).chatStatus).toBe("skipped");
+ });
+
+ it("其他通知類型與 24 小時前的通知不派送", async () => {
+ const a = caseFor(f.applicant.id, "AS-2026-0005");
+ const approved = addNotification(f.applicant.id, "application.approved", a);
+ const old = addNotification(f.designManager.id, "application.pending_review", a, {
+ createdAt: "2026-11-10T07:00:00.000Z",
+ });
+ const { sender, sent } = fakeSender();
+
+ expect(await runChatDispatch(t.db, sender, APP, NOW)).toBe(0);
+ expect(sent).toHaveLength(0);
+ expect(status(approved).chatStatus).toBeNull();
+ expect(status(old).chatStatus).toBeNull();
+ });
+
+ it("暫時性失敗重試,滿 3 次標為 failed", async () => {
+ const a = caseFor(f.applicant.id, "AS-2026-0006");
+ const id = addNotification(f.designManager.id, "application.pending_review", a);
+ const { sender, sent } = fakeSender("retry", "retry", "retry");
+
+ for (let i = 0; i < CHAT_MAX_ATTEMPTS + 1; i++) await runChatDispatch(t.db, sender, APP, NOW);
+ expect(sent).toHaveLength(CHAT_MAX_ATTEMPTS);
+ expect(status(id)).toMatchObject({ chatStatus: "failed", chatAttempts: CHAT_MAX_ATTEMPTS });
+ });
+
+ it("超過 10 筆只列前 10 筆並註明其餘筆數", async () => {
+ for (let i = 1; i <= 12; i++) {
+ const id = caseFor(f.applicant.id, `AS-2026-01${String(i).padStart(2, "0")}`);
+ addNotification(f.designManager.id, "application.pending_review", id);
+ }
+ const { sender, sent } = fakeSender();
+ await runChatDispatch(t.db, sender, APP, NOW);
+ expect(sent[0].content).toContain("你有 12 筆待審案件");
+ expect(sent[0].content).toContain("AS-2026-0110");
+ expect(sent[0].content).not.toContain("AS-2026-0111");
+ expect(sent[0].content).toContain("另有 2 筆");
+ });
+});
+
+describe("Zulip 發送器", () => {
+ const env = (extra: Record = {}) =>
+ parseEnv({
+ AUTH_MODE: "dev",
+ SESSION_SECRET: "x".repeat(32),
+ APP_URL: APP,
+ ZULIP_SITE: "https://chat.example.tw/",
+ ZULIP_BOT_EMAIL: "bot@chat.example.tw",
+ ZULIP_API_KEY: "secret-key",
+ ...extra,
+ });
+ const respond = (status: number, body: object = {}) =>
+ vi.fn().mockResolvedValue(new Response(JSON.stringify(body), { status }));
+
+ it("沒設定時不建立發送器", () => {
+ expect(zulipSenderFromEnv(parseEnv({ AUTH_MODE: "dev" }))).toBeNull();
+ });
+
+ it("以 Basic auth 私訊該 email", async () => {
+ const fetchImpl = respond(200, { result: "success" });
+ expect(await zulipSenderFromEnv(env(), fetchImpl)!.send("a@moonshine.tw", "hi")).toBe("sent");
+ const [url, init] = fetchImpl.mock.calls[0];
+ expect(url).toBe("https://chat.example.tw/api/v1/messages");
+ expect((init!.headers as Record).Authorization).toBe(
+ `Basic ${Buffer.from("bot@chat.example.tw:secret-key").toString("base64")}`,
+ );
+ const body = init!.body as URLSearchParams;
+ expect(body.get("type")).toBe("private");
+ expect(body.get("to")).toBe('["a@moonshine.tw"]');
+ });
+
+ it("dry-run 不呼叫 Zulip", async () => {
+ const fetchImpl = respond(200);
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ const sender = zulipSenderFromEnv(env({ ZULIP_DELIVERY: "dry-run" }), fetchImpl)!;
+ expect(await sender.send("a@moonshine.tw", "hi")).toBe("dry_run");
+ expect(fetchImpl).not.toHaveBeenCalled();
+ info.mockRestore();
+ });
+
+ it("找不到人略過、429/5xx/連線失敗重試、401 失敗", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const send = (fetchImpl: typeof fetch) =>
+ zulipSenderFromEnv(env(), fetchImpl)!.send("a@moonshine.tw", "hi");
+ expect(await send(respond(400, { result: "error", msg: "Invalid email 'a@x'" }))).toBe(
+ "skipped",
+ );
+ expect(await send(respond(429))).toBe("retry");
+ expect(await send(respond(502))).toBe("retry");
+ expect(await send(vi.fn().mockRejectedValue(new Error("down")))).toBe("retry");
+ expect(await send(respond(401, { result: "error", msg: "Invalid API key" }))).toBe("failed");
+ expect(warn.mock.calls.flat().join()).not.toContain("secret-key");
+ warn.mockRestore();
+ });
+});
+
+describe("quoteUserText", () => {
+ it("每行放進引用區塊並中和 @", () => {
+ expect(quoteUserText(" 請找 @**王** \n補件 ")).toBe("> 請找 @**王**\n> 補件");
+ });
+});
diff --git a/src/server/notifications/zulip.ts b/src/server/notifications/zulip.ts
new file mode 100644
index 0000000..2a21b08
--- /dev/null
+++ b/src/server/notifications/zulip.ts
@@ -0,0 +1,244 @@
+import { and, desc, eq, gte, inArray, isNull, lt } from "drizzle-orm";
+import {
+ CHAT_NOTIFICATION_TYPES,
+ type ChatNotificationType,
+ type ChatStatus,
+} from "@/lib/notifications";
+import type { Db } from "@/server/db/client";
+import { applicationTransitions, applications, notifications, users } from "@/server/db/schema";
+import { zulipConfigured, type Env } from "@/server/env";
+
+// Zulip 私訊(zulip-notifications):待審與退回兩種站內通知,交易提交後由每分鐘的派送工作
+// 合併成一則私訊發給同一位收件人。發送失敗只記 log,不影響案件操作與站內通知(design Z1–Z4)。
+
+/** 待發列最多嘗試幾次(網路錯誤、逾時、429、5xx 才會重試)。 */
+export const CHAT_MAX_ATTEMPTS = 3;
+/** 只派送這段時間內產生的通知:上線前與停機期間累積的舊通知不補發。 */
+export const CHAT_WINDOW_MS = 24 * 60 * 60 * 1000;
+/** 待審合併訊息最多列幾筆案件,其餘只寫筆數。 */
+export const CHAT_LIST_LIMIT = 10;
+const TIMEOUT_MS = 5_000;
+const HEADER = "**AI 補助申請系統**";
+
+/** 單次發送的結果:`retry` 是暫時性失敗,下一輪再試。 */
+export type SendOutcome = ChatStatus | "retry";
+
+export interface ZulipSender {
+ /** 私訊一個人。只有 Zulip 回 success 才是 `sent`。 */
+ send(email: string, content: string): Promise;
+}
+
+/** 以環境變數建立發送器;設定不齊時回傳 null(只發站內通知)。 */
+export function zulipSenderFromEnv(env: Env, fetchImpl: typeof fetch = fetch): ZulipSender | null {
+ if (!zulipConfigured(env)) return null;
+ const auth = Buffer.from(`${env.ZULIP_BOT_EMAIL}:${env.ZULIP_API_KEY}`).toString("base64");
+ const url = `${env.ZULIP_SITE!.replace(/\/$/, "")}/api/v1/messages`;
+ return {
+ async send(email, content) {
+ if (env.ZULIP_DELIVERY === "dry-run") {
+ console.info("[zulip] dry-run,未實際發送", { to: email, content });
+ return "dry_run";
+ }
+ let res: Response;
+ try {
+ res = await fetchImpl(url, {
+ method: "POST",
+ headers: {
+ Authorization: `Basic ${auth}`,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ // "private" 新舊版 Zulip 都接受(新版的 "direct" 是同一件事)。
+ body: new URLSearchParams({ type: "private", to: JSON.stringify([email]), content }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (error) {
+ console.warn("[zulip] 連線失敗,稍後重試:", error instanceof Error ? error.name : error);
+ return "retry";
+ }
+ if (res.ok) return "sent";
+ if (res.status === 429 || res.status >= 500) return "retry";
+ const msg = await res
+ .json()
+ .then((body: { msg?: string }) => body.msg ?? "")
+ .catch(() => "");
+ // 對方沒登入過 Zulip:找不到人,略過不重試。
+ if (res.status === 400 && /invalid email/i.test(msg)) return "skipped";
+ // 401:bot email 或 API key 錯、bot 已停用。不印出金鑰或訊息內容。
+ console.warn(`[zulip] 發送失敗(HTTP ${res.status})`);
+ return "failed";
+ },
+ };
+}
+
+/** 使用者輸入的文字放進 Zulip Markdown:中和 `@` 提及,每行放進引用區塊。 */
+export function quoteUserText(text: string): string {
+ return text
+ .trim()
+ .replaceAll("@", "@")
+ .split(/\r?\n/)
+ .map((line) => `> ${line.trimEnd()}`)
+ .join("\n");
+}
+
+interface CaseItem {
+ applicationId: number;
+ label: string;
+ applicant: string;
+ resubmitted: boolean;
+ comment: string | null;
+}
+
+export function pendingReviewMessage(appUrl: string, items: readonly CaseItem[]): string {
+ const shown = items.slice(0, CHAT_LIST_LIMIT).map((item) => {
+ const tag = item.resubmitted ? "(補件重送)" : "";
+ return `- ${item.applicant.replaceAll("@", "@")} · ${item.label}${tag}`;
+ });
+ const rest = items.length - shown.length;
+ return [
+ HEADER,
+ `你有 ${items.length} 筆待審案件:`,
+ ...shown,
+ ...(rest > 0 ? [`- 另有 ${rest} 筆`] : []),
+ "",
+ `[前往審核](${appUrl}/department/review)`,
+ ].join("\n");
+}
+
+export function returnedMessage(appUrl: string, items: readonly CaseItem[]): string {
+ const blocks = items.map((item) =>
+ [`**${item.label}**`, item.comment ? quoteUserText(item.comment) : "> (未填寫意見)"].join(
+ "\n",
+ ),
+ );
+ const link =
+ items.length === 1
+ ? `[查看並補件](${appUrl}/applications/${items[0].applicationId})`
+ : `[查看我的申請](${appUrl}/applications)`;
+ return [HEADER, `你有 ${items.length} 筆申請被主管退回補件:`, ...blocks, link].join("\n\n");
+}
+
+/**
+ * 派送一輪(每分鐘):取 24 小時內待發的待審與退回通知;案件已審(待審通知已讀)或收件人沒有
+ * email、已停用 → 略過;其餘依(收件人、類型)合併成一則私訊,結果寫回組內每一列。回傳處理的列數。
+ */
+export async function runChatDispatch(
+ db: Db,
+ sender: ZulipSender,
+ appUrl: string,
+ now: Date,
+): Promise {
+ const since = new Date(now.getTime() - CHAT_WINDOW_MS).toISOString();
+ const rows = db
+ .select({
+ id: notifications.id,
+ type: notifications.type,
+ title: notifications.title,
+ targetKey: notifications.targetKey,
+ readAt: notifications.readAt,
+ attempts: notifications.chatAttempts,
+ recipientId: notifications.recipientId,
+ email: users.email,
+ active: users.active,
+ })
+ .from(notifications)
+ .innerJoin(users, eq(users.id, notifications.recipientId))
+ .where(
+ and(
+ isNull(notifications.chatStatus),
+ inArray(notifications.type, [...CHAT_NOTIFICATION_TYPES]),
+ lt(notifications.chatAttempts, CHAT_MAX_ATTEMPTS),
+ gte(notifications.createdAt, since),
+ ),
+ )
+ .orderBy(notifications.id)
+ .all();
+ if (rows.length === 0) return 0;
+
+ const stamp = now.toISOString();
+ const mark = (ids: number[], status: ChatStatus) =>
+ db
+ .update(notifications)
+ .set({ chatStatus: status, chatAt: stamp })
+ .where(inArray(notifications.id, ids))
+ .run();
+
+ const skip: number[] = [];
+ const groups = new Map();
+ for (const row of rows) {
+ const stale = row.type === "application.pending_review" && row.readAt !== null;
+ if (stale || !row.email || !row.active) {
+ skip.push(row.id);
+ continue;
+ }
+ const key = `${row.recipientId}|${row.type}`;
+ groups.set(key, [...(groups.get(key) ?? []), row]);
+ }
+ if (skip.length > 0) mark(skip, "skipped");
+
+ for (const group of groups.values()) {
+ const ids = group.map((r) => r.id);
+ const type = group[0].type as ChatNotificationType;
+ const items = caseItems(
+ db,
+ type,
+ group.map((r) => ({ applicationId: Number(r.targetKey), title: r.title })),
+ );
+ const content =
+ type === "application.pending_review"
+ ? pendingReviewMessage(appUrl, items)
+ : returnedMessage(appUrl, items);
+ const outcome = await sender.send(group[0].email!, content);
+ if (outcome === "retry") {
+ const exhausted = group.filter((r) => r.attempts + 1 >= CHAT_MAX_ATTEMPTS).map((r) => r.id);
+ db.update(notifications)
+ .set({ chatAttempts: group[0].attempts + 1, chatAt: stamp })
+ .where(inArray(notifications.id, ids))
+ .run();
+ if (exhausted.length > 0) mark(exhausted, "failed");
+ } else {
+ mark(ids, outcome);
+ }
+ }
+ return rows.length;
+}
+
+function caseItems(
+ db: Db,
+ type: ChatNotificationType,
+ entries: readonly { applicationId: number; title: string }[],
+): CaseItem[] {
+ return entries.map(({ applicationId, title }) => {
+ const app = db
+ .select({
+ applicationNo: applications.applicationNo,
+ name: users.name,
+ employeeNo: users.employeeNo,
+ })
+ .from(applications)
+ .innerJoin(users, eq(users.id, applications.applicantId))
+ .where(eq(applications.id, applicationId))
+ .get();
+ // 意見全文取該案件最新一筆退回(站內通知內文是截短版)。
+ const comment =
+ type === "application.returned"
+ ? (db
+ .select({ comment: applicationTransitions.comment })
+ .from(applicationTransitions)
+ .where(
+ and(
+ eq(applicationTransitions.applicationId, applicationId),
+ eq(applicationTransitions.action, "return"),
+ ),
+ )
+ .orderBy(desc(applicationTransitions.id))
+ .get()?.comment ?? null)
+ : null;
+ return {
+ applicationId,
+ label: app?.applicationNo ?? `#${applicationId}`,
+ applicant: app ? (app.name ?? app.employeeNo) : "--",
+ resubmitted: title.startsWith("補件"),
+ comment,
+ };
+ });
+}
diff --git a/src/server/startup.ts b/src/server/startup.ts
index 372a766..43b8394 100644
--- a/src/server/startup.ts
+++ b/src/server/startup.ts
@@ -5,7 +5,8 @@ import { runMigrations } from "@/server/db/migrate";
import { getEnv } from "@/server/env";
import { ensureDefaultRuleVersion, ensureHalfSubsidyVersion } from "@/server/rules/params";
import { rebaseHeadcountSnapshots } from "@/server/rules/rebase-snapshots";
-import { startReminderScheduler } from "@/server/notifications/scheduler";
+import { startChatScheduler, startReminderScheduler } from "@/server/notifications/scheduler";
+import { zulipSenderFromEnv } from "@/server/notifications/zulip";
import { clearStalePendingReviews } from "@/server/notifications/service";
import { startSettlementScheduler } from "@/server/settlement/scheduler";
import { appNow, realNow, systemTimeAt } from "@/server/clock";
@@ -55,4 +56,12 @@ export function startBackgroundJobs(): void {
}
startSettlementScheduler(db, getEnv().TZ_APP);
startReminderScheduler(db, getEnv().TZ_APP);
+ // 待審與退回同時私訊 Zulip(zulip-notifications);沒設定時只發站內通知。
+ const env = getEnv();
+ const sender = zulipSenderFromEnv(env);
+ if (sender) startChatScheduler(db, sender, env.APP_URL!);
+ else
+ console.warn(
+ "[startup] Zulip 通知未設定(ZULIP_SITE/ZULIP_BOT_EMAIL/ZULIP_API_KEY/APP_URL),只發站內通知",
+ );
}
diff --git a/vibe.yaml b/vibe.yaml
index efbd0d6..da36b4c 100644
--- a/vibe.yaml
+++ b/vibe.yaml
@@ -24,3 +24,7 @@ environment:
- SESSION_SECRET
- APP_URL
- BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS
+ # Zulip 待審與退回私訊(zulip-notifications)。ZULIP_DELIVERY 只在本機用,不列在這裡。
+ - ZULIP_SITE
+ - ZULIP_BOT_EMAIL
+ - ZULIP_API_KEY