Merge pull request #18 from d0zingcat/feature/topic_global

This commit is contained in:
2026-01-24 22:26:05 +08:00
committed by GitHub
13 changed files with 473 additions and 107 deletions

83
AGENTS.md Normal file
View File

@@ -0,0 +1,83 @@
# Agent Guide for Alert Message Center
This document provides instructions for AI agents working on the Alert Message Center codebase.
## 🛠 Commands
### Workspace Operations
- **Install**: `bun install`
- **Root Dev**: `bun run dev` (starts both server and web)
- **Root Build**: `bun run build`
- **Lint & Format**:
- `bun run lint`: Run Biome linter
- `bun run format`: Fix formatting issues
- `bun run check`: Linter + Formatter fix
### Backend (`apps/server`)
- **Dev**: `bun run dev`
- **Migrations**:
- `bun run db:generate`: Generate migration files
- `bun run db:push`: Push schema changes directly (dev only)
- `bun run db:migrate:deploy`: Run migrations in production/Docker
- **Verification**: `bun run src/verify_permissions.ts` (Manual verification script)
### Frontend (`apps/web`)
- **Dev**: `bun run dev`
- **Build**: `bun run build`
### Testing
- No automated tests currently exist in the repository. If adding tests, use **Bun Test**.
- **Run Single Test**: `bun test path/to/file.test.ts`
---
## 📜 Code Style & Conventions
### 1. General
- **Runtime**: Bun is the primary runtime. Use `node:` protocol for built-in modules (e.g., `import fs from "node:fs"`).
- **Formatting**: Enforced by Biome. Use **tabs** for indentation and **double quotes**.
- **Naming**:
- Variables/Functions: `camelCase`
- Components/Classes/Interfaces: `PascalCase`
- Database Tables/Columns: `snake_case` (e.g., `topic_group_chats`)
- URL Slugs: `kebab-case`
### 2. TypeScript & Type Safety
- **Strict Mode**: No `any` allowed. Use explicit interfaces or Zod schemas.
- **Interfaces vs Types**: Prefer `interface` for object definitions and `type` for unions/aliases.
- **RPC**: Use `hono/client` for type-safe communication between frontend and backend.
- **Vite Env**: Always use optional chaining when accessing `import.meta.env?.VITE_...`.
### 3. Backend (Hono + Drizzle)
- **Routing**: Group logic into sub-apps (e.g., `api.ts`, `auth.ts`, `webhook.ts`).
- **Database**: Use Drizzle ORM. Prefer relational queries where possible (`db.query.xxx.findMany`).
- **Validation**: Use `@hono/zod-validator` for request validation.
- **Logging**: Use the structured logger in `src/lib/logger.ts` (Pino).
- **Pattern**: `logger.error({ err, context }, "Message")`.
### 4. Frontend (React + Tailwind)
- **Components**: Functional components with hooks.
- **Styling**: Tailwind CSS utility classes. Avoid custom CSS files.
- **Icons**: Use `lucide-react`.
- **Resilience**:
- Always check `res.ok` before parsing API responses.
- Provide fallback states (e.g., `[]`) for data fetching.
### 5. Error Handling
- **Backend**: Wrap critical logic in `try/catch`. Log errors with context. Return meaningful JSON errors with appropriate HTTP status codes.
- **Frontend**: Use `useState` to track error states and display user-friendly messages.
---
## 🏗 Architecture Context
- **Topic Model**: Alerts are sent to "Topics". Users and Group Chats subscribe to Topics.
- **Personal Inbox**: Each user has a `personalToken` (8-character hex) for direct `/dm` alerts.
- **Feishu Integration**: Uses `@larksuiteoapi/node-sdk`. Supports both Webhook and WebSocket modes for events.
- **Auth**: Feishu SSO (OAuth2). Admin status is assigned via `ADMIN_EMAILS` env var on first login.
## 🤖 Rules for Agents
- **NO `any`**: This is a hard requirement. Research types or define them.
- **Biome First**: Always run `bun run check` before concluding a task.
- **Preserve Patterns**: Follow existing structure in `apps/server/src` and `apps/web/src`.
- **Minimalism**: Fix bugs minimally. Avoid large refactors unless requested.
- **Context**: Agent-specific context is located in `@docs/`. Refer to `docs/copilot-context.md` for additional instructions.

View File

@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
**CHANGELOG** | [简体中文](./CHANGELOG.zh-CN.md)
## [1.4.0] - 2026-01-23
### Added
- **Global Topics**: Introduced a new topic type that broadcasts alerts to all users automatically.
- **User Requests**: All users can now request a topic to be "Global" during creation.
- **Admin Control**: Admins can promote any topic to "Global" or create new global topics via the Admin Dashboard.
- **Automatic Distribution**: Alerts sent to Global Topics are delivered to every registered user without requiring individual subscriptions.
- **UI Indicators**: Added "Global" badges and specialized management actions in the Topics and Admin views.
## [1.3.3] - 2026-01-17
### Added

View File

@@ -7,6 +7,15 @@
**更新日志** | [English](./CHANGELOG.md)
## [1.4.0] - 2026-01-23
### 新增
- **全局话题 (Global Topics)**: 引入了全新的话题类型,可自动向所有用户广播告警。
- **用户申请**: 现在所有用户在创建话题时都可以选择申请将其设为“全局话题”。
- **管理员控制**: 管理员可以通过管理员后台将任何话题提升为“全局话题”,或直接创建新的全局话题。
- **自动分发**: 发送到全局话题的告警将投递给每一位已注册的用户,无需用户手动订阅。
- **UI 标识**: 在话题列表和管理员视图中增加了“全局”标识和专门的管理操作。
## [1.3.3] - 2026-01-17
### 新增

View File

@@ -1,6 +1,6 @@
{
"name": "@alertmessagecenter/server",
"version": "1.3.3",
"version": "1.4.0",
"scripts": {
"dev": "bun run --env-file .env --watch src/index.ts",
"start": "bun run src/index.ts",

View File

@@ -18,8 +18,15 @@ const api = new Hono<{ Variables: { session: AuthSession } }>();
const topicSchema = z.object({
name: z.string().min(1),
slug: z.string().min(1),
slug: z
.string()
.min(1)
.regex(
/^[a-z0-9-]+$/i,
"Slug must only contain alphanumeric characters and hyphens",
),
description: z.string().optional(),
isGlobal: z.boolean().optional(),
});
const groupBindingSchema = z.object({
@@ -143,6 +150,7 @@ api.post("/topics", requireAuth, zValidator("json", topicSchema), async (c) => {
.insert(topics)
.values({
...body,
isGlobal: body.isGlobal ?? false,
status,
createdBy: session.id,
approvedBy: session.isAdmin || session.isTrusted ? session.id : null,
@@ -170,7 +178,10 @@ api.put(
const body = c.req.valid("json");
const result = await db
.update(topics)
.set(body)
.set({
...body,
isGlobal: body.isGlobal !== undefined ? body.isGlobal : undefined,
})
.where(eq(topics.id, id))
.returning();
return c.json(result[0]);

View File

@@ -20,6 +20,7 @@ export const topics = pgTable("topics", {
status: text("status", { enum: ["pending", "approved", "rejected"] })
.default("approved")
.notNull(),
isGlobal: boolean("is_global").default(false).notNull(),
createdBy: text("created_by").references(() => users.id),
approvedBy: text("approved_by").references(() => users.id),
createdAt: timestamp("created_at").defaultNow().notNull(),

View File

@@ -17,58 +17,16 @@ interface Recipient {
const webhook = new Hono();
webhook.post("/:token/topic/:slug", async (c) => {
const token = c.req.param("token");
const slug = c.req.param("slug");
logger.info({ token, slug }, "[Webhook] Received request");
// 0. Find the User by Token
const user = await db.query.users.findFirst({
where: eq(users.personalToken, token),
});
if (!user) {
logger.warn({ token }, "[Webhook] Invalid personal token");
return c.json({ error: "Invalid personal token" }, 401);
}
// biome-ignore lint/suspicious/noExplicitAny: Webhook body can be any arbitrary JSON
let body: Record<string, any>;
try {
const rawBody = await c.req.text();
logger.debug({ bodyLength: rawBody.length }, "[Webhook] Received raw body");
if (!rawBody || rawBody.trim() === "") {
return c.json({ error: "Empty body" }, 400);
}
body = JSON.parse(rawBody);
} catch (e) {
logger.error({ err: e }, "[Webhook] Failed to parse JSON body");
return c.json({ error: "Invalid JSON body" }, 400);
}
// 1. Find the Topic
const topic = await db.query.topics.findFirst({
where: eq(topics.slug, slug),
with: {
subscriptions: {
with: {
user: true,
},
},
groupChats: true,
},
});
if (!topic) {
logger.warn({ slug }, "[Webhook] Topic not found");
return c.json({ error: "Topic not found" }, 404);
}
logger.info({ topicName: topic.name }, "[Webhook] Found topic");
const dispatchAlert = async (
c: any,
topic: any,
body: any,
user: any | null,
) => {
// 2. Collect recipients
const userRecipients: Recipient[] = topic.subscriptions
.map((sub) => sub.user)
.map((u) => {
const userRecipients: Recipient[] = (topic.subscriptions || [])
.map((sub: any) => sub.user)
.map((u: any) => {
if (!u || !u.feishuUserId) return null;
return {
type: "user" as const,
@@ -80,11 +38,11 @@ webhook.post("/:token/topic/:slug", async (c) => {
: "user_id") as FeishuReceiveIdType,
};
})
.filter((u): u is NonNullable<typeof u> => u !== null);
.filter((u: any): u is Recipient => u !== null);
const groupRecipients: Recipient[] = topic.groupChats
.filter((g) => g.status === "approved")
.map((g) => ({
const groupRecipients: Recipient[] = (topic.groupChats || [])
.filter((g: any) => g.status === "approved")
.map((g: any) => ({
type: "group",
id: g.id, // Binding ID
name: g.name,
@@ -98,7 +56,7 @@ webhook.post("/:token/topic/:slug", async (c) => {
.insert(alertTasks)
.values({
topicSlug: topic.slug,
senderId: user.id,
senderId: user?.id || null, // Global topic might not have a sender
status: "processing",
recipientCount: allRecipients.length,
successCount: 0,
@@ -272,7 +230,7 @@ webhook.post("/:token/topic/:slug", async (c) => {
taskId: task.id,
successCount,
totalCount: allRecipients.length,
slug,
slug: topic.slug,
},
"[Webhook] Task processed",
);
@@ -284,6 +242,115 @@ webhook.post("/:token/topic/:slug", async (c) => {
status: "processing",
recipientCount: allRecipients.length,
});
};
webhook.post("/topic/:slug", async (c) => {
const slug = c.req.param("slug");
logger.info({ slug }, "[Webhook] Received global request");
// 1. Find the Topic
const topic = await db.query.topics.findFirst({
where: eq(topics.slug, slug),
with: {
subscriptions: {
with: {
user: true,
},
},
groupChats: true,
},
});
if (!topic) {
logger.warn({ slug }, "[Webhook] Topic not found");
return c.json({ error: "Topic not found" }, 404);
}
if (!topic.isGlobal) {
logger.warn({ slug }, "[Webhook] Topic is not global");
return c.json(
{ error: "This topic requires a personal token to send alerts" },
401,
);
}
// biome-ignore lint/suspicious/noExplicitAny: Webhook body can be any arbitrary JSON
let body: Record<string, any>;
try {
const rawBody = await c.req.text();
if (!rawBody || rawBody.trim() === "") {
return c.json({ error: "Empty body" }, 400);
}
body = JSON.parse(rawBody);
} catch (_e) {
return c.json({ error: "Invalid JSON body" }, 400);
}
return dispatchAlert(c, topic, body, null);
});
webhook.post("/:token/topic/:slug", async (c) => {
const token = c.req.param("token");
const slug = c.req.param("slug");
logger.info({ token, slug }, "[Webhook] Received request");
// 1. Find the Topic
const topic = await db.query.topics.findFirst({
where: eq(topics.slug, slug),
with: {
subscriptions: {
with: {
user: true,
},
},
groupChats: true,
},
});
if (!topic) {
logger.warn({ slug }, "[Webhook] Topic not found");
return c.json({ error: "Topic not found" }, 404);
}
let user: any = null;
if (!topic.isGlobal) {
// 0. Find the User by Token
user = await db.query.users.findFirst({
where: eq(users.personalToken, token),
});
if (!user) {
logger.warn({ token }, "[Webhook] Invalid personal token");
return c.json({ error: "Invalid personal token" }, 401);
}
}
// biome-ignore lint/suspicious/noExplicitAny: Webhook body can be any arbitrary JSON
let body: Record<string, any>;
try {
const rawBody = await c.req.text();
if (!rawBody || rawBody.trim() === "") {
return c.json({ error: "Empty body" }, 400);
}
body = JSON.parse(rawBody);
} catch (_e) {
return c.json({ error: "Invalid JSON body" }, 400);
}
return dispatchAlert(c, topic, body, user);
});
webhook.all("/topic/:slug", (c) => {
return c.json(
{
error: "Method not allowed",
message: "Please use POST to send alerts to this webhook",
format: "POST /webhook/topic/:slug",
example:
'curl -X POST -H "Content-Type: application/json" -d \'{"content":{"text":"Hello"}}\' URL',
},
405,
);
});
webhook.post("/:token/dm", async (c) => {

View File

@@ -1,6 +1,6 @@
{
"name": "@alertmessagecenter/web",
"version": "1.3.3",
"version": "1.4.0",
"type": "module",
"scripts": {
"dev": "bun run --env-file .env vite",

View File

@@ -1,3 +1,4 @@
import { Globe, Lock, Trash2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { client } from "../lib/client";
import SystemLoadView from "./SystemLoadView";
@@ -13,6 +14,7 @@ interface Topic {
name: string;
slug: string;
description?: string;
isGlobal?: boolean;
status: "pending" | "approved" | "rejected";
subscriptions?: { id: string }[];
creator?: TopicUser;
@@ -251,6 +253,21 @@ function TopicsManagement() {
}
};
const handleToggleGlobal = async (topic: Topic) => {
try {
await client.api.topics[":id"].$put(
{
param: { id: topic.id },
json: { isGlobal: !topic.isGlobal },
},
{ init: { credentials: "include" } },
);
fetchAllTopics();
} catch (error) {
console.error(error);
}
};
if (loading) return <div>Loading topics...</div>;
return (
@@ -282,8 +299,21 @@ function TopicsManagement() {
{topics.map((topic) => (
<tr key={topic.id}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900">
{topic.name}
<div className="flex items-center">
<div className="text-sm font-medium text-gray-900">
{topic.name}
</div>
{topic.isGlobal ? (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-purple-100 text-purple-700 border border-purple-200 uppercase tracking-tight">
<Globe className="w-2.5 h-2.5 mr-1" />
Global
</span>
) : (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-600 border border-gray-200 uppercase tracking-tight">
<Lock className="w-2.5 h-2.5 mr-1" />
Private
</span>
)}
</div>
<div className="text-sm text-gray-500 font-mono">
{topic.slug}
@@ -312,13 +342,38 @@ function TopicsManagement() {
{topic.approver?.name || "-"}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<button
type="button"
onClick={() => handleDelete(topic.id, topic.name)}
className="text-red-600 hover:text-red-900"
>
Delete
</button>
<div className="flex justify-end space-x-2">
<button
type="button"
onClick={() => handleToggleGlobal(topic)}
className={`inline-flex items-center px-3 py-1 rounded-md text-xs font-medium transition-colors border ${
topic.isGlobal
? "bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100"
: "bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100"
}`}
title={topic.isGlobal ? "Disable Global" : "Enable Global"}
>
{topic.isGlobal ? (
<>
<Lock className="w-3 h-3 mr-1" />
Make Private
</>
) : (
<>
<Globe className="w-3 h-3 mr-1" />
Make Global
</>
)}
</button>
<button
type="button"
onClick={() => handleDelete(topic.id, topic.name)}
className="inline-flex items-center px-3 py-1 rounded-md text-xs font-medium bg-red-50 text-red-700 border border-red-200 hover:bg-red-100 transition-colors"
>
<Trash2 className="w-3 h-3 mr-1" />
Delete
</button>
</div>
</td>
</tr>
))}
@@ -407,7 +462,20 @@ function TopicRequestsList() {
{requests.map((req) => (
<li key={req.id} className="py-4 flex justify-between items-center">
<div>
<p className="font-medium text-gray-900">{req.name}</p>
<div className="flex items-center">
<p className="font-medium text-gray-900">{req.name}</p>
{req.isGlobal ? (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-purple-100 text-purple-700 border border-purple-200 uppercase tracking-tight">
<Globe className="w-2.5 h-2.5 mr-1" />
Global
</span>
) : (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-600 border border-gray-200 uppercase tracking-tight">
<Lock className="w-2.5 h-2.5 mr-1" />
Private
</span>
)}
</div>
<p className="text-sm text-gray-500">
Slug: <span className="font-mono">{req.slug}</span>
</p>

View File

@@ -1,6 +1,8 @@
import {
Check,
Copy,
Globe,
Lock,
Plus,
Settings,
ShieldCheck,
@@ -35,6 +37,7 @@ interface Topic {
creator?: TopicUser;
approver?: TopicUser;
createdBy?: string;
isGlobal?: boolean;
status?: string;
createdAt?: string;
}
@@ -55,6 +58,7 @@ export default function TopicsView() {
name: "",
slug: "",
description: "",
isGlobal: false,
});
const [submitStatus, setSubmitStatus] = useState<{
type: "success" | "error";
@@ -137,6 +141,7 @@ export default function TopicsView() {
name: string;
slug: string;
description?: string;
isGlobal?: boolean;
},
},
{
@@ -151,7 +156,7 @@ export default function TopicsView() {
? "Topic created successfully!"
: "Request submitted! Waiting for approval.",
});
setFormData({ name: "", slug: "", description: "" });
setFormData({ name: "", slug: "", description: "", isGlobal: false });
fetchTopics();
fetchMyRequests();
setTimeout(() => {
@@ -294,6 +299,15 @@ export default function TopicsView() {
return `${baseUrl}/webhook/${currentUser.personalToken}/topic/${topicSlug}`;
};
const getGlobalWebhookUrl = (topicSlug: string) => {
// biome-ignore lint/suspicious/noExplicitAny: Vite env access
const meta = import.meta as any;
const baseUrl = (
meta.env?.VITE_WEBHOOK_BASE_URL || window.location.origin
).replace(/\/$/, "");
return `${baseUrl}/webhook/topic/${topicSlug}`;
};
const getDmWebhookUrl = () => {
if (!currentUser?.personalToken) return "";
// biome-ignore lint/suspicious/noExplicitAny: Vite env access
@@ -422,8 +436,19 @@ export default function TopicsView() {
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center justify-between">
<p className="text-sm font-medium text-indigo-600 truncate">
<p className="text-sm font-medium text-indigo-600 truncate flex items-center">
{topic.name}
{topic.isGlobal ? (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-purple-100 text-purple-700 border border-purple-200 uppercase tracking-tight">
<Globe className="w-2.5 h-2.5 mr-1" />
Global
</span>
) : (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-600 border border-gray-200 uppercase tracking-tight">
<Lock className="w-2.5 h-2.5 mr-1" />
Private
</span>
)}
</p>
<div className="flex items-center space-x-2">
<button
@@ -509,37 +534,94 @@ export default function TopicsView() {
)}
</div>
{currentUser && (
<div className="mt-3 bg-gray-50 p-2 rounded border border-gray-200">
<div className="flex justify-between items-center">
<span className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
Your Personal Webhook
</span>
<button
type="button"
onClick={() =>
copyToClipboard(
getWebhookUrl(topic.slug),
topic.id,
)
}
className="text-indigo-600 hover:text-indigo-800 flex items-center text-xs font-medium"
>
{copiedId === topic.id ? (
<>
<Check className="w-3 h-3 mr-1" />
Copied!
</>
) : (
<>
<Copy className="w-3 h-3 mr-1" />
Copy URL
</>
)}
</button>
</div>
<div className="mt-1 text-xs font-mono text-gray-600 break-all select-all">
{getWebhookUrl(topic.slug)}
<div
className={`mt-3 ${topic.isGlobal ? "grid grid-cols-1 md:grid-cols-2 gap-4" : "space-y-3"}`}
>
<div className="bg-gray-50 p-3 rounded-lg border border-gray-200 shadow-sm flex flex-col justify-between">
<div>
<div className="flex justify-between items-center mb-1.5">
<span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
Your Personal Webhook
</span>
<button
type="button"
onClick={() =>
copyToClipboard(
getWebhookUrl(topic.slug),
topic.id,
)
}
className="text-indigo-600 hover:text-indigo-800 flex items-center text-xs font-semibold bg-white px-2 py-0.5 rounded border border-gray-200 shadow-sm transition-all hover:shadow hover:translate-y-[-1px]"
>
{copiedId === topic.id ? (
<>
<Check className="w-3 h-3 mr-1" />
Copied
</>
) : (
<>
<Copy className="w-3 h-3 mr-1" />
Copy URL
</>
)}
</button>
</div>
<div className="text-[11px] font-mono text-gray-600 break-all select-all bg-white/60 p-1.5 rounded border border-gray-100/50 leading-relaxed">
{getWebhookUrl(topic.slug)}
</div>
</div>
{topic.isGlobal && (
<p className="mt-1.5 text-[10px] text-gray-400 italic">
* Requires your personal token to identify you
as the sender.
</p>
)}
</div>
{topic.isGlobal && (
<div className="bg-purple-50/50 p-3 rounded-lg border border-purple-100 shadow-sm relative overflow-hidden group flex flex-col justify-between">
<div className="absolute top-0 right-0 p-1 opacity-10 group-hover:opacity-20 transition-opacity">
<Globe className="w-12 h-12 text-purple-600" />
</div>
<div className="flex justify-between items-center mb-1.5">
<div className="flex items-center">
<Globe className="w-3.5 h-3.5 mr-1.5 text-purple-500" />
<span className="text-[10px] font-bold text-purple-600 uppercase tracking-widest">
Global Webhook (Public)
</span>
</div>
<button
type="button"
onClick={() =>
copyToClipboard(
getGlobalWebhookUrl(topic.slug),
`${topic.id}-global`,
)
}
className="text-purple-600 hover:text-purple-800 flex items-center text-xs font-semibold bg-white px-2 py-0.5 rounded border border-purple-200 shadow-sm transition-all hover:shadow hover:translate-y-[-1px]"
>
{copiedId === `${topic.id}-global` ? (
<>
<Check className="w-3 h-3 mr-1" />
Copied
</>
) : (
<>
<Copy className="w-3 h-3 mr-1" />
Copy URL
</>
)}
</button>
</div>
<div className="text-[11px] font-mono text-purple-800 break-all select-all bg-white/60 p-1.5 rounded border border-purple-100/50 leading-relaxed">
{getGlobalWebhookUrl(topic.slug)}
</div>
<p className="mt-1.5 text-[10px] text-purple-500 italic">
* Global topics can receive alerts without a
personal token.
</p>
</div>
)}
</div>
)}
</div>
@@ -665,6 +747,8 @@ export default function TopicsView() {
id="topic-slug"
type="text"
required
pattern="[a-zA-Z0-9-]+"
title="Slug must only contain alphanumeric characters and hyphens"
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm border p-2 text-gray-900"
value={formData.slug}
onChange={(e) =>
@@ -672,6 +756,26 @@ export default function TopicsView() {
}
/>
</div>
<div className="flex items-center">
<input
id="is-global"
type="checkbox"
className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
checked={formData.isGlobal || false}
onChange={(e) =>
setFormData({ ...formData, isGlobal: e.target.checked })
}
/>
<label
htmlFor="is-global"
className="ml-2 block text-sm text-gray-900 font-medium"
>
Global Topic
</label>
<p className="ml-2 text-xs text-gray-500">
(Broadcast to ALL users. Requires Admin approval)
</p>
</div>
<div>
<label
htmlFor="topic-description"

View File

@@ -1,7 +1,14 @@
# Project Context for GitHub Copilot (v1.3.3)
# Project Context for GitHub Copilot (v1.4.0)
This document provides technical context, architectural decisions, and code conventions for the **Alert Message Center** project. It is intended to help AI assistants understand the codebase.
## 0. AI/Agent Specific Instructions
> [!IMPORTANT]
> **AI Agents MUST read [AGENTS.md](../AGENTS.md) first.** It contains critical information about:
> - Build/lint/test commands.
> - Required code style (tabs, double quotes, naming conventions).
> - Hard rules (NO `any`, Biome checks).
## 1. Project Overview
**Alert Message Center** (formerly Alert Manager) is a centralized alert dispatching system.
@@ -41,6 +48,7 @@ The database schema is defined in `apps/server/src/db/schema.ts`.
- `name`: Display name (e.g., "Payment Service Errors").
- `slug`: URL-safe identifier (e.g., `payment-errors`). Used in webhook URLs.
- `description`: Optional text.
- `isGlobal`: Boolean flag. If true, alerts are sent to all users automatically.
- `status`: `pending`, `approved`, or `rejected`.
- `createdBy`: Foreign Key -> `users.id`.
- `approvedBy`: Foreign Key -> `users.id`.
@@ -115,7 +123,11 @@ The database schema is defined in `apps/server/src/db/schema.ts`.
- **Topic-based**: `POST /api/webhook/:token/topic/:slug`
- **Direct (Inbox)**: `POST /api/webhook/:token/dm`
2. **Lookup**:
- For Topic-based: Find `Topic` by `slug` and fetch all `subscriptions`.
- For Topic-based: Find `Topic` by `slug`.
- **Recipients**:
- If `isGlobal` is true: Fetch all active users from DB.
- If not global: Fetch all `subscriptions` for that topic.
- Always fetch all bound `topic_group_chats`.
- For Direct: Identify the user via `token`.
3. **Dispatch**:
- Call `FeishuClient.sendMessage` for each recipient.
@@ -171,7 +183,7 @@ The database schema is defined in `apps/server/src/db/schema.ts`.
- `GET /api/topics/my-requests`: List user's own topic requests.
- `GET /api/topics/requests`: List pending topic requests (Admin only).
- `GET /api/topics/all`: List all topics regardless of status (Admin only).
- `POST /api/topics`: Create a topic (Admin creates approved, User creates pending).
- `POST /api/topics`: Create a topic (Admin/Trusted creates approved, User creates pending; Supports `isGlobal`).
- `POST /api/topics/:id/approve`: Approve a topic request (Admin only).
- `POST /api/topics/:id/reject`: Reject a topic request (Admin only).
- `DELETE /api/topics/:id`: Delete a topic (Admin only).
@@ -250,5 +262,6 @@ The database schema is defined in `apps/server/src/db/schema.ts`.
- **[README.md](file:///Users/lilithgames/Workspace/play/alert-message-center/README.md)**: Main project documentation (English version).
- **[README.zh-CN.md](file:///Users/lilithgames/Workspace/play/alert-message-center/README.zh-CN.md)**: Simplified Chinese version of the documentation.
- **[AGENTS.md](file:///Users/lilithgames/Workspace/play/alert-message-center/AGENTS.md)**: Specialized instructions and conventions for AI agents.
- **[CHANGELOG.md](file:///Users/lilithgames/Workspace/play/alert-message-center/CHANGELOG.md)**: Record of version changes.
- **[todo.md](file:///Users/lilithgames/Workspace/play/alert-message-center/todo.md)**: Task tracking.

View File

@@ -1,6 +1,6 @@
{
"name": "alertmessagecenter",
"version": "1.1.1",
"version": "1.4.0",
"workspaces": [
"apps/*"
],

View File

@@ -16,6 +16,7 @@
## Phase 2: Enhancements
- [x] **Authentication**: Feishu SSO integration and role-based access control.
- [x] **Global Monitoring Dashboard**: Real-time System Load metrics (Grafana-style).
- [x] **Global Topics**: Support for broadcasting alerts to all users automatically.
- [ ] **Message Preview**: Preview Feishu card JSON in the UI.
- [x] **History/Logs**: Basic tracking for sent alerts (Alert Tasks/Logs).
- [x] **Admin Topic Management**: Approve, reject, and delete topics (with audit trail).