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
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ A smart notification management system that helps you track expiry dates and exp
- **Auto-renewal** — Expired subscriptions are automatically renewed with payment history recorded
- **Payment History** — Record every payment, multi-currency with real-time exchange rates
- **Dashboard** — Monthly/yearly expense stats, expiry alerts, category analysis
- **9 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX
- **10 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX, Slack
- **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
- **Scheduled Reminders** — Hourly auto-check with global notification hours and per-item override
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- **自动续费** — 过期订阅自动续期并记录支付历史
- **支付历史** — 记录每笔支付,支持多币种与实时汇率转换
- **仪表盘** — 月度/年度支出统计、到期预警、分类分析
- **9 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、Server酱、PushPlus、NotifyX
- **10 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、Server酱、PushPlus、NotifyX、Slack
- **渠道管理** — 独立页面统一管理通知渠道的启用与配置
- **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道
- **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖
Expand Down
1 change: 1 addition & 0 deletions web/src/lib/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export const CHANNELS = [
{ id: "serverchan", label: "ServerChan" },
{ id: "pushplus", label: "PushPlus" },
{ id: "notifyx", label: "NotifyX" },
{ id: "slack", label: "Slack" },
] as const;
1 change: 1 addition & 0 deletions web/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@
"serverchan": "ServerChan",
"pushplus": "PushPlus",
"notifyx": "NotifyX",
"slack": "Slack",
"botToken": "Bot Token",
"chatId": "Chat ID",
"url": "URL",
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@
"serverchan": "Server酱",
"pushplus": "PushPlus",
"notifyx": "NotifyX",
"slack": "Slack",
"botToken": "机器人令牌",
"chatId": "聊天ID",
"url": "URL",
Expand Down
12 changes: 12 additions & 0 deletions web/src/pages/channels/ChannelPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,18 @@ const CHANNELS: ChannelDef[] = [
label: "NotifyX",
fields: [{ key: "api_key", label: "API Key", type: "password" }],
},
{
id: "slack",
label: "Slack",
fields: [
{
key: "webhook_url",
label: "Webhook URL",
type: "password",
placeholder: "https://hooks.slack.com/services/...",
},
],
},
];

// ---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions worker/src/db/queries/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export async function upsertNotificationConfig(
"serverchan_config",
"pushplus_config",
"notifyx_config",
"slack_config",
"notification_hours",
];

Expand Down
1 change: 1 addition & 0 deletions worker/src/db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
serverchan_config TEXT NOT NULL DEFAULT '{}',
pushplus_config TEXT NOT NULL DEFAULT '{}',
notifyx_config TEXT NOT NULL DEFAULT '{}',
slack_config TEXT NOT NULL DEFAULT '{}',
notification_hours TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL
);
Expand Down
17 changes: 17 additions & 0 deletions worker/src/lib/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ async function runMigrations(db: D1Database, prefix: string): Promise<void> {
// ignore
}

// Migration: add slack_config column to notification_configs
try {
const notifCols = await db
.prepare(`PRAGMA table_info(${prefix}notification_configs)`)
.all<{ name: string }>();
if (!notifCols.results.some((c) => c.name === "slack_config")) {
await db
.prepare(
`ALTER TABLE ${prefix}notification_configs ADD COLUMN slack_config TEXT NOT NULL DEFAULT '{}'`,
)
.run();
}
} catch (err) {
console.error("Migration failed for notification_configs table:", err);
}

// Migration: items table columns (type/use_lunar -> calendar_mode, lunar_expiry_date).
// Uses ALTER TABLE instead of recreating the table: DROP TABLE would cascade-delete payment_history.
try {
Expand Down Expand Up @@ -201,6 +217,7 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
serverchan_config TEXT NOT NULL DEFAULT '{}',
pushplus_config TEXT NOT NULL DEFAULT '{}',
notifyx_config TEXT NOT NULL DEFAULT '{}',
slack_config TEXT NOT NULL DEFAULT '{}',
notification_hours TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL
);
Expand Down
2 changes: 2 additions & 0 deletions worker/src/routes/me.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ meRoutes.get("/notifications", async (c) => {
"password",
"device_key",
"headers",
"webhook_url",
].some((s) => k.includes(s))
) {
redacted[k] = v ? "••••••" : "";
Expand Down Expand Up @@ -357,6 +358,7 @@ meRoutes.put("/notifications", async (c) => {
"password",
"device_key",
"headers",
"webhook_url",
];
for (const [k, v] of Object.entries(newConfig)) {
if (secretFields.some((s) => k.includes(s)) && (!v || v === "••••••")) {
Expand Down
2 changes: 2 additions & 0 deletions worker/src/services/notify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { sendGotify } from "./gotify";
import { sendServerChan } from "./serverchan";
import { sendPushPlus } from "./pushplus";
import { sendNotifyX } from "./notifyx";
import { sendSlack } from "./slack";
import { sendNotifyEmail } from "./email-notify";
import type { Env } from "../../types";
import { insertNotificationHistory } from "../../db/queries/notification-history";
Expand Down Expand Up @@ -48,6 +49,7 @@ const CHANNEL_SENDERS: Record<
serverchan: sendServerChan,
pushplus: sendPushPlus,
notifyx: sendNotifyX,
slack: sendSlack,
};

const SEND_TIMEOUT_MS = 15000;
Expand Down
49 changes: 49 additions & 0 deletions worker/src/services/notify/slack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { Env } from "../../types";
import type { NotifyMessage } from "./index";
import { safeErrorText, validateOutboundUrl } from "./safe-fetch";

interface SlackConfig {
webhook_url: string;
}

export async function sendSlack(
configJson: string,
message: NotifyMessage,
_env: Env,
): Promise<{ success: boolean; error?: string }> {
const config: SlackConfig = JSON.parse(configJson);
if (!config.webhook_url) {
return { success: false, error: "Slack webhook URL required" };
}

const check = validateOutboundUrl(config.webhook_url);
if (check.error || !check.url) {
return { success: false, error: `Slack: ${check.error ?? "Invalid URL"}` };
}
if (check.url.hostname !== "hooks.slack.com") {
return {
success: false,
error: "Slack: webhook URL must be on hooks.slack.com",
};
}

const lines = [`_${message.title}_`, message.body];
if (message.url) lines.push(message.url);
const text = lines.join("\n");

const response = await fetch(config.webhook_url, {
method: "POST",
redirect: "manual",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text }),
});

if (!response.ok) {
const err = await safeErrorText(response);
return {
success: false,
error: `Slack error (${response.status}): ${err}`,
};
}
return { success: true };
}
2 changes: 2 additions & 0 deletions worker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export interface NotificationConfig {
serverchan_config: string;
pushplus_config: string;
notifyx_config: string;
slack_config: string;
notification_hours: string;
updated_at: string;
}
Expand Down Expand Up @@ -133,4 +134,5 @@ export const VALID_CHANNELS: string[] = [
"serverchan",
"pushplus",
"notifyx",
"slack",
];
174 changes: 174 additions & 0 deletions worker/test/migrations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { DatabaseSync } from "node:sqlite";
import { describe, expect, it } from "vitest";
import { runSetup } from "../src/lib/setup";
import type { Env } from "../src/types";

/**
* Minimal D1 stand-in backed by a real in-memory SQLite database. Unlike the
* MockD1 in helpers.ts this keeps real column defaults and row data, which is
* what the slack_config migration needs to be verified against.
*/
class SqliteD1 {
readonly db = new DatabaseSync(":memory:");

prepare(sql: string): any {
const db = this.db;
const statement = () => db.prepare(sql);

return {
bind: (...args: unknown[]) => ({
first: async <T>() =>
(statement().get(...(args as any[])) ?? null) as T | null,
all: async <T>() => ({
results: statement().all(...(args as any[])) as T[],
}),
run: async () => {
statement().run(...(args as any[]));
return { success: true };
},
}),
first: async <T>() => (statement().get() ?? null) as T | null,
all: async <T>() => ({ results: statement().all() as T[] }),
run: async () => {
statement().run();
return { success: true };
},
};
}
}

const PREFIX = "en_";

// Schema as deployed before the Slack channel existed: no slack_config column.
const OLD_SCHEMA = `
CREATE TABLE ${PREFIX}users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
is_active INTEGER NOT NULL DEFAULT 1,
email_verified INTEGER NOT NULL DEFAULT 0,
base_currency TEXT NOT NULL DEFAULT 'CNY',
timezone TEXT NOT NULL DEFAULT 'UTC',
language TEXT NOT NULL DEFAULT 'zh',
theme TEXT NOT NULL DEFAULT 'system',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);

CREATE TABLE ${PREFIX}notification_configs (
user_id TEXT PRIMARY KEY REFERENCES ${PREFIX}users(id) ON DELETE CASCADE,
enabled_channels 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 '{}',
gotify_config TEXT NOT NULL DEFAULT '{}',
serverchan_config TEXT NOT NULL DEFAULT '{}',
pushplus_config TEXT NOT NULL DEFAULT '{}',
notifyx_config TEXT NOT NULL DEFAULT '{}',
notification_hours TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL
);

CREATE TABLE ${PREFIX}notification_history (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
item_id TEXT,
channel TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT,
success INTEGER NOT NULL DEFAULT 1,
error TEXT,
created_at TEXT NOT NULL
);

CREATE TABLE ${PREFIX}items (
id TEXT PRIMARY KEY,
calendar_mode TEXT NOT NULL DEFAULT 'solar',
lunar_expiry_date TEXT
);

INSERT INTO ${PREFIX}users
(id, email, password_hash, created_at, updated_at)
VALUES
('u1', 'u1@example.com', 'hash', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'),
('u2', 'u2@example.com', 'hash', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z');

INSERT INTO ${PREFIX}notification_configs
(user_id, enabled_channels, telegram_config, gotify_config, notification_hours, updated_at)
VALUES
('u1', '["telegram"]', '{"bot_token":"secret"}', '{"server_url":"https://gotify.example.com","app_token":"tok"}', '[8,9]', '2026-01-01T00:00:00.000Z');
`;

function makeEnv(d1: SqliteD1): Env {
return { DB: d1, TABLE_PREFIX: "en" } as unknown as Env;
}

type ColumnInfo = {
name: string;
type: string;
notnull: number;
dflt_value: string | null;
};

describe("notification_configs slack_config migration", () => {
it("adds slack_config with a '{}' default and keeps existing data", async () => {
const d1 = new SqliteD1();
d1.db.exec(OLD_SCHEMA);

const result = await runSetup(makeEnv(d1));
expect(result).toEqual({ success: true, alreadyInitialized: true });

const columns = d1.db
.prepare(`PRAGMA table_info(${PREFIX}notification_configs)`)
.all() as ColumnInfo[];
const slackColumn = columns.find((c) => c.name === "slack_config");
expect(slackColumn).toBeDefined();
expect(slackColumn?.type).toBe("TEXT");
expect(slackColumn?.notnull).toBe(1);
expect(slackColumn?.dflt_value).toBe("'{}'");

// The pre-existing row survives and is backfilled with the default.
const row = d1.db
.prepare(`SELECT * FROM ${PREFIX}notification_configs WHERE user_id = ?`)
.get("u1") as Record<string, unknown>;
expect(row.enabled_channels).toBe('["telegram"]');
expect(row.telegram_config).toBe('{"bot_token":"secret"}');
expect(row.gotify_config).toBe(
'{"server_url":"https://gotify.example.com","app_token":"tok"}',
);
expect(row.notification_hours).toBe("[8,9]");
expect(row.updated_at).toBe("2026-01-01T00:00:00.000Z");
expect(row.slack_config).toBe("{}");

// New rows get the same default.
d1.db
.prepare(
`INSERT INTO ${PREFIX}notification_configs (user_id, updated_at) VALUES (?, ?)`,
)
.run("u2", "2026-02-01T00:00:00.000Z");
const newRow = d1.db
.prepare(
`SELECT slack_config FROM ${PREFIX}notification_configs WHERE user_id = ?`,
)
.get("u2") as Record<string, unknown>;
expect(newRow.slack_config).toBe("{}");
});

it("is idempotent when the column already exists", async () => {
const d1 = new SqliteD1();
d1.db.exec(OLD_SCHEMA);

await runSetup(makeEnv(d1));
const second = await runSetup(makeEnv(d1));
expect(second).toEqual({ success: true, alreadyInitialized: true });

const rows = d1.db
.prepare(`SELECT * FROM ${PREFIX}notification_configs`)
.all() as Record<string, unknown>[];
expect(rows).toHaveLength(1);
expect(rows[0].slack_config).toBe("{}");
});
});
Loading
Loading