Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions web/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,6 @@ export interface NotificationHistory {
body: string | null;
success: number;
error: string | null;
trigger_source: string | null;
created_at: string;
}
44 changes: 38 additions & 6 deletions worker/src/db/queries/notification-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -22,12 +30,13 @@ export async function insertNotificationHistory(
body?: string | null;
success: boolean;
error?: string | null;
trigger_source?: string | null;
},
): Promise<void> {
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,
Expand All @@ -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<NotificationHistoryRecord[]> {
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<NotificationHistoryRecord & { item_name?: string }>();
return result.results;
}
Expand Down
13 changes: 13 additions & 0 deletions worker/src/lib/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
];
}
25 changes: 18 additions & 7 deletions worker/src/routes/me.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
});

Expand Down
8 changes: 7 additions & 1 deletion worker/src/routes/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
3 changes: 3 additions & 0 deletions worker/src/services/notify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions worker/src/services/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ async function processSubscription(
prefix,
userId,
itemId: sub.id,
triggerSource: "item",
},
channels,
);
Expand Down
10 changes: 8 additions & 2 deletions worker/test/admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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" },
],
});
});
});
3 changes: 2 additions & 1 deletion worker/test/default-channel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
`);
}
Expand Down
Loading
Loading