From 6ee93f5ec56e53f22881f91a2baf1b6469215983 Mon Sep 17 00:00:00 2001 From: Todos Date: Wed, 28 Oct 2026 13:06:16 +0800 Subject: [PATCH 1/2] feat(worker): add trigger_source to notification history Record item/api/test provenance, add channel/success/source filters, and update the shared web type. Checkpoint: VsCbE0EXd7kBjUoypDpX1 --- web/src/types/index.ts | 1 + worker/src/db/queries/notification-history.ts | 44 +- worker/src/lib/migrations.ts | 13 + worker/src/routes/me.ts | 25 +- worker/src/routes/notify.ts | 8 +- worker/src/services/notify/index.ts | 3 + worker/src/services/scheduler.ts | 1 + worker/test/admin.test.ts | 10 +- worker/test/ledger.test.ts | 73 +++- worker/test/migrations.test.ts | 30 +- worker/test/notification-history.test.ts | 398 ++++++++++++++++++ worker/test/prefix.test.ts | 15 +- worker/test/setup.test.ts | 15 +- 13 files changed, 599 insertions(+), 37 deletions(-) create mode 100644 worker/test/notification-history.test.ts diff --git a/web/src/types/index.ts b/web/src/types/index.ts index 7cb8b9d..0a5f35c 100644 --- a/web/src/types/index.ts +++ b/web/src/types/index.ts @@ -111,5 +111,6 @@ export interface NotificationHistory { body: string | null; success: number; error: string | null; + trigger_source: string | null; created_at: string; } diff --git a/worker/src/db/queries/notification-history.ts b/worker/src/db/queries/notification-history.ts index 9bf6ff6..32ccd8d 100644 --- a/worker/src/db/queries/notification-history.ts +++ b/worker/src/db/queries/notification-history.ts @@ -7,9 +7,17 @@ export interface NotificationHistoryRecord { body: string | null; success: number; error: string | null; + trigger_source: string | null; created_at: string; } +export interface ListHistoryOptions { + limit?: number; + channel?: string; + success?: boolean; + triggerSource?: string; +} + export async function insertNotificationHistory( db: D1Database, prefix: string, @@ -22,12 +30,13 @@ export async function insertNotificationHistory( body?: string | null; success: boolean; error?: string | null; + trigger_source?: string | null; }, ): Promise { await db .prepare( - `INSERT INTO ${prefix}notification_history (id, user_id, item_id, channel, title, body, success, error, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO ${prefix}notification_history (id, user_id, item_id, channel, title, body, success, error, trigger_source, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .bind( record.id, @@ -38,27 +47,50 @@ export async function insertNotificationHistory( record.body ?? null, record.success ? 1 : 0, record.error ?? null, + record.trigger_source ?? null, new Date().toISOString(), ) .run(); } +function normalizeLimit(limit: number | undefined): number { + if (limit === undefined || !Number.isFinite(limit)) return 50; + return Math.min(Math.max(Math.trunc(limit), 1), 200); +} + export async function listNotificationHistory( db: D1Database, prefix: string, userId: string, - limit = 50, -): Promise { + options: ListHistoryOptions = {}, +): Promise<(NotificationHistoryRecord & { item_name?: string })[]> { + const where = ["h.user_id = ?"]; + const params: (string | number)[] = [userId]; + + if (options.channel) { + where.push("h.channel = ?"); + params.push(options.channel); + } + if (options.success !== undefined) { + where.push("h.success = ?"); + params.push(options.success ? 1 : 0); + } + if (options.triggerSource) { + where.push("h.trigger_source = ?"); + params.push(options.triggerSource); + } + params.push(normalizeLimit(options.limit)); + const result = await db .prepare( `SELECT h.*, i.name as item_name FROM ${prefix}notification_history h LEFT JOIN ${prefix}items i ON i.id = h.item_id - WHERE h.user_id = ? + WHERE ${where.join(" AND ")} ORDER BY h.created_at DESC LIMIT ?`, ) - .bind(userId, limit) + .bind(...params) .all(); return result.results; } diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts index 4eca597..5cb2c5c 100644 --- a/worker/src/lib/migrations.ts +++ b/worker/src/lib/migrations.ts @@ -136,11 +136,24 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_history ( CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_user_id ON {prefix}notification_history(user_id, created_at)`; +/** + * schema_v2 — notification history provenance. `trigger_source` is nullable so + * rows written before this migration keep their meaning (unknown source), and + * the composite index serves the history page's channel/success/source filters. + */ +const SCHEMA_V2 = `ALTER TABLE {prefix}notification_history ADD COLUMN trigger_source TEXT; +CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_filter + ON {prefix}notification_history(user_id, channel, success, created_at)`; + export function getMigrations(prefix: string): Migration[] { return [ { name: "schema_v1", sql: SCHEMA_V1.replace(/\{prefix\}/g, prefix), }, + { + name: "schema_v2", + sql: SCHEMA_V2.replace(/\{prefix\}/g, prefix), + }, ]; } diff --git a/worker/src/routes/me.ts b/worker/src/routes/me.ts index acf3342..9c216f3 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -446,6 +446,7 @@ meRoutes.post("/notifications/test", async (c) => { title: message.title, success: result.success, error: result.error, + trigger_source: "test", }); } catch (err) { console.error("Failed to insert notification history:", err); @@ -457,13 +458,23 @@ meRoutes.post("/notifications/test", async (c) => { meRoutes.get("/notification-history", async (c) => { const userId = getEffectiveUserId(c); const prefix = getTablePrefix(c.env); - const limit = Math.min(Number(c.req.query("limit") || 50), 200); - const history = await listNotificationHistory( - c.env.DB, - prefix, - userId, - limit, - ); + const limitParam = c.req.query("limit"); + const limit = + limitParam === undefined || limitParam.trim() === "" + ? undefined + : Number(limitParam); + const successParam = c.req.query("success"); + const history = await listNotificationHistory(c.env.DB, prefix, userId, { + limit: Number.isFinite(limit) ? limit : undefined, + channel: c.req.query("channel") || undefined, + success: + successParam === "true" + ? true + : successParam === "false" + ? false + : undefined, + triggerSource: c.req.query("trigger_source") || undefined, + }); return c.json(history); }); diff --git a/worker/src/routes/notify.ts b/worker/src/routes/notify.ts index a75b1a1..e11a81a 100644 --- a/worker/src/routes/notify.ts +++ b/worker/src/routes/notify.ts @@ -73,7 +73,13 @@ notifyRoutes.post("/", async (c) => { notifyConfig, message, c.env, - undefined, + { + db: c.env.DB, + prefix, + userId, + itemId: null, + triggerSource: "api", + }, channels, ); return c.json({ success: true, results }); diff --git a/worker/src/services/notify/index.ts b/worker/src/services/notify/index.ts index 2b53031..ae0dc33 100644 --- a/worker/src/services/notify/index.ts +++ b/worker/src/services/notify/index.ts @@ -28,6 +28,8 @@ export interface NotifyContext { prefix: string; userId: string; itemId?: string | null; + /** Why this notification was sent: "item", "api" or "test". */ + triggerSource?: string; } const CHANNEL_SENDERS: Record< @@ -80,6 +82,7 @@ async function recordHistory( body, success, error, + trigger_source: context.triggerSource ?? null, }); } catch (err) { console.error("Failed to insert notification history:", err); diff --git a/worker/src/services/scheduler.ts b/worker/src/services/scheduler.ts index e7cf32f..84e9d74 100644 --- a/worker/src/services/scheduler.ts +++ b/worker/src/services/scheduler.ts @@ -340,6 +340,7 @@ async function processSubscription( prefix, userId, itemId: sub.id, + triggerSource: "item", }, channels, ); diff --git a/worker/test/admin.test.ts b/worker/test/admin.test.ts index 05bd9c9..91c5ed6 100644 --- a/worker/test/admin.test.ts +++ b/worker/test/admin.test.ts @@ -27,7 +27,10 @@ describe("POST /api/admin/setup", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const db = env.DB as MockD1; @@ -112,7 +115,10 @@ describe("POST /api/admin/setup", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); }); }); diff --git a/worker/test/ledger.test.ts b/worker/test/ledger.test.ts index 95b741b..b2bbe98 100644 --- a/worker/test/ledger.test.ts +++ b/worker/test/ledger.test.ts @@ -107,6 +107,13 @@ function seedCurrentShape(d1: SqliteD1, prefix = ""): void { execSQL(d1, CURRENT_SCHEMA.replace(/\{prefix\}/g, prefix)); } +/** Apply only `schema_v1`, for parity checks against the pre-ledger fixture. */ +function seedSchemaV1(d1: SqliteD1, prefix = ""): void { + const migration = getMigrations(prefix).find((m) => m.name === "schema_v1"); + if (!migration) throw new Error("schema_v1 migration missing"); + execSQL(d1, migration.sql); +} + /** * The oldest shape the legacy patch set still has to fix: no * notification_history.body, no slack/feishu/discord/default_channel columns, @@ -273,14 +280,18 @@ describe("migrationsTable name formula", () => { }); describe("migration list", () => { - it("collapses the pre-ledger history into a single schema_v1 entry", () => { + it("keeps schema_v1 as the base and appends schema_v2", () => { const migrations = getMigrations("enotify_"); - expect(migrations.map((m) => m.name)).toEqual(["schema_v1"]); + expect(migrations.map((m) => m.name)).toEqual(["schema_v1", "schema_v2"]); // `{prefix}` is resolved for the caller, the DDL itself carries no placeholder. expect(migrations[0].sql).toContain( "CREATE TABLE IF NOT EXISTS enotify_users", ); expect(migrations[0].sql).not.toContain("{prefix}"); + expect(migrations[1].sql).toContain( + "ALTER TABLE enotify_notification_history ADD COLUMN trigger_source TEXT", + ); + expect(migrations[1].sql).not.toContain("{prefix}"); }); it("migration SQL contains no ';' inside string literals", () => { @@ -306,7 +317,10 @@ describe("fresh install through the ledger", () => { expect(result).toEqual({ success: true, effectivePrefix: "enotify_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const tables = tableNames(d1); @@ -324,7 +338,14 @@ describe("fresh install through the ledger", () => { expect(tables).toContain("_enotify_schema_migrations"); expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); + expect( + columnsOf(d1, "enotify_notification_history").map((c) => c.name), + ).toContain("trigger_source"); + expect( + indexesOf(d1, "enotify_notification_history").map((i) => i.name), + ).toContain("idx_enotify_notification_history_filter"); const settings = rowsOf(d1, "enotify_system_settings", "key").map( (r) => r.key, @@ -351,7 +372,10 @@ describe("fresh install through the ledger", () => { success: true, alreadyInitialized: true, effectivePrefix: "enotify_", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], }); expect(snapshot(d1)).toEqual(before); }); @@ -376,7 +400,7 @@ describe("schema_v1 structure parity with the pre-ledger install", () => { it("matches the pre-ledger snapshot table by table (PRAGMA table_info + indexes)", async () => { const d1 = new SqliteD1(); - await runSetup(makeEnv(d1, "")); + seedSchemaV1(d1); // Only the ledger table is new; every pre-existing table is described below. const businessTables = tableNames(d1).filter( @@ -399,7 +423,7 @@ describe("schema_v1 structure parity with the pre-ledger install", () => { it("keeps the structure of a pre-ledger database after the in-place transition", async () => { const d1 = new SqliteD1(); - await runSetup(makeEnv(d1, "")); + seedSchemaV1(d1); // Same 7 tables, same columns/indexes as the legacy patch set produced. for (const expected of fixture.tables) { @@ -497,7 +521,7 @@ describe("legacy database transition", () => { ); }); - it("stamps an already up-to-date database and is a no-op on the next run", async () => { + it("stamps an already up-to-date database, applies pending migrations, then no-ops", async () => { const d1 = new SqliteD1(); seedCurrentShape(d1); execSQL( @@ -523,15 +547,29 @@ describe("legacy database transition", () => { expect(rowsOf(d1, "users")).toEqual(before.users); expect(rowsOf(d1, "notification_configs")).toEqual(before.configs); - const afterFirst = snapshot(d1); const second = await runSetup(makeEnv(d1, "")); expect(second).toEqual({ success: true, alreadyInitialized: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "applied" }, + ], + }); + + const afterSecond = snapshot(d1); + const third = await runSetup(makeEnv(d1, "")); + expect(third).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "", + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], }); - expect(snapshot(d1)).toEqual(afterFirst); + expect(snapshot(d1)).toEqual(afterSecond); }); it("clears retired channel IDs during the transition (same behaviour as before)", async () => { @@ -658,10 +696,14 @@ describe("ledger consistency check", () => { success: true, alreadyInitialized: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); expect(ledgerRows(d1, "_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); expect(exists(d1, "users")).toBe(true); }); @@ -678,6 +720,7 @@ describe("prefix variants", () => { expect(exists(d1, "_enotify_schema_migrations")).toBe(true); expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); expect(exists(d1, "enotify_users")).toBe(true); }); @@ -689,6 +732,7 @@ describe("prefix variants", () => { expect(exists(d1, "_schema_migrations")).toBe(true); expect(ledgerRows(d1, "_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); expect(exists(d1, "users")).toBe(true); }); @@ -700,6 +744,7 @@ describe("prefix variants", () => { expect(exists(d1, "_X_schema_migrations")).toBe(true); expect(ledgerRows(d1, "_X_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); expect(exists(d1, "X_users")).toBe(true); }); @@ -766,12 +811,16 @@ describe("prefix conflict guard with the ledger", () => { expect(result).toEqual({ success: true, effectivePrefix: "enotify_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); // The foreign ledger is neither read nor written. expect(ledgerRows(d1, "_ZETA_schema_migrations")).toEqual([]); expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, + { name: "schema_v2" }, ]); }); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index ac574da..d6c4ee2 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -231,9 +231,18 @@ describe("notification_configs slack_config migration", () => { success: true, alreadyInitialized: true, effectivePrefix: "en_", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "applied" }, + ], }); + const third = await runSetup(makeEnv(d1)); + expect(third.migrations).toEqual([ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ]); + const rows = d1.db .prepare(`SELECT * FROM ${PREFIX}notification_configs`) .all() as Record[]; @@ -404,9 +413,18 @@ describe("retired channel cleanup migration", () => { success: true, alreadyInitialized: true, effectivePrefix: "en_", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "applied" }, + ], }); + const third = await runSetup(makeEnv(d1)); + expect(third.migrations).toEqual([ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ]); + expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); expect(enabledChannelsOf(d1, "u3")).toBe("not-json"); @@ -417,6 +435,9 @@ describe("retired channel cleanup migration", () => { it("no longer reports unknown channels after the migration", async () => { const d1 = new SqliteD1(); seedLegacyChannels(d1); + // First setup stamps schema_v1 on a pre-ledger database; the second one + // applies the migrations appended after it (schema_v2). + await runSetup(makeEnv(d1)); await runSetup(makeEnv(d1)); const fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); @@ -458,7 +479,10 @@ describe("fresh install schema", () => { expect(result).toEqual({ success: true, effectivePrefix: "en_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const columns = d1.db diff --git a/worker/test/notification-history.test.ts b/worker/test/notification-history.test.ts new file mode 100644 index 0000000..8fe9929 --- /dev/null +++ b/worker/test/notification-history.test.ts @@ -0,0 +1,398 @@ +import { Hono } from "hono"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + insertNotificationHistory, + listNotificationHistory, +} from "../src/db/queries/notification-history"; +import { runSetup } from "../src/lib/setup"; +import { meRoutes } from "../src/routes/me"; +import { notifyRoutes } from "../src/routes/notify"; +import { sendNotifications } from "../src/services/notify/index"; +import type { Env, NotificationConfig } from "../src/types"; +import { + cookieHeader, + makeToken, + MockKV, + request, + seedSession, + TEST_JWT_SECRET, + TEST_SETUP_SECRET, +} from "./helpers"; +import { SqliteD1 } from "./support/sqlite-d1"; + +const PREFIX = "en_"; +const FILTER_INDEX = `idx_${PREFIX}notification_history_filter`; + +function makeEnv(d1: SqliteD1): Env { + return { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "en", + ASSETS: {}, + } as unknown as Env; +} + +async function seededEnv(): Promise<{ d1: SqliteD1; env: Env }> { + const d1 = new SqliteD1(); + const env = makeEnv(d1); + const result = await runSetup(env); + expect(result.success).toBe(true); + return { d1, env }; +} + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api/me", meRoutes); + app.route("/api/notify", notifyRoutes); + return app; +} + +async function login(env: Env): Promise<{ headers: Record }> { + await seedSession(env as unknown as Record, "u1", "s1"); + const token = await makeToken("user", { sub: "u1", sid: "s1" }); + return { headers: cookieHeader(token) }; +} + +function seedRow( + d1: SqliteD1, + row: { + id: string; + user?: string; + channel?: string; + success?: boolean; + source?: string | null; + createdAt?: string; + }, +): void { + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_history + (id, user_id, item_id, channel, title, body, success, error, trigger_source, created_at) + VALUES (?, ?, NULL, ?, ?, NULL, ?, NULL, ?, ?)`, + ) + .run( + row.id, + row.user ?? "u1", + row.channel ?? "telegram", + `title-${row.id}`, + row.success === false ? 0 : 1, + row.source === undefined ? null : row.source, + row.createdAt ?? "2026-01-01T00:00:00.000Z", + ); +} + +function seedHistory(d1: SqliteD1): void { + seedRow(d1, { + id: "h1", + source: "item", + createdAt: "2026-01-01T00:00:00.000Z", + }); + seedRow(d1, { + id: "h2", + source: "item", + success: false, + createdAt: "2026-01-02T00:00:00.000Z", + }); + seedRow(d1, { + id: "h3", + channel: "bark", + source: "api", + success: false, + createdAt: "2026-01-03T00:00:00.000Z", + }); + seedRow(d1, { + id: "h4", + source: "test", + createdAt: "2026-01-04T00:00:00.000Z", + }); + seedRow(d1, { + id: "h5", + user: "u2", + source: "item", + createdAt: "2026-01-05T00:00:00.000Z", + }); + seedRow(d1, { + id: "h6", + source: null, + createdAt: "2026-01-06T00:00:00.000Z", + }); +} + +function ids(rows: { id: string }[]): string[] { + return rows.map((row) => row.id); +} + +function notifyConfig(): NotificationConfig { + return { + user_id: "u1", + enabled_channels: JSON.stringify(["telegram"]), + default_channel: "telegram", + telegram_config: JSON.stringify({ bot_token: "token", chat_id: "1" }), + webhook_config: "{}", + wechatbot_config: "{}", + email_config: "{}", + bark_config: "{}", + slack_config: "{}", + feishu_config: "{}", + discord_config: "{}", + notification_hours: "[]", + updated_at: "", + }; +} + +function seedNotificationConfig(d1: SqliteD1): void { + d1.db + .prepare( + `INSERT OR IGNORE INTO ${PREFIX}users + (id, email, password_hash, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "u1", + "u1@example.com", + "hash", + "2026-01-01T00:00:00.000Z", + "2026-01-01T00:00:00.000Z", + ); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs + (user_id, enabled_channels, default_channel, telegram_config, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "u1", + JSON.stringify(["telegram"]), + "telegram", + JSON.stringify({ bot_token: "token", chat_id: "1" }), + "2026-01-01T00:00:00.000Z", + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("schema_v2", () => { + it("adds trigger_source and the filter index", async () => { + const { d1 } = await seededEnv(); + + const columns = d1.db + .prepare(`PRAGMA table_info(${PREFIX}notification_history)`) + .all() as { name: string }[]; + expect(columns.map((column) => column.name)).toContain("trigger_source"); + + const index = d1.db + .prepare(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?`) + .get(FILTER_INDEX) as { name: string } | undefined; + expect(index).toEqual({ name: FILTER_INDEX }); + }); +}); + +describe("insertNotificationHistory", () => { + it("writes trigger_source and leaves it NULL when omitted", async () => { + const { d1 } = await seededEnv(); + + await insertNotificationHistory(d1 as unknown as D1Database, PREFIX, { + id: "h-api", + user_id: "u1", + channel: "telegram", + title: "api", + success: true, + trigger_source: "api", + }); + await insertNotificationHistory(d1 as unknown as D1Database, PREFIX, { + id: "h-legacy", + user_id: "u1", + channel: "telegram", + title: "legacy", + success: false, + error: "boom", + }); + + const rows = d1.db + .prepare( + `SELECT id, trigger_source FROM ${PREFIX}notification_history ORDER BY id`, + ) + .all() as { id: string; trigger_source: string | null }[]; + expect(rows).toEqual([ + { id: "h-api", trigger_source: "api" }, + { id: "h-legacy", trigger_source: null }, + ]); + }); +}); + +describe("listNotificationHistory filters", () => { + it("filters by channel, success and trigger source with exact matches", async () => { + const { d1 } = await seededEnv(); + seedHistory(d1); + const db = d1 as unknown as D1Database; + + expect(ids(await listNotificationHistory(db, PREFIX, "u1"))).toEqual([ + "h6", + "h4", + "h3", + "h2", + "h1", + ]); + expect( + ids(await listNotificationHistory(db, PREFIX, "u1", { channel: "bark" })), + ).toEqual(["h3"]); + expect( + ids(await listNotificationHistory(db, PREFIX, "u1", { success: false })), + ).toEqual(["h3", "h2"]); + expect( + ids( + await listNotificationHistory(db, PREFIX, "u1", { + triggerSource: "item", + }), + ), + ).toEqual(["h2", "h1"]); + expect( + ids( + await listNotificationHistory(db, PREFIX, "u1", { + channel: "telegram", + success: false, + triggerSource: "item", + }), + ), + ).toEqual(["h2"]); + expect( + ids(await listNotificationHistory(db, PREFIX, "u1", { limit: 2 })), + ).toEqual(["h6", "h4"]); + }); + + it("never returns another user's rows", async () => { + const { d1 } = await seededEnv(); + seedHistory(d1); + + const rows = await listNotificationHistory( + d1 as unknown as D1Database, + PREFIX, + "u2", + ); + expect(ids(rows)).toEqual(["h5"]); + }); +}); + +describe("GET /api/me/notification-history", () => { + it("translates query parameters into filters", async () => { + const { d1, env } = await seededEnv(); + seedHistory(d1); + const auth = await login(env); + + const filtered = await request( + makeApp(), + env, + "/api/me/notification-history?channel=telegram&success=false&trigger_source=item", + { headers: auth.headers }, + ); + expect(filtered.status).toBe(200); + expect(ids(filtered.body)).toEqual(["h2"]); + + const limited = await request( + makeApp(), + env, + "/api/me/notification-history?limit=2", + { headers: auth.headers }, + ); + expect(ids(limited.body)).toEqual(["h6", "h4"]); + }); + + it("ignores an invalid success value and a non-numeric limit", async () => { + const { d1, env } = await seededEnv(); + seedHistory(d1); + const auth = await login(env); + + const res = await request( + makeApp(), + env, + "/api/me/notification-history?success=maybe&limit=abc", + { headers: auth.headers }, + ); + expect(res.status).toBe(200); + expect(ids(res.body)).toEqual(["h6", "h4", "h3", "h2", "h1"]); + }); +}); + +describe("notification writers record their trigger source", () => { + it("sendNotifications persists context.triggerSource", async () => { + const { d1, env } = await seededEnv(); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response("ok", { status: 200 })), + ); + + const results = await sendNotifications( + notifyConfig(), + { title: "Test", body: "Body" }, + env, + { + db: d1 as unknown as D1Database, + prefix: PREFIX, + userId: "u1", + itemId: null, + triggerSource: "item", + }, + ["telegram"], + ); + expect(results).toEqual([{ channel: "telegram", success: true }]); + + const row = d1.db + .prepare( + `SELECT trigger_source, item_id FROM ${PREFIX}notification_history`, + ) + .get() as { trigger_source: string; item_id: string | null }; + expect(row).toEqual({ trigger_source: "item", item_id: null }); + }); + + it("POST /api/me/notifications/test writes trigger_source 'test'", async () => { + const { d1, env } = await seededEnv(); + seedNotificationConfig(d1); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response("ok", { status: 200 })), + ); + const auth = await login(env); + + const res = await request(makeApp(), env, "/api/me/notifications/test", { + method: "POST", + headers: { ...auth.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ channel: "telegram" }), + }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true }); + + const row = d1.db + .prepare(`SELECT trigger_source FROM ${PREFIX}notification_history`) + .get() as { trigger_source: string }; + expect(row.trigger_source).toBe("test"); + }); + + it("POST /api/notify writes trigger_source 'api' with no item", async () => { + const { d1, env } = await seededEnv(); + seedNotificationConfig(d1); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response("ok", { status: 200 })), + ); + const auth = await login(env); + + const res = await request(makeApp(), env, "/api/notify", { + method: "POST", + headers: { ...auth.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ title: "Hello" }), + }); + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + + const row = d1.db + .prepare( + `SELECT trigger_source, item_id FROM ${PREFIX}notification_history`, + ) + .get() as { trigger_source: string; item_id: string | null }; + expect(row).toEqual({ trigger_source: "api", item_id: null }); + }); +}); diff --git a/worker/test/prefix.test.ts b/worker/test/prefix.test.ts index b57b8f8..97c3524 100644 --- a/worker/test/prefix.test.ts +++ b/worker/test/prefix.test.ts @@ -235,7 +235,10 @@ describe("runSetup anti-silent-switch guard", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const db = env.DB as MockD1; @@ -259,7 +262,10 @@ describe("runSetup anti-silent-switch guard", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "enotify_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const db = env.DB as MockD1; @@ -303,7 +309,10 @@ describe("admin setup route surfaces prefix conflicts", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "eNotify_", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); }); }); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 9acdf8c..448ec87 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -163,12 +163,18 @@ describe("POST /api/setup (regression)", () => { expect(res.body).toEqual({ success: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "applied" }], + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + ], }); const db = env.DB as MockD1; expect(db.tables.has("users")).toBe(true); - expect(db.ledger.get("_schema_migrations")).toEqual(["schema_v1"]); + expect(db.ledger.get("_schema_migrations")).toEqual([ + "schema_v1", + "schema_v2", + ]); }); it("reports alreadyInitialized on a second call", async () => { @@ -188,7 +194,10 @@ describe("POST /api/setup (regression)", () => { success: true, alreadyInitialized: true, effectivePrefix: "", - migrations: [{ name: "schema_v1", status: "skipped" }], + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + ], }); }); From c1faa1778c4a488d7f22c8a8c707d97ef1443156 Mon Sep 17 00:00:00 2001 From: Todos Date: Wed, 28 Oct 2026 13:16:48 +0800 Subject: [PATCH 2/2] fix(test): add trigger_source to default-channel history mock Keep the local SQLite mock aligned with schema_v2 so API notification history inserts stop failing silently. Checkpoint: NiUhYAs1Z9_CIR-v-mLMS --- worker/test/default-channel.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/worker/test/default-channel.test.ts b/worker/test/default-channel.test.ts index 9795e8b..7b74d2b 100644 --- a/worker/test/default-channel.test.ts +++ b/worker/test/default-channel.test.ts @@ -46,7 +46,8 @@ class SqliteD1 { 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 + body TEXT, success INTEGER, error TEXT, trigger_source TEXT, + created_at TEXT ); `); }