feat: 实时消息与管理端运营能力

新增群聊/私信与公共 WebSocket 总线,站长用户内容档案,并将通知与待审角标改为推送驱动;同步精简管理仪表盘并修复主题换肤 DOM 冲突。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-15 22:58:16 +08:00
parent 29db9ae9b5
commit 42c395a864
55 changed files with 7607 additions and 346 deletions

View File

@@ -9,6 +9,7 @@ import {
ChevronRight,
Clock,
ExternalLink,
FolderSearch,
History,
Loader2,
Monitor,
@@ -31,9 +32,10 @@ import {
type Board,
type LoginLog,
} from "@/lib/api";
import { ROLES } from "@/lib/roles";
import { isOwner, ROLES } from "@/lib/roles";
import { formatDate, formatRelative } from "@/lib/format";
import { toast } from "@/lib/toast";
import { realtime } from "@/lib/realtime";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
@@ -156,6 +158,24 @@ export default function UsersAdmin({
.catch(() => {});
}, []);
// 在线状态实时化:WS hello 全量快照校正当前页绿点,之后 presence:update 增量跳变;
// 后端在线判定(有活跃 WS 连接)比列表接口的 5 分钟 last_seen 启发式更精确
useEffect(() => {
const reconcile = (ids: ReadonlySet<number>) => {
if (ids.size === 0) return;
setUsers((prev) =>
prev.map((u) => (u.online === ids.has(u.id) ? u : { ...u, online: ids.has(u.id) }))
);
};
reconcile(realtime.getOnlineIds());
const off = realtime.onPresence(({ user_id: id, online }) => {
setUsers((prev) =>
prev.map((u) => (u.id === id && u.online !== online ? { ...u, online } : u))
);
});
return off;
}, []);
const load = useCallback(async (opts: { page: number; filter: UserFilter; q: string }) => {
const seq = ++seqRef.current;
setLoading(true);
@@ -319,10 +339,24 @@ export default function UsersAdmin({
);
const renderActions = (u: AdminUser, isSelf: boolean) => {
// 站长账号:任何人不可操作(后端 403 兜底),仅保留主页入口与站长标识
const canAudit = isOwner(currentUserRole);
const auditBtn = canAudit ? (
<Link
href={`/admin/users/${u.id}`}
title="内容档案"
aria-label={`查看 ${u.username} 的内容档案`}
className={ghostBtn}
style={{ color: "var(--accent)" }}
>
<FolderSearch size={15} />
</Link>
) : null;
// 站长账号:不可改角色/封禁,保留主页与(站长自己的)内容档案
if (u.role === ROLES.OWNER) {
return (
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<Link
href={`/u/${u.id}`}
title="查看个人主页"
@@ -336,17 +370,21 @@ export default function UsersAdmin({
}
if (isSelf) {
return (
<span
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
>
当前账号
</span>
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<span
className="inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap"
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
>
当前账号
</span>
</div>
);
}
const busy = actingId === u.id;
return (
<div className="flex items-center gap-1 justify-end">
{auditBtn}
<button
type="button"
title="登录历史"
@@ -623,7 +661,11 @@ export default function UsersAdmin({
</div>
<div className="min-w-0">{renderLastLogin(u)}</div>
<div className="hidden xl:block">
<p className="text-[12.5px] font-semibold tabular-nums" style={{ color: "var(--ink-2)" }}>
<p
className="text-[12.5px] font-semibold tabular-nums"
style={{ color: "var(--ink-2)" }}
title="仅统计已发布内容;驳回/删除见内容档案"
>
帖 {u.post_count} · 评 {u.comment_count}
</p>
<p className="text-[11px] tabular-nums" style={{ color: "var(--ink-3)" }}>
@@ -661,7 +703,11 @@ export default function UsersAdmin({
</div>
{renderStatus(u)}
</div>
<p className="mt-2.5 text-[11.5px] tabular-nums" style={{ color: "var(--ink-3)" }}>
<p
className="mt-2.5 text-[11.5px] tabular-nums"
style={{ color: "var(--ink-3)" }}
title="仅统计已发布内容;驳回/删除见内容档案"
>
帖 {u.post_count} · 评 {u.comment_count} · 注册 {formatDate(u.created_at)}
</p>
<p className="mt-1 text-[11.5px] tabular-nums flex items-center gap-1.5" style={{ color: "var(--ink-3)" }}>
@@ -671,37 +717,49 @@ export default function UsersAdmin({
{u.last_login_at ? ` · ${formatRelative(u.last_login_at)}` : ""}
</button>
</p>
{!isSelf && u.role !== ROLES.OWNER && (
<div className="flex items-center gap-2 mt-3 flex-wrap">
<div className="flex items-center gap-2 mt-3 flex-wrap">
{isOwner(currentUserRole) && (
<Link href={`/admin/users/${u.id}`} className="btn btn-line btn-sm">
<FolderSearch size={13} /> 内容档案
</Link>
)}
{(isSelf || u.role === ROLES.OWNER) && (
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
<ExternalLink size={13} /> 主页
</Link>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setRoleTarget(u)}
className="btn btn-line btn-sm"
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
>
<ShieldCheck size={13} />
角色权限
</button>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setBanTarget(u)}
className="btn btn-sm"
style={
u.banned
? { background: "var(--ok-soft)", color: "var(--ok)" }
: { background: "var(--danger-soft)", color: "var(--danger)" }
}
>
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
{u.banned ? "解封" : "封禁"}
</button>
</div>
)}
)}
{!isSelf && u.role !== ROLES.OWNER && (
<>
<Link href={`/u/${u.id}`} className="btn btn-line btn-sm">
<ExternalLink size={13} /> 主页
</Link>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setRoleTarget(u)}
className="btn btn-line btn-sm"
style={u.role !== ROLES.USER ? { color: "var(--accent)", borderColor: "var(--accent)" } : undefined}
>
<ShieldCheck size={13} />
角色权限
</button>
<button
type="button"
disabled={actingId === u.id}
onClick={() => setBanTarget(u)}
className="btn btn-sm"
style={
u.banned
? { background: "var(--ok-soft)", color: "var(--ok)" }
: { background: "var(--danger-soft)", color: "var(--danger)" }
}
>
{u.banned ? <RotateCcw size={13} /> : <Ban size={13} />}
{u.banned ? "解封" : "封禁"}
</button>
</>
)}
</div>
</div>
</div>
);

View File

@@ -0,0 +1,400 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import {
ArrowLeft,
ChevronLeft,
ChevronRight,
ExternalLink,
FileText,
Loader2,
MessageCircle,
MessagesSquare,
} from "lucide-react";
import {
apiAdminUserAuditComments,
apiAdminUserAuditMessages,
apiAdminUserAuditPosts,
type AdminAuditCommentItem,
type AdminAuditMessageItem,
type AdminAuditPostItem,
type AdminUserAuditProfile,
} from "@/lib/api";
import { formatDate, formatRelative } from "@/lib/format";
import Avatar from "@/components/Avatar";
import RoleBadge from "@/components/RoleBadge";
type TabKey = "posts" | "comments" | "messages";
const TABS: { key: TabKey; label: string; icon: React.ReactNode }[] = [
{ key: "posts", label: "帖子", icon: <FileText size={14} /> },
{ key: "comments", label: "评论", icon: <MessageCircle size={14} /> },
{ key: "messages", label: "私信与群消息", icon: <MessagesSquare size={14} /> },
];
const PAGE_SIZE = 20;
function StatusChip({
status,
deleted,
recalled,
}: {
status?: string;
deleted?: boolean;
recalled?: boolean;
}) {
const chips: { label: string; color: string; soft: string }[] = [];
if (deleted) chips.push({ label: "已删除", color: "var(--danger)", soft: "var(--danger-soft)" });
if (recalled) chips.push({ label: "已撤回", color: "var(--ink-3)", soft: "var(--tint)" });
if (status === "pending") chips.push({ label: "待审", color: "var(--gold)", soft: "var(--gold-soft)" });
if (status === "rejected") chips.push({ label: "已驳回", color: "var(--danger)", soft: "var(--danger-soft)" });
if (status === "published" && !deleted) {
chips.push({ label: "已发布", color: "var(--ok)", soft: "var(--ok-soft)" });
}
if (chips.length === 0 && !recalled) {
chips.push({ label: "正常", color: "var(--ink-3)", soft: "var(--tint)" });
}
return (
<span className="inline-flex flex-wrap gap-1">
{chips.map((c) => (
<span
key={c.label}
className="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-bold"
style={{ background: c.soft, color: c.color }}
>
{c.label}
</span>
))}
</span>
);
}
function Pager({
page,
total,
onChange,
loading,
}: {
page: number;
total: number;
onChange: (p: number) => void;
loading?: boolean;
}) {
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
if (pages <= 1) return null;
return (
<div className="flex items-center justify-center gap-2 py-3">
<button
type="button"
disabled={page <= 1 || loading}
onClick={() => onChange(page - 1)}
className="btn btn-line btn-sm"
aria-label="上一页"
>
<ChevronLeft size={14} />
</button>
<span className="text-[12.5px] tabular-nums meta">
{page} / {pages}
</span>
<button
type="button"
disabled={page >= pages || loading}
onClick={() => onChange(page + 1)}
className="btn btn-line btn-sm"
aria-label="下一页"
>
<ChevronRight size={14} />
</button>
</div>
);
}
export default function UserAuditClient({
userId,
initial,
}: {
userId: number;
initial: AdminUserAuditProfile;
}) {
const [profile] = useState(initial);
const [tab, setTab] = useState<TabKey>("posts");
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [posts, setPosts] = useState<AdminAuditPostItem[]>([]);
const [comments, setComments] = useState<AdminAuditCommentItem[]>([]);
const [messages, setMessages] = useState<AdminAuditMessageItem[]>([]);
const [total, setTotal] = useState(0);
const u = profile.user;
const load = useCallback(
async (t: TabKey, p: number) => {
setLoading(true);
setError("");
try {
if (t === "posts") {
const res = await apiAdminUserAuditPosts(userId, p);
setPosts(res.items || []);
setTotal(res.total);
} else if (t === "comments") {
const res = await apiAdminUserAuditComments(userId, p);
setComments(res.items || []);
setTotal(res.total);
} else {
const res = await apiAdminUserAuditMessages(userId, p);
setMessages(res.items || []);
setTotal(res.total);
}
} catch (e) {
setError(e instanceof Error ? e.message : "加载失败");
} finally {
setLoading(false);
}
},
[userId]
);
useEffect(() => {
load(tab, page);
}, [tab, page, load]);
const switchTab = (t: TabKey) => {
setTab(t);
setPage(1);
};
const tabCount = (t: TabKey) => {
if (t === "posts") return profile.posts_total;
if (t === "comments") return profile.comments_total;
return profile.messages_total;
};
return (
<div>
<Link
href="/admin/users"
className="inline-flex items-center gap-1.5 text-[13px] font-semibold mb-4 hover:opacity-80"
style={{ color: "var(--accent)" }}
>
<ArrowLeft size={14} />
返回用户列表
</Link>
<div className="panel p-4 sm:p-5 mb-4">
<div className="flex items-start gap-3.5">
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={48} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<h1
className="text-[18px] sm:text-[20px] font-extrabold truncate"
style={{ color: "var(--ink)" }}
>
{u.nickname}
</h1>
<RoleBadge role={u.role} />
{u.banned && (
<span
className="text-[11px] font-bold px-2 py-0.5 rounded-full"
style={{ background: "var(--danger-soft)", color: "var(--danger)" }}
>
已封禁
</span>
)}
</div>
<p className="meta text-[12.5px] mt-0.5 truncate">@{u.username}</p>
<p className="meta text-[12px] mt-2">
注册于 {formatDate(u.created_at)} · 已发布帖 {profile.published_posts} / 评{" "}
{profile.published_comments}
</p>
</div>
<Link
href={`/u/${u.id}`}
className="btn btn-line btn-sm gap-1.5 shrink-0"
target="_blank"
>
<ExternalLink size={13} />
主页
</Link>
</div>
<div
className="mt-4 grid grid-cols-3 gap-2 sm:gap-3 pt-4"
style={{ borderTop: "1px solid var(--line)" }}
>
{[
{ label: "全部帖子", value: profile.posts_total },
{ label: "全部评论", value: profile.comments_total },
{ label: "全部消息", value: profile.messages_total },
].map((c) => (
<div key={c.label} className="text-center">
<p
className="text-[20px] font-extrabold tabular-nums leading-none"
style={{ color: "var(--ink)" }}
>
{c.value.toLocaleString("zh-CN")}
</p>
<p className="meta text-[11.5px] mt-1.5">{c.label}</p>
</div>
))}
</div>
</div>
<div
className="flex gap-1 mb-3 overflow-x-auto"
style={{ borderBottom: "1px solid var(--line)" }}
>
{TABS.map((t) => {
const active = tab === t.key;
return (
<button
key={t.key}
type="button"
onClick={() => switchTab(t.key)}
className="inline-flex items-center gap-1.5 px-3 py-2.5 text-[13px] font-bold whitespace-nowrap -mb-px"
style={{
color: active ? "var(--accent)" : "var(--ink-3)",
borderBottom: active ? "2px solid var(--accent)" : "2px solid transparent",
}}
>
{t.icon}
{t.label}
<span className="tabular-nums font-semibold opacity-70">
{tabCount(t.key).toLocaleString("zh-CN")}
</span>
</button>
);
})}
</div>
<div className="panel overflow-hidden">
{error && (
<p className="text-center py-10 text-[13px]" style={{ color: "var(--danger)" }}>
{error}
</p>
)}
{!error && loading && posts.length + comments.length + messages.length === 0 && (
<div className="flex justify-center py-14" style={{ color: "var(--ink-3)" }}>
<Loader2 size={22} className="animate-spin" />
</div>
)}
{!error && !loading && total === 0 && (
<p className="meta text-center py-14 text-[13px]">该分类暂无内容</p>
)}
{tab === "posts" &&
posts.map((p) => (
<div
key={p.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip status={p.status} deleted={p.deleted} />
{p.board_name && (
<span className="text-[11.5px] meta truncate">{p.board_name}</span>
)}
</div>
{p.deleted ? (
<p className="text-[14px] font-bold" style={{ color: "var(--ink-3)" }}>
{p.title || "(无标题)"}
</p>
) : (
<Link
href={`/post/${p.id}`}
className="text-[14px] font-bold hover:underline"
style={{ color: "var(--ink)" }}
>
{p.title || "(无标题)"}
</Link>
)}
{p.content && (
<p className="meta text-[12.5px] mt-1 line-clamp-2 leading-relaxed">
{p.content}
</p>
)}
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(p.created_at)}
</span>
</div>
</div>
))}
{tab === "comments" &&
comments.map((c) => (
<div
key={c.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip status={c.status} deleted={c.deleted} />
{c.deleted ? (
<span className="text-[11.5px] meta">帖子 #{c.post_id}</span>
) : (
<Link
href={`/post/${c.post_id}`}
className="text-[11.5px] font-semibold hover:underline"
style={{ color: "var(--accent)" }}
>
帖子 #{c.post_id}
</Link>
)}
</div>
<p
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
style={{ color: c.deleted ? "var(--ink-3)" : "var(--ink)" }}
>
{c.content || "(空)"}
</p>
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(c.created_at)}
</span>
</div>
</div>
))}
{tab === "messages" &&
messages.map((m) => (
<div
key={m.id}
className="px-4 sm:px-5 py-3.5"
style={{ borderTop: "1px solid var(--line)" }}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap mb-1">
<StatusChip deleted={m.deleted} recalled={m.recalled} />
<span className="text-[11.5px] meta truncate">
{m.room_name}
{m.room_type === "direct" ? " · 私聊" : m.room_type === "group" ? " · 群聊" : ""}
</span>
</div>
<p
className="text-[13.5px] leading-relaxed whitespace-pre-wrap break-words"
style={{
color: m.recalled || m.deleted ? "var(--ink-3)" : "var(--ink)",
fontStyle: m.recalled ? "italic" : undefined,
}}
>
{m.content || "(空)"}
</p>
</div>
<span className="shrink-0 text-[11.5px] meta tabular-nums">
{formatRelative(m.created_at)}
</span>
</div>
</div>
))}
<Pager page={page} total={total} onChange={setPage} loading={loading} />
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { authCookieHeader } from "@/lib/cookies";
import { fetchAdminUserAudit } from "@/lib/api";
import { getMeCached } from "@/lib/serverData";
import { isOwner, isSuperOrOwner } from "@/lib/roles";
import Forbidden from "../../Forbidden";
import UserAuditClient from "./UserAuditClient";
export const metadata: Metadata = {
title: "用户内容档案",
};
interface PageProps {
params: Promise<{ id: string }>;
}
export default async function AdminUserAuditPage({ params }: PageProps) {
const { id: idRaw } = await params;
const userId = parseInt(idRaw, 10);
if (!Number.isFinite(userId) || userId <= 0) {
return <Forbidden text="无效的用户 ID。" />;
}
const cookie = authCookieHeader(await cookies());
const me = await getMeCached(cookie || undefined);
if (!me.user || !isSuperOrOwner(me.user.role)) {
return <Forbidden text="用户与角色权限仅超级管理员和站长可操作。" />;
}
if (!isOwner(me.user.role)) {
return <Forbidden text="用户内容档案仅站长可查看。" />;
}
let profile;
try {
profile = await fetchAdminUserAudit(userId, cookie || undefined);
} catch (e) {
const msg = e instanceof Error ? e.message : "获取用户档案失败";
return <Forbidden text={msg} />;
}
return <UserAuditClient userId={userId} initial={profile} />;
}