zulip-notifications: 待審 (incl. resubmits) and 退回補件 notifications are also sent as Zulip direct messages to the recipient's account email via an incoming-webhook bot (user decision 2026-11-11: only these two). notifications gets chat_status / chat_attempts / chat_at as the outbox; a per-minute dispatcher (after the business transaction) merges each recipient's pending rows into one message: reviews list applicant + case number (first 10), returns include the full manager comment with @ mentions neutralized; no amounts. Already-reviewed cases, recipients without email or inactive, and rows older than 24 h are skipped; transient failures retry 3 times, failures only log. ZULIP_SITE / ZULIP_BOT_EMAIL / ZULIP_API_KEY added to vibe.yaml (values in .env.deploy); missing config keeps the site running with in-app notifications only; ZULIP_DELIVERY=dry-run for local use. Help page and CLAUDE.md updated; change archived into notifications
CI / build (push) Successful in 4m53s
CI / build (push) Successful in 4m53s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
622dcbbf79
commit
e600048c3d
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-11
|
||||
@@ -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(寫進說明)。
|
||||
@@ -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 私訊。
|
||||
- 不改權限:收件人與站內通知完全相同(部門主管、申請人本人)。
|
||||
@@ -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 私訊
|
||||
@@ -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` 照舊通過。
|
||||
@@ -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 私訊
|
||||
|
||||
@@ -43,6 +43,13 @@ export default async function HelpPage() {
|
||||
第一次以公司帳號登入時系統會自動建立帳號。部門與部門主管依人資資料於登入時更新;人事異動後尚未反映時,請重新登入,仍不正確請洽系統管理員。
|
||||
</p>
|
||||
</Card>
|
||||
<Card title="通知">
|
||||
<p className="text-ink/90">
|
||||
通知會出現在右上角的鈴鐺。主管有新的待審案件、或申請被退回補件時,也會同時收到公司 Zulip
|
||||
的私訊(主管意見會寫在訊息裡,短時間內多筆會合併成一則);尚未登入過 Zulip
|
||||
的人只會收到站內通知。
|
||||
</p>
|
||||
</Card>
|
||||
<Card title="補助怎麼算">
|
||||
<ul className="list-disc space-y-2 pl-5 text-ink/90">
|
||||
<li>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
+16
-1
@@ -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: "[email protected]",
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<typeof seedApplicationFixture>;
|
||||
|
||||
/** 記錄每次發送的假發送器;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, "[email protected]");
|
||||
setEmail(f.applicant.id, "[email protected]");
|
||||
setEmail(f.colleague.id, "[email protected]");
|
||||
});
|
||||
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("[email protected]");
|
||||
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("[email protected]");
|
||||
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<string, string> = {}) =>
|
||||
parseEnv({
|
||||
AUTH_MODE: "dev",
|
||||
SESSION_SECRET: "x".repeat(32),
|
||||
APP_URL: APP,
|
||||
ZULIP_SITE: "https://chat.example.tw/",
|
||||
ZULIP_BOT_EMAIL: "[email protected]",
|
||||
ZULIP_API_KEY: "secret-key",
|
||||
...extra,
|
||||
});
|
||||
const respond = (status: number, body: object = {}) =>
|
||||
vi.fn<typeof fetch>().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("[email protected]", "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<string, string>).Authorization).toBe(
|
||||
`Basic ${Buffer.from("[email protected]:secret-key").toString("base64")}`,
|
||||
);
|
||||
const body = init!.body as URLSearchParams;
|
||||
expect(body.get("type")).toBe("private");
|
||||
expect(body.get("to")).toBe('["[email protected]"]');
|
||||
});
|
||||
|
||||
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("[email protected]", "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("[email protected]", "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<typeof fetch>().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> 補件");
|
||||
});
|
||||
});
|
||||
@@ -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<SendOutcome>;
|
||||
}
|
||||
|
||||
/** 以環境變數建立發送器;設定不齊時回傳 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<number> {
|
||||
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<string, typeof rows>();
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
+10
-1
@@ -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),只發站內通知",
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user