From ee85c7b150883789b6babd0a84691a9fe0273c55 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:15:14 +0800 Subject: [PATCH] feat(worker): route unselected notifications to default channel (ONE-154) --- CLAUDE.md | 6 +- README.en.md | 10 +- README.md | 10 +- worker/src/db/queries/notifications.ts | 1 + worker/src/db/schema.sql | 1 + worker/src/lib/setup.ts | 44 +++- worker/src/routes/items.ts | 33 ++- worker/src/routes/me.ts | 30 ++- worker/src/routes/notify.ts | 44 +++- worker/src/services/notify/index.ts | 17 +- worker/src/services/scheduler.ts | 32 ++- worker/src/types.ts | 1 + worker/test/default-channel.test.ts | 336 +++++++++++++++++++++++++ worker/test/email-notify.test.ts | 1 + worker/test/me-notifications.test.ts | 84 +++++++ worker/test/migrations.test.ts | 68 +++++ 16 files changed, 673 insertions(+), 45 deletions(-) create mode 100644 worker/test/default-channel.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index b85d26b..a5459ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,13 +67,13 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `lunar.ts` — Chinese lunar calendar support (1900–2100) - `currency.ts` — multi-currency / exchange rate conversion -**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter. +**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` sends to selected enabled channels via the `channels` parameter, or only to the user's default channel when no channels are selected. **Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it: 1. Checks their allowed notification hours (per-timezone). 2. Auto-renews expired items (with KV deduplication). -3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise all enabled channels receive the notification. +3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise only the user's default channel receives the notification. **Cloudflare bindings**: @@ -101,7 +101,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - **UI (zh)**: shows "通知" / "通知管理" - **UI (en)**: shows "Notification" / "Notifications" - **`notification_config`** / `NotificationConfig` refers to push channel configuration, not items — these are separate concepts. -- **Code/UI for channels**: `channels` / `Channel` in code and nav. DB column `channels` on items stores a JSON array of channel IDs (e.g. `["telegram","email"]`). Empty array `[]` means "use all enabled channels". +- **Code/UI for channels**: `channels` / `Channel` in code and nav. DB column `channels` on items stores a JSON array of channel IDs (e.g. `["telegram","email"]`). Empty array `[]` means "use the default channel". - **UI (zh)**: shows "渠道" / "渠道管理" - **UI (en)**: shows "Channel" / "Channel Management" diff --git a/README.en.md b/README.en.md index 972c63d..31154f0 100644 --- a/README.en.md +++ b/README.en.md @@ -13,7 +13,7 @@ A smart notification management system that helps you track expiry dates and exp - **Dashboard** — Monthly/yearly expense stats, expiry alerts, category analysis - **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Slack, Feishu, Discord - **Channel Management** — Dedicated page to enable and configure notification channels -- **Per-Item Channel Selection** — Each notification item can specify which channels to use; defaults to all enabled channels if unset +- **Per-Item Channel Selection** — Each notification item can select multiple channels; if unset, only the default channel is used - **Scheduled Reminders** — Hourly auto-check with global notification hours and per-item override - **Notification History** — View all sent notifications with delivery status - **Two-Factor Auth** — TOTP (authenticator app), Email OTP, Passkey @@ -140,9 +140,15 @@ curl -X POST https://your-worker.workers.dev/api/notify \ -H "Authorization: Bearer enk_xxxxxxxx" \ -H "Content-Type: application/json" \ -d '{"title": "Reminder", "body": "Content", "url": "https://example.com"}' + +# Send only to Telegram and Bark +curl -X POST https://your-worker.workers.dev/api/notify \ + -H "Authorization: Bearer enk_xxxxxxxx" \ + -H "Content-Type: application/json" \ + -d '{"title": "Reminder", "body": "Content", "channels": ["telegram", "bark"]}' ``` -`POST /api/notify` sends a push to the user's enabled notification channels; `title` defaults to `Notification` when omitted. Besides the API key, it also accepts a cookie login session. +`POST /api/notify` accepts an optional `channels` array to select multiple channels. If omitted or empty, only the user's default channel is used. Unknown or disabled channels, and requests without channels when no default is configured, return 400 without sending. `title` defaults to `Notification` when omitted. Besides the API key, it also accepts a cookie login session. Each key is limited to 120 requests/minute (`429` beyond that). Invalid, expired or revoked keys get `401`; keys stop working as soon as their user is disabled. `/api/notify` has an additional per-IP limit of 30 requests/minute. diff --git a/README.md b/README.md index 19c02bd..2c3b42a 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ - **仪表盘** — 月度/年度支出统计、到期预警、分类分析 - **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Slack、飞书、Discord - **渠道管理** — 独立页面统一管理通知渠道的启用与配置 -- **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道 +- **按项选择渠道** — 每个通知项可单独多选使用哪些渠道,未指定则只使用默认渠道 - **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖 - **通知历史** — 查看所有已发送通知的记录与状态 - **两步验证** — TOTP(验证器应用)、邮箱验证码、Passkey @@ -145,9 +145,15 @@ curl -X POST https://your-worker.workers.dev/api/notify \ -H "Authorization: Bearer enk_xxxxxxxx" \ -H "Content-Type: application/json" \ -d '{"title": "提醒", "body": "内容", "url": "https://example.com"}' + +# 多选 Telegram 和 Bark,其他渠道不发送 +curl -X POST https://your-worker.workers.dev/api/notify \ + -H "Authorization: Bearer enk_xxxxxxxx" \ + -H "Content-Type: application/json" \ + -d '{"title": "提醒", "body": "内容", "channels": ["telegram", "bark"]}' ``` -`POST /api/notify` 会向该用户已启用的通知渠道发送推送;`title` 省略时默认为 `Notification`。该接口除了 API Key 也接受 cookie 登录态。 +`POST /api/notify` 请求体可带可选 `channels` 数组多选渠道;不带或为空数组时只发该用户的默认渠道。`channels` 含未知或未启用渠道、或未设默认渠道时返回 400 且不发送。`title` 省略时默认为 `Notification`。该接口除了 API Key 也接受 cookie 登录态。 每个 key 限流 120 次/分钟,超出返回 `429`。key 无效、过期或已吊销时返回 `401`;对应用户被禁用后其 key 立即失效。`/api/notify` 另有一层按 IP 的 30 次/分钟限流。 diff --git a/worker/src/db/queries/notifications.ts b/worker/src/db/queries/notifications.ts index 3cc2cea..64af03d 100644 --- a/worker/src/db/queries/notifications.ts +++ b/worker/src/db/queries/notifications.ts @@ -30,6 +30,7 @@ export async function upsertNotificationConfig( const fields: (keyof Omit)[] = [ "enabled_channels", + "default_channel", "telegram_config", "webhook_config", "wechatbot_config", diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index 08956f8..531b229 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -79,6 +79,7 @@ CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, enabled_channels TEXT NOT NULL DEFAULT '[]', + default_channel TEXT NOT NULL DEFAULT '', telegram_config TEXT NOT NULL DEFAULT '{}', webhook_config TEXT NOT NULL DEFAULT '{}', wechatbot_config TEXT NOT NULL DEFAULT '{}', diff --git a/worker/src/lib/setup.ts b/worker/src/lib/setup.ts index f16e127..7a1dfe8 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -72,16 +72,37 @@ async function runMigrations(db: D1Database, prefix: string): Promise { console.error("Migration failed for notification_configs table:", err); } + // Migration: add default_channel column to notification_configs. This must + // run before the retired-channel cleanup, which reads the new column. + try { + const notifCols = await db + .prepare(`PRAGMA table_info(${prefix}notification_configs)`) + .all<{ name: string }>(); + if (!notifCols.results.some((c) => c.name === "default_channel")) { + await db + .prepare( + `ALTER TABLE ${prefix}notification_configs ADD COLUMN default_channel TEXT NOT NULL DEFAULT ''`, + ) + .run(); + } + } catch (err) { + console.error("Migration failed for notification_configs table:", err); + } + // Migration: drop retired channels (serverchan/pushplus/gotify/notifyx) from - // enabled_channels. Their sender code is gone, so a stale ID would make every - // push fail with "Unknown channel" and write a notification_history row. + // enabled_channels and default_channel. Their sender code is gone, so stale + // enabled IDs would fail and a retired default would make routing fail too. // Idempotent: the second run finds nothing to strip and performs no UPDATE. try { const rows = await db .prepare( - `SELECT user_id, enabled_channels FROM ${prefix}notification_configs`, + `SELECT user_id, enabled_channels, default_channel FROM ${prefix}notification_configs`, ) - .all<{ user_id: string; enabled_channels: string }>(); + .all<{ + user_id: string; + enabled_channels: string; + default_channel: string; + }>(); for (const row of rows.results) { let channels: unknown; try { @@ -91,12 +112,20 @@ async function runMigrations(db: D1Database, prefix: string): Promise { } if (!Array.isArray(channels)) continue; const filtered = channels.filter((ch) => !RETIRED_CHANNELS.includes(ch)); - if (filtered.length === channels.length) continue; + const defaultChannel = RETIRED_CHANNELS.includes(row.default_channel) + ? "" + : row.default_channel; + if ( + filtered.length === channels.length && + defaultChannel === row.default_channel + ) { + continue; + } await db .prepare( - `UPDATE ${prefix}notification_configs SET enabled_channels = ? WHERE user_id = ?`, + `UPDATE ${prefix}notification_configs SET enabled_channels = ?, default_channel = ? WHERE user_id = ?`, ) - .bind(JSON.stringify(filtered), row.user_id) + .bind(JSON.stringify(filtered), defaultChannel, row.user_id) .run(); } } catch (err) { @@ -262,6 +291,7 @@ CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, enabled_channels TEXT NOT NULL DEFAULT '[]', + default_channel TEXT NOT NULL DEFAULT '', telegram_config TEXT NOT NULL DEFAULT '{}', webhook_config TEXT NOT NULL DEFAULT '{}', wechatbot_config TEXT NOT NULL DEFAULT '{}', diff --git a/worker/src/routes/items.ts b/worker/src/routes/items.ts index 0d473e6..be640f8 100644 --- a/worker/src/routes/items.ts +++ b/worker/src/routes/items.ts @@ -702,19 +702,26 @@ itemRoutes.post("/:id/test-notify", async (c) => { itemChannels = []; } - const results = await sendNotifications( - notifyConfig, - message, - c.env, - { - db: c.env.DB, - prefix, - userId, - itemId: id, - }, - itemChannels?.length ? itemChannels : undefined, - ); - return c.json({ results }); + try { + const results = await sendNotifications( + notifyConfig, + message, + c.env, + { + db: c.env.DB, + prefix, + userId, + itemId: id, + }, + itemChannels?.length ? itemChannels : undefined, + ); + return c.json({ results }); + } catch (err) { + return c.json( + { error: err instanceof Error ? err.message : String(err) }, + 400, + ); + } }); // Payment history diff --git a/worker/src/routes/me.ts b/worker/src/routes/me.ts index 9309a26..acf3342 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -240,11 +240,16 @@ meRoutes.get("/notifications", async (c) => { const config = await getNotificationConfig(c.env.DB, prefix, userId); if (!config) { - return c.json({ enabled_channels: [], notification_hours: [] }); + return c.json({ + enabled_channels: [], + default_channel: "", + notification_hours: [], + }); } // Redact sensitive fields - return configured flags instead const safeConfig: Record = { + default_channel: config.default_channel || "", enabled_channels: (() => { try { return JSON.parse(config.enabled_channels); @@ -334,6 +339,16 @@ meRoutes.put("/notifications", async (c) => { } updates.enabled_channels = JSON.stringify(body.enabled_channels); } + if (body.default_channel !== undefined) { + if ( + typeof body.default_channel !== "string" || + (body.default_channel !== "" && + !VALID_CHANNELS.includes(body.default_channel)) + ) { + return c.json({ error: "Invalid channel name" }, 400); + } + updates.default_channel = body.default_channel; + } if (body.notification_hours !== undefined) { if (!Array.isArray(body.notification_hours)) return c.json({ error: "notification_hours must be an array" }, 400); @@ -352,6 +367,19 @@ meRoutes.put("/notifications", async (c) => { const channels = VALID_CHANNELS; const existing = await getNotificationConfig(c.env.DB, prefix, userId); + + let finalEnabled: string[] = []; + try { + finalEnabled = + body.enabled_channels ?? JSON.parse(existing?.enabled_channels || "[]"); + } catch { + finalEnabled = []; + } + const finalDefault = body.default_channel ?? existing?.default_channel ?? ""; + if (finalDefault !== "" && !finalEnabled.includes(finalDefault)) { + return c.json({ error: "Default channel must be an enabled channel" }, 400); + } + for (const ch of channels) { if (body[`${ch}_config`]) { const existingConfig = existing diff --git a/worker/src/routes/notify.ts b/worker/src/routes/notify.ts index 7e11b53..a75b1a1 100644 --- a/worker/src/routes/notify.ts +++ b/worker/src/routes/notify.ts @@ -1,5 +1,5 @@ import { Hono } from "hono"; -import { getTablePrefix, type HonoEnv } from "../types"; +import { getTablePrefix, VALID_CHANNELS, type HonoEnv } from "../types"; import { getNotificationConfig } from "../db/queries/notifications"; import { sendNotifications, @@ -35,16 +35,54 @@ notifyRoutes.post("/", async (c) => { title?: string; body?: string; url?: string; + channels?: unknown; }>(); + let channels: string[] | undefined; + if (body.channels !== undefined) { + if (!Array.isArray(body.channels)) { + return c.json({ error: "channels must be an array" }, 400); + } + channels = body.channels; + const invalidChannel = channels.find((ch) => !VALID_CHANNELS.includes(ch)); + if (invalidChannel !== undefined) { + return c.json({ error: `Invalid channel name: ${invalidChannel}` }, 400); + } + let enabledChannels: string[]; + try { + enabledChannels = JSON.parse(notifyConfig.enabled_channels || "[]"); + } catch { + enabledChannels = []; + } + const disabledChannel = channels.find( + (ch) => !enabledChannels.includes(ch), + ); + if (disabledChannel) { + return c.json({ error: `Channel not enabled: ${disabledChannel}` }, 400); + } + } + const message: NotifyMessage = { title: body.title || "Notification", body: body.body || "", url: body.url, }; - const results = await sendNotifications(notifyConfig, message, c.env); - return c.json({ success: true, results }); + try { + const results = await sendNotifications( + notifyConfig, + message, + c.env, + undefined, + channels, + ); + return c.json({ success: true, results }); + } catch (err) { + return c.json( + { error: err instanceof Error ? err.message : String(err) }, + 400, + ); + } }); // Third-party token trigger — deprecated in favour of API keys. Return 410 diff --git a/worker/src/services/notify/index.ts b/worker/src/services/notify/index.ts index 8061665..2b53031 100644 --- a/worker/src/services/notify/index.ts +++ b/worker/src/services/notify/index.ts @@ -100,14 +100,27 @@ export async function sendNotifications( enabledChannels = []; } + let targetChannels: string[]; // If specific channels are requested, intersect with enabled channels if (channels && channels.length > 0) { - enabledChannels = enabledChannels.filter((ch) => channels.includes(ch)); + targetChannels = enabledChannels.filter((ch) => channels.includes(ch)); + if (targetChannels.length === 0) { + throw new Error("None of the requested channels are enabled"); + } + } else { + const defaultChannel = config.default_channel || ""; + if (defaultChannel === "") { + throw new Error("No default channel configured"); + } + if (!enabledChannels.includes(defaultChannel)) { + throw new Error(`Default channel is not enabled: ${defaultChannel}`); + } + targetChannels = [defaultChannel]; } const results: NotifyResult[] = []; - for (const channel of enabledChannels) { + for (const channel of targetChannels) { const sender = CHANNEL_SENDERS[channel]; if (!sender) { results.push({ channel, success: false, error: "Unknown channel" }); diff --git a/worker/src/services/scheduler.ts b/worker/src/services/scheduler.ts index 74d8bbc..e7cf32f 100644 --- a/worker/src/services/scheduler.ts +++ b/worker/src/services/scheduler.ts @@ -330,18 +330,26 @@ async function processSubscription( }; } - await sendNotifications( - notifyConfig, - message, - env, - { - db: env.DB, - prefix, - userId, - itemId: sub.id, - }, - channels, - ); + try { + await sendNotifications( + notifyConfig, + message, + env, + { + db: env.DB, + prefix, + userId, + itemId: sub.id, + }, + channels, + ); + } catch (err) { + console.error( + `Failed to resolve notification channels for item ${sub.id}:`, + err instanceof Error ? err.message : String(err), + ); + continue; + } await kv.put(dedupeKey, "1", { expirationTtl: 172800 }); } } diff --git a/worker/src/types.ts b/worker/src/types.ts index cd08e50..284c069 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -77,6 +77,7 @@ export interface PaymentHistory { export interface NotificationConfig { user_id: string; enabled_channels: string; + default_channel: string; telegram_config: string; webhook_config: string; wechatbot_config: string; diff --git a/worker/test/default-channel.test.ts b/worker/test/default-channel.test.ts new file mode 100644 index 0000000..9795e8b --- /dev/null +++ b/worker/test/default-channel.test.ts @@ -0,0 +1,336 @@ +import { DatabaseSync } from "node:sqlite"; +import { Hono } from "hono"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { sendNotifications } from "../src/services/notify/index"; +import { notifyRoutes } from "../src/routes/notify"; +import { itemRoutes } from "../src/routes/items"; +import { handleScheduled } from "../src/services/scheduler"; +import type { Env, NotificationConfig } from "../src/types"; +import { + cookieHeader, + makeToken, + MockKV, + request, + seedSession, +} from "./helpers"; + +class SqliteD1 { + readonly db = new DatabaseSync(":memory:"); + + constructor() { + this.db.exec(` + CREATE TABLE notification_configs ( + user_id TEXT PRIMARY KEY, + enabled_channels TEXT NOT NULL DEFAULT '[]', + default_channel TEXT NOT NULL DEFAULT '', + telegram_config TEXT NOT NULL DEFAULT '{}', + webhook_config TEXT NOT NULL DEFAULT '{}', + wechatbot_config TEXT NOT NULL DEFAULT '{}', + email_config TEXT NOT NULL DEFAULT '{}', + bark_config TEXT NOT NULL DEFAULT '{}', + slack_config TEXT NOT NULL DEFAULT '{}', + feishu_config TEXT NOT NULL DEFAULT '{}', + discord_config TEXT NOT NULL DEFAULT '{}', + notification_hours TEXT NOT NULL DEFAULT '[]', + updated_at TEXT NOT NULL DEFAULT '' + ); + CREATE TABLE items ( + id TEXT PRIMARY KEY, user_id TEXT, name TEXT, item_mode TEXT, + category TEXT, start_date TEXT, expiry_date TEXT, period_value INTEGER, + period_unit TEXT, reminder_unit TEXT, reminder_value INTEGER, notes TEXT, + amount REAL, currency TEXT, last_payment_date TEXT, is_active INTEGER, + auto_renew INTEGER, calendar_mode TEXT, lunar_expiry_date TEXT, + channels TEXT, notification_hours TEXT, item_kind TEXT, + created_at TEXT, updated_at TEXT + ); + CREATE TABLE users (id TEXT PRIMARY KEY, timezone TEXT, language TEXT, is_active INTEGER); + CREATE TABLE notification_history ( + id TEXT, user_id TEXT, item_id TEXT, channel TEXT, title TEXT, + body TEXT, success INTEGER, error TEXT, created_at TEXT + ); + `); + } + + prepare(sql: string): any { + const db = this.db; + const statement = () => db.prepare(sql); + return { + bind: (...args: unknown[]) => ({ + first: async () => + (statement().get(...(args as any[])) ?? null) as T | null, + all: async () => ({ + results: statement().all(...(args as any[])) as T[], + }), + run: async () => { + statement().run(...(args as any[])); + return { success: true }; + }, + }), + first: async () => (statement().get() ?? null) as T | null, + all: async () => ({ results: statement().all() as T[] }), + run: async () => { + statement().run(); + return { success: true }; + }, + }; + } +} + +function config(defaultChannel = "telegram"): NotificationConfig { + return { + user_id: "user-1", + enabled_channels: JSON.stringify(["telegram", "bark", "email"]), + default_channel: defaultChannel, + telegram_config: '{"bot_token":"token","chat_id":"1"}', + webhook_config: "{}", + wechatbot_config: "{}", + email_config: "{}", + bark_config: '{"device_key":"key"}', + slack_config: "{}", + feishu_config: "{}", + discord_config: "{}", + notification_hours: "[]", + updated_at: "", + }; +} + +const MESSAGE = { title: "Test", body: "Body" }; + +function calledChannels(fetchMock: ReturnType): string[] { + return fetchMock.mock.calls.map(([url]) => { + const value = String(url); + if (value.includes("api.telegram.org")) return "telegram"; + if (value.includes("api.day.app")) return "bark"; + throw new Error(`Unexpected sender URL: ${value}`); + }); +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe("sendNotifications default-channel resolution", () => { + let fetchMock: ReturnType; + + beforeEach(() => { + fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + }); + + it.each([ + ["omitted", undefined, ["telegram"]], + ["empty", [], ["telegram"]], + ["single selected", ["bark"], ["bark"]], + ["multiple selected", ["bark", "email"], ["bark", "email"]], + ])( + "uses the expected targets when channels are %s", + async (_name, channels, expected) => { + const results = await sendNotifications( + config(), + MESSAGE, + {} as Env, + undefined, + channels, + ); + expect(results.map((r) => r.channel)).toEqual(expected); + expect(calledChannels(fetchMock)).toEqual( + expected.filter((c) => c !== "email"), + ); + }, + ); + + it("throws when no requested channel is enabled and sends nothing", async () => { + await expect( + sendNotifications(config(), MESSAGE, {} as Env, undefined, ["wechatbot"]), + ).rejects.toThrow("None of the requested channels are enabled"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("throws when no default is configured", async () => { + await expect( + sendNotifications(config(""), MESSAGE, {} as Env), + ).rejects.toThrow("No default channel configured"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("throws when the default is not enabled", async () => { + await expect( + sendNotifications(config("wechatbot"), MESSAGE, {} as Env), + ).rejects.toThrow("Default channel is not enabled: wechatbot"); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +async function makeRouteEnv(db: SqliteD1, defaultChannel = "telegram") { + const current = config(defaultChannel); + db.db + .prepare( + `INSERT INTO notification_configs + (user_id, enabled_channels, default_channel, telegram_config, bark_config) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "user-1", + current.enabled_channels, + defaultChannel, + current.telegram_config, + current.bark_config, + ); + const env: Record = { + DB: db, + KV: new MockKV(), + JWT_SECRET: "test-jwt-secret-0123456789abcdef", + TABLE_PREFIX: "", + }; + await seedSession(env, "user-1", "session-1"); + return env; +} + +async function token() { + return makeToken("user", { sub: "user-1", sid: "session-1" }); +} + +describe("POST /api/notify channel routing", () => { + let db: SqliteD1; + let app: Hono; + let fetchMock: ReturnType; + + beforeEach(() => { + db = new SqliteD1(); + app = new Hono(); + app.route("/api/notify", notifyRoutes); + fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + }); + + async function post(body: unknown, defaultChannel = "telegram") { + const env = await makeRouteEnv(db, defaultChannel); + return request(app, env, "/api/notify", { + method: "POST", + headers: { + ...cookieHeader(await token()), + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }); + } + + it("sends only selected channels", async () => { + const res = await post({ title: "Test", channels: ["telegram", "bark"] }); + expect(res.status).toBe(200); + expect(res.body.results.map((r: any) => r.channel)).toEqual([ + "telegram", + "bark", + ]); + }); + + it("rejects an unknown channel without sending", async () => { + const res = await post({ channels: ["unknown"] }); + expect(res.status).toBe(400); + expect(res.body.error).toBe("Invalid channel name: unknown"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a valid but disabled channel without sending", async () => { + const res = await post({ channels: ["wechatbot"] }); + expect(res.status).toBe(400); + expect(res.body.error).toBe("Channel not enabled: wechatbot"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("uses only the default when channels are omitted", async () => { + const res = await post({ title: "Test" }); + expect(res.status).toBe(200); + expect(res.body.results.map((r: any) => r.channel)).toEqual(["telegram"]); + }); + + it("returns 400 without sending after the default is cleared", async () => { + const res = await post({ title: "Test" }, ""); + expect(res.status).toBe(400); + expect(res.body.error).toBe("No default channel configured"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a non-array channels value", async () => { + const res = await post({ channels: "telegram" }); + expect(res.status).toBe(400); + expect(res.body.error).toBe("channels must be an array"); + }); +}); + +describe("item and scheduler default-channel paths", () => { + let db: SqliteD1; + let fetchMock: ReturnType; + + beforeEach(() => { + db = new SqliteD1(); + fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + }); + + function seedItem() { + db.db + .prepare( + `INSERT INTO items + (id, user_id, name, item_mode, category, expiry_date, period_value, + period_unit, reminder_unit, reminder_value, notes, currency, is_active, + auto_renew, calendar_mode, channels, notification_hours, item_kind) + VALUES ('item-1', 'user-1', 'Test item', 'cycle', '', ?, 1, 'month', + 'day', 30, '', 'CNY', 1, 0, 'solar', '[]', '[]', 'subscription')`, + ) + .run(new Date(Date.now() + 86400000).toISOString().slice(0, 10)); + db.db.prepare("INSERT INTO users VALUES ('user-1', 'UTC', 'en', 1)").run(); + } + + it("test-notify uses the default and returns 400 when none is set", async () => { + seedItem(); + const app = new Hono(); + app.route("/api/items", itemRoutes); + const env = await makeRouteEnv(db); + const headers = cookieHeader(await token()); + const success = await request(app, env, "/api/items/item-1/test-notify", { + method: "POST", + headers, + }); + expect(success.status).toBe(200); + expect(success.body.results.map((r: any) => r.channel)).toEqual([ + "telegram", + ]); + + db.db.prepare("UPDATE notification_configs SET default_channel = ''").run(); + const failure = await request(app, env, "/api/items/item-1/test-notify", { + method: "POST", + headers, + }); + expect(failure.status).toBe(400); + expect(failure.body.error).toBe("No default channel configured"); + }); + + it("scheduler skips dedupe on resolution failure and succeeds after fixing the default", async () => { + seedItem(); + const env = (await makeRouteEnv(db, "")) as unknown as Env; + const kv = env.KV as unknown as MockKV; + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + await handleScheduled(env); + expect(fetchMock).not.toHaveBeenCalled(); + expect( + [...kv.store.keys()].some((k) => k.startsWith("notify_dedupe:")), + ).toBe(false); + expect(errorMock).toHaveBeenCalledWith( + expect.stringContaining("item-1"), + "No default channel configured", + ); + + db.db + .prepare("UPDATE notification_configs SET default_channel = 'telegram'") + .run(); + await handleScheduled(env); + expect(calledChannels(fetchMock)).toEqual(["telegram"]); + expect( + [...kv.store.keys()].some((k) => k.startsWith("notify_dedupe:")), + ).toBe(true); + }); +}); diff --git a/worker/test/email-notify.test.ts b/worker/test/email-notify.test.ts index 3310b91..1fc0588 100644 --- a/worker/test/email-notify.test.ts +++ b/worker/test/email-notify.test.ts @@ -464,6 +464,7 @@ describe("sendNotifyEmail", () => { { user_id: "user-1", enabled_channels: JSON.stringify(["email"]), + default_channel: "email", email_config: JSON.stringify({ to: "user@example.com" }), } as any, MESSAGE, diff --git a/worker/test/me-notifications.test.ts b/worker/test/me-notifications.test.ts index 0dec07f..46cc602 100644 --- a/worker/test/me-notifications.test.ts +++ b/worker/test/me-notifications.test.ts @@ -67,6 +67,90 @@ async function makeLoggedInEnv(db: ConfigDB): Promise> { return env; } +describe("GET/PUT /api/me/notifications — default channel", () => { + let db: ConfigDB; + let app: Hono; + let env: Record; + let token: string; + + beforeEach(async () => { + db = new ConfigDB(); + app = makeApp(); + env = await makeLoggedInEnv(db); + token = await makeToken("user", { sub: "user-1", sid: "session-1" }); + }); + + async function put(body: Record) { + return request(app, env, "/api/me/notifications", { + method: "PUT", + headers: { ...cookieHeader(token), "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + } + + function seed(enabled = ["telegram", "bark"], defaultChannel = "") { + db.rows.set("user-1", { + user_id: "user-1", + enabled_channels: JSON.stringify(enabled), + default_channel: defaultChannel, + notification_hours: "[]", + updated_at: new Date().toISOString(), + }); + } + + it("returns an empty default when no config row exists", async () => { + const res = await request(app, env, "/api/me/notifications", { + headers: cookieHeader(token), + }); + expect(res.status).toBe(200); + expect(res.body.default_channel).toBe(""); + }); + + it("stores and reads an enabled default", async () => { + seed(); + expect((await put({ default_channel: "telegram" })).status).toBe(200); + expect(db.rows.get("user-1")?.default_channel).toBe("telegram"); + const res = await request(app, env, "/api/me/notifications", { + headers: cookieHeader(token), + }); + expect(res.body.default_channel).toBe("telegram"); + }); + + it("rejects a disabled default without changing the stored config", async () => { + seed(["telegram"], "telegram"); + const before = { ...db.rows.get("user-1") }; + const res = await put({ default_channel: "bark" }); + expect(res.status).toBe(400); + expect(res.body.error).toBe("Default channel must be an enabled channel"); + expect(db.rows.get("user-1")).toEqual(before); + }); + + it("rejects disabling the current default without changing the stored config", async () => { + seed(["telegram", "bark"], "telegram"); + const before = { ...db.rows.get("user-1") }; + const res = await put({ enabled_channels: ["bark"] }); + expect(res.status).toBe(400); + expect(db.rows.get("user-1")).toEqual(before); + }); + + it("allows changing enabled channels and the default atomically", async () => { + seed(["telegram", "bark"], "telegram"); + const res = await put({ + enabled_channels: ["bark"], + default_channel: "bark", + }); + expect(res.status).toBe(200); + expect(db.rows.get("user-1")?.enabled_channels).toBe('["bark"]'); + expect(db.rows.get("user-1")?.default_channel).toBe("bark"); + }); + + it("allows clearing the default", async () => { + seed(["telegram"], "telegram"); + expect((await put({ default_channel: "" })).status).toBe(200); + expect(db.rows.get("user-1")?.default_channel).toBe(""); + }); +}); + describe("GET/PUT /api/me/notifications — per-user SMTP credentials", () => { let db: ConfigDB; let app: Hono; diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index cc49e05..a16693e 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -114,6 +114,72 @@ type ColumnInfo = { dflt_value: string | null; }; +describe("notification_configs default_channel migration", () => { + it("adds an empty default, keeps existing data and is idempotent", async () => { + const d1 = new SqliteD1(); + d1.db.exec(OLD_SCHEMA); + + await runSetup(makeEnv(d1)); + const columns = d1.db + .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) + .all() as ColumnInfo[]; + const column = columns.find((c) => c.name === "default_channel"); + expect(column).toMatchObject({ + type: "TEXT", + notnull: 1, + dflt_value: "''", + }); + const row = d1.db + .prepare( + `SELECT * FROM ${PREFIX}notification_configs WHERE user_id = 'u1'`, + ) + .get() as Record; + expect(row.default_channel).toBe(""); + expect(row.enabled_channels).toBe('["telegram"]'); + expect(row.notification_hours).toBe("[8,9]"); + + await runSetup(makeEnv(d1)); + const after = d1.db + .prepare( + `SELECT * FROM ${PREFIX}notification_configs WHERE user_id = 'u1'`, + ) + .get(); + expect(after).toEqual(row); + }); + + it("clears only retired default channels", async () => { + const d1 = new SqliteD1(); + d1.db.exec(OLD_SCHEMA); + d1.db + .prepare( + `ALTER TABLE ${PREFIX}notification_configs ADD COLUMN default_channel TEXT NOT NULL DEFAULT ''`, + ) + .run(); + d1.db + .prepare( + `UPDATE ${PREFIX}notification_configs SET default_channel = 'gotify' WHERE user_id = 'u1'`, + ) + .run(); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, enabled_channels, default_channel, updated_at) + VALUES ('u2', '["bark"]', 'bark', '2026-01-01T00:00:00.000Z')`, + ) + .run(); + + await runSetup(makeEnv(d1)); + const rows = d1.db + .prepare( + `SELECT user_id, enabled_channels, default_channel FROM ${PREFIX}notification_configs ORDER BY user_id`, + ) + .all(); + expect(rows).toEqual([ + { user_id: "u1", enabled_channels: '["telegram"]', default_channel: "" }, + { user_id: "u2", enabled_channels: '["bark"]', default_channel: "bark" }, + ]); + }); +}); + describe("notification_configs slack_config migration", () => { it("adds slack_config with a '{}' default and keeps existing data", async () => { const d1 = new SqliteD1(); @@ -362,6 +428,7 @@ describe("retired channel cleanup migration", () => { prefix: PREFIX, userId: "u1", }, + ["telegram"], ); expect(results).toEqual([{ channel: "telegram", success: true }]); @@ -391,6 +458,7 @@ describe("fresh install schema", () => { expect(names).not.toContain("pushplus_config"); expect(names).not.toContain("gotify_config"); expect(names).not.toContain("notifyx_config"); + expect(names).toContain("default_channel"); expect(names).toContain("slack_config"); expect(names).toContain("feishu_config"); expect(names).toContain("discord_config");