feat(gmw): public features #2-#6 — live moderation feed, toxic topic trends, channel timeline, CSV export, activity heatmap

- Live Moderation Feed: gateway publishes discord:moderation:action (Redis) → backend WS emits moderation_action → public web shows realtime stream.
- Toxic Topic Trends: backend moderation.trends aggregates categories/severity/action_type (read-only) → SVG bar + donut.
- Channel Timeline: messages view gets Feed/Timeline toggle with date-grouped separators.
- CSV Export: client-side downloadCsv for moderation actions (no backend write scope).
- Activity Heatmap: backend messages.activity (per-hour volume by channel) → pure-SVG grid.

User reputation deliberately excluded — no such feature exists in the codebase.
All read-only / public-facing / fully automatic per project rules.
This commit is contained in:
asepharyana
2026-08-18 17:43:02 +07:00
parent 36363fa3db
commit 9b3134d767
26 changed files with 854 additions and 44 deletions
@@ -459,6 +459,31 @@ export class MessagesRepository {
return { data: trimmed, nextCursor };
}
/**
* Per-hour message volume for the last `days` days, grouped by channel.
* Powers the public Activity Heatmap (read-only, no write scope).
* Returns a flat list of { channel_id, hour (0-23), count } buckets.
*/
async getActivity(days = 30) {
const db = getDatabase();
const since = Date.now() - days * 24 * 60 * 60 * 1000;
const result = await db.execute(sql`
SELECT channel_id,
EXTRACT(HOUR FROM to_timestamp(created_at / 1000))::int AS hour,
COUNT(*)::int AS c
FROM messages
WHERE created_at >= ${since}
GROUP BY channel_id, hour
ORDER BY channel_id, hour
`);
const rows = (result.rows as Record<string, unknown>[]) || [];
return rows.map((r) => ({
channelId: String(r.channel_id ?? "unknown"),
hour: Number(r.hour ?? 0),
count: Number(r.c ?? 0),
}));
}
}
export const messagesRepository = new MessagesRepository();
@@ -101,6 +101,10 @@ export class MessagesService {
const results = hits.map((h) => mapSearchHit(h));
return { results, nextCursor: null };
}
async getActivity(days = 30) {
return messagesRepository.getActivity(days);
}
}
/** Shape returned to the frontend (text + metadata from the archive payload). */
@@ -164,6 +164,60 @@ export class ModerationRepository {
return { data, nextCursor };
}
/**
* Aggregate moderation trends over the last `days` days.
* - category counts (from the jsonb/text[] `categories` column, unnested)
* - severity distribution
* - action_type distribution
* Read-only; powers the public Toxic Topic Trends panel.
*/
async getTrends(days: number) {
const db = getDatabase();
const since = Date.now() - days * 24 * 60 * 60 * 1000;
const cats = await db.execute(sql`
SELECT jsonb_array_elements_text(a.categories::jsonb) AS cat, COUNT(*)::int AS c
FROM moderation_actions a
WHERE a.created_at >= ${since} AND a.categories IS NOT NULL AND a.categories != '[]' AND a.categories != ''
GROUP BY cat
ORDER BY c DESC
LIMIT 15
`);
const catRows = (cats.rows as Record<string, unknown>[]) || [];
const sev = await db.execute(sql`
SELECT severity, COUNT(*)::int AS c
FROM moderation_actions
WHERE created_at >= ${since} AND severity IS NOT NULL
GROUP BY severity
`);
const sevRows = (sev.rows as Record<string, unknown>[]) || [];
const act = await db.execute(sql`
SELECT action_type, COUNT(*)::int AS c
FROM moderation_actions
WHERE created_at >= ${since}
GROUP BY action_type
ORDER BY c DESC
`);
const actRows = (act.rows as Record<string, unknown>[]) || [];
return {
categories: catRows.map((r) => ({
name: String(r.cat),
count: Number(r.c ?? 0),
})),
severities: sevRows.map((r) => ({
level: String(r.severity),
count: Number(r.c ?? 0),
})),
actions: actRows.map((r) => ({
type: String(r.action_type),
count: Number(r.c ?? 0),
})),
};
}
}
export const moderationRepository = new ModerationRepository();
@@ -8,10 +8,13 @@ const logger = createChildLogger("moderation.service");
export class ModerationService {
async getStats() {
logger.debug("Fetching moderation stats");
return moderationRepository.getStats();
}
async getTrends(days = 30) {
return moderationRepository.getTrends(days);
}
async listActions(query: ListModerationQuery) {
logger.debug({ query }, "Listing moderation actions");
return moderationRepository.listActions(query);
+15
View File
@@ -143,6 +143,14 @@ const messagesRouter = {
semanticSearch: os
.input(semanticSearchSchema)
.handler(({ input }) => messagesService.semanticSearch(input)),
// Public, read-only activity heatmap data (per-hour volume by channel).
activity: os
.input(
z.object({
days: z.coerce.number().int().positive().max(365).default(30),
}),
)
.handler(({ input }) => messagesService.getActivity(input.days)),
};
// ── Moderation ───────────────────────────────────────────────────
@@ -165,6 +173,13 @@ const moderationRouter = {
cursor: input.cursor,
}),
),
trends: os
.input(
z.object({
days: z.coerce.number().int().positive().max(365).default(30),
}),
)
.handler(({ input }) => moderationService.getTrends(input.days)),
};
// ── Media ────────────────────────────────────────────────────────
@@ -30,6 +30,7 @@ export const DISCORD_CHANNEL_TOPIC_UPDATED = "discord:channel:topic_updated";
export const DISCORD_PRESENCE_UPDATED = "discord:presence:updated";
export const DISCORD_GUILD_MEMBER_ADDED = "discord:guild_member:added";
export const DISCORD_GUILD_MEMBER_REMOVED = "discord:guild_member:removed";
export const DISCORD_MODERATION_ACTION = "discord:moderation:action";
// ---------------------------------------------------------------------------
// Command channels (backend -> discord-gateway)
@@ -126,4 +127,5 @@ export const DISCORD_CHANNEL_TO_WS_EVENT: Record<string, string> = {
[DISCORD_PRESENCE_UPDATED]: "presence_updated",
[DISCORD_GUILD_MEMBER_ADDED]: "guild_member_added",
[DISCORD_GUILD_MEMBER_REMOVED]: "guild_member_removed",
[DISCORD_MODERATION_ACTION]: "moderation_action",
};