fix: 待审通知实时回填审核态并重构消息页体验

This commit is contained in:
2026-09-02 01:39:27 +08:00
parent 2e9c42a34c
commit 1c0f7ede55
18 changed files with 1458 additions and 463 deletions

View File

@@ -12,6 +12,7 @@ import (
"github.com/kardianos/service" "github.com/kardianos/service"
"git.iioio.com/freefire/jiang13-forum/config" "git.iioio.com/freefire/jiang13-forum/config"
forumsvc "git.iioio.com/freefire/jiang13-forum/service"
"git.iioio.com/freefire/jiang13-forum/model" "git.iioio.com/freefire/jiang13-forum/model"
"git.iioio.com/freefire/jiang13-forum/router" "git.iioio.com/freefire/jiang13-forum/router"
) )
@@ -78,6 +79,9 @@ func (p *program) setup() error {
if err := model.InitDB(cfg.DBPath()); err != nil { if err := model.InitDB(cfg.DBPath()); err != nil {
return fmt.Errorf("数据库初始化失败: %w", err) return fmt.Errorf("数据库初始化失败: %w", err)
} }
if err := forumsvc.BackfillModerationNotifyRefs(); err != nil {
log.Printf("待审通知关联字段回填警告: %v", err)
}
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil { if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
return fmt.Errorf("监控库初始化失败: %w", err) return fmt.Errorf("监控库初始化失败: %w", err)
} }

View File

@@ -664,6 +664,8 @@ export const api = {
}, },
markNotificationsRead: () => markNotificationsRead: () =>
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }), request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }),
markMessageRead: (id: number) =>
request<{ message: string }>(`/api/messages/${id}/read`, { method: 'POST' }),
sendMessage: (body: { to_user_id: number; subject?: string; content: string }) => sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
request<{ message: PrivateMessage }>('/api/messages', { request<{ message: PrivateMessage }>('/api/messages', {
method: 'POST', body: JSON.stringify(body), method: 'POST', body: JSON.stringify(body),

View File

@@ -717,9 +717,13 @@ export interface PrivateMessage {
to_user_id: number; to_user_id: number;
subject: string; subject: string;
content: string; content: string;
kind: 'user' | 'system' | 'reject' | 'report_result' | string; kind: 'user' | 'system' | 'reject' | 'report_result' | 'reply' | 'mention' | 'moderation' | string;
related_post_id?: number; related_post_id?: number;
related_report_id?: number; related_report_id?: number;
related_comment_id?: number;
related_floor?: number;
/** 待审目标实时状态pending|published|rejected|deleted */
related_status?: string;
is_read: boolean; is_read: boolean;
created_at: string; created_at: string;
from_user?: User; from_user?: User;

View File

@@ -72,6 +72,8 @@ export default function MainLayout() {
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments()); const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers()); const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread()); const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
const [dmUnread, setDmUnread] = useState(0);
const [notifyUnread, setNotifyUnread] = useState(0);
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags()); const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0); const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
const [postOutline, setPostOutline] = useState<{ const [postOutline, setPostOutline] = useState<{
@@ -309,13 +311,29 @@ export default function MainLayout() {
const refreshUnreadMessages = useCallback(() => { const refreshUnreadMessages = useCallback(() => {
if (!user) { if (!user) {
setUnreadMessages(0); setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
return; return;
} }
api.messageUnreadCount() api.messageUnreadCount()
.then((r) => setUnreadMessages(r.count || 0)) .then((r) => {
.catch(() => setUnreadMessages(0)); setUnreadMessages(r.count || 0);
setDmUnread(r.dm_count ?? 0);
setNotifyUnread(r.notify_count ?? 0);
})
.catch(() => {
setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
});
}, [user]); }, [user]);
/** 仅有通知未读时直达通知 Tab避免先看到空私信列表 */
const openMessages = useCallback(() => {
const path = notifyUnread > 0 && dmUnread === 0 ? '/messages?tab=notify' : '/messages';
void transitionTo(nav, path);
}, [nav, notifyUnread, dmUnread]);
useEffect(() => { useEffect(() => {
refreshUnreadMessages(); refreshUnreadMessages();
const onRefresh = () => refreshUnreadMessages(); const onRefresh = () => refreshUnreadMessages();
@@ -667,7 +685,7 @@ export default function MainLayout() {
className="header-icon-btn header-msg-btn" className="header-icon-btn header-msg-btn"
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'} title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'} aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
onClick={() => void transitionTo(nav, '/messages')} onClick={openMessages}
> >
<Mail size={18} aria-hidden /> <Mail size={18} aria-hidden />
{unreadMessages > 0 && ( {unreadMessages > 0 && (
@@ -691,7 +709,7 @@ export default function MainLayout() {
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}> <DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''} {typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/messages')}> <DropdownMenuItem onClick={openMessages}>
{unreadMessages > 0 ? ` (${unreadMessages})` : ''} {unreadMessages > 0 ? ` (${unreadMessages})` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}></DropdownMenuItem> <DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}></DropdownMenuItem>

View File

@@ -1,6 +1,18 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom'; import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Bell, CheckCheck, Inbox, Mail, Send } from 'lucide-react'; import {
ArrowLeft,
AtSign,
Bell,
CheckCheck,
Flag,
Inbox,
Mail,
MessageCircleReply,
Send,
ShieldAlert,
XCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner'; import { Spinner } from '@/components/ui/spinner';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
@@ -9,7 +21,7 @@ import type { MessageConversation, PrivateMessage, User } from '../api/types';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
import { useNoIndexSEO } from '../hooks/usePageSEO'; import { useNoIndexSEO } from '../hooks/usePageSEO';
import { formatTime } from '../utils/content'; import { formatDateTime, formatTime } from '../utils/content';
import { postPath } from '../utils/permalink'; import { postPath } from '../utils/permalink';
import { userPath } from '../utils/userPath'; import { userPath } from '../utils/userPath';
import { InFlowSiteFooter } from '../components/SiteFooter'; import { InFlowSiteFooter } from '../components/SiteFooter';
@@ -20,7 +32,6 @@ import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
type MsgTab = 'dm' | 'notify'; type MsgTab = 'dm' | 'notify';
type ConvSnap = { conversations: MessageConversation[]; total: number; page: number }; type ConvSnap = { conversations: MessageConversation[]; total: number; page: number };
type NotifySnap = { notifications: PrivateMessage[]; total: number; page: number };
type ThreadSnap = { messages: PrivateMessage[]; total: number; peerUser: User | null }; type ThreadSnap = { messages: PrivateMessage[]; total: number; peerUser: User | null };
const NOTIFY_KINDS = [ const NOTIFY_KINDS = [
@@ -28,23 +39,91 @@ const NOTIFY_KINDS = [
{ key: 'reply', label: '回复' }, { key: 'reply', label: '回复' },
{ key: 'mention', label: '@提及' }, { key: 'mention', label: '@提及' },
{ key: 'moderation', label: '待审' }, { key: 'moderation', label: '待审' },
{ key: 'reject', label: '拒帖' }, { key: 'reject', label: '未通过' },
{ key: 'report_result', label: '举报' }, { key: 'report_result', label: '举报' },
{ key: 'system', label: '系统' }, { key: 'system', label: '系统' },
] as const; ] as const;
function kindLabel(kind: string) { function kindLabel(kind: string, relatedStatus?: string) {
if (kind === 'moderation') {
if (relatedStatus && relatedStatus !== 'pending') return '审核';
return '待审';
}
switch (kind) { switch (kind) {
case 'reject': return '拒帖通知'; case 'reject': return '未通过';
case 'report_result': return '举报结果'; case 'report_result': return '举报结果';
case 'reply': return '回复提醒'; case 'reply': return '回复提醒';
case 'mention': return '@提及'; case 'mention': return '@提及';
case 'moderation': return '待审提醒';
case 'system': return '系统通知'; case 'system': return '系统通知';
default: return '通知'; default: return '通知';
} }
} }
function statusLabel(status?: string) {
switch (status) {
case 'pending': return '待审';
case 'published': return '已通过';
case 'rejected': return '未通过';
case 'deleted': return '已删除';
default: return '';
}
}
/** 仍待处理的审核通知(无状态按待审处理,兼容未回填) */
function isPendingModeration(m: PrivateMessage) {
return m.kind === 'moderation' && (!m.related_status || m.related_status === 'pending');
}
function KindIcon({ kind }: { kind: string }) {
const props = { size: 15, 'aria-hidden': true as const };
switch (kind) {
case 'reply': return <MessageCircleReply {...props} />;
case 'mention': return <AtSign {...props} />;
case 'moderation': return <ShieldAlert {...props} />;
case 'reject': return <XCircle {...props} />;
case 'report_result': return <Flag {...props} />;
default: return <Bell {...props} />;
}
}
/** 按通知类型生成跳转目标与 CTA 文案(待审跳前台帖/楼层) */
function notifyTarget(m: PrivateMessage): { to: string; label: string } | null {
const postID = m.related_post_id;
const commentID = m.related_comment_id;
const floor = m.related_floor && m.related_floor > 0 ? m.related_floor : 0;
const looksLikeComment =
(m.subject || '').includes('评论') || (m.content || '').includes('评论');
if (m.kind === 'moderation') {
if (!postID) return null;
const isComment = !!commentID || looksLikeComment;
const path = isComment && floor > 0
? `${postPath(postID)}#floor-${floor}`
: postPath(postID);
const pending = isPendingModeration(m);
if (isComment) {
return { to: path, label: pending ? '去审核评论' : '查看评论' };
}
return { to: path, label: pending ? '去审核帖子' : '查看帖子' };
}
if (postID) {
const path = floor > 0 ? `${postPath(postID)}#floor-${floor}` : postPath(postID);
if (m.kind === 'reply' || m.kind === 'mention') {
return { to: path, label: floor > 0 ? '查看回复' : '查看帖子' };
}
if (m.kind === 'reject' && (commentID || looksLikeComment)) {
return { to: path, label: '查看评论' };
}
if (m.kind === 'report_result' && floor > 0) {
return { to: path, label: '查看评论' };
}
return { to: path, label: '查看帖子' };
}
return null;
}
function peerTitle(conv: MessageConversation | null, peerUser: User | null | undefined, peerId: number) { function peerTitle(conv: MessageConversation | null, peerUser: User | null | undefined, peerId: number) {
if (peerId === 0 || conv?.is_system) return '系统通知'; if (peerId === 0 || conv?.is_system) return '系统通知';
return peerUser?.nickname || conv?.peer_user?.nickname || `用户 #${peerId}`; return peerUser?.nickname || conv?.peer_user?.nickname || `用户 #${peerId}`;
@@ -72,7 +151,7 @@ function AvatarBubble({
if (system) { if (system) {
return ( return (
<span className="pm-avatar pm-avatar--system" aria-hidden> <span className="pm-avatar pm-avatar--system" aria-hidden>
<Bell size={16} /> <Bell size={14} />
</span> </span>
); );
} }
@@ -83,7 +162,6 @@ function AvatarBubble({
} }
function parseTab(raw: string | null, peer: string | null): MsgTab { function parseTab(raw: string | null, peer: string | null): MsgTab {
// 带 peer 时强制私信页(用户主页「发私信」入口)
if (peer !== null && peer !== '') return 'dm'; if (peer !== null && peer !== '') return 'dm';
return raw === 'notify' ? 'notify' : 'dm'; return raw === 'notify' ? 'notify' : 'dm';
} }
@@ -121,16 +199,23 @@ export default function MessagesPage() {
const [notifyLoading, setNotifyLoading] = useState(false); const [notifyLoading, setNotifyLoading] = useState(false);
const [notifyUnread, setNotifyUnread] = useState(0); const [notifyUnread, setNotifyUnread] = useState(0);
const [dmUnread, setDmUnread] = useState(0); const [dmUnread, setDmUnread] = useState(0);
const [unreadOnly, setUnreadOnly] = useState(false);
const threadEndRef = useRef<HTMLDivElement>(null); const threadEndRef = useRef<HTMLDivElement>(null);
const threadScrollRef = useRef<HTMLDivElement>(null); const threadScrollRef = useRef<HTMLDivElement>(null);
const stickToBottomRef = useRef(true); const stickToBottomRef = useRef(true);
const notifyLoadSeq = useRef(0);
const dmConversations = useMemo( const dmConversations = useMemo(
() => conversations.filter((c) => !c.is_system && c.peer_user_id > 0), () => conversations.filter((c) => !c.is_system && c.peer_user_id > 0),
[conversations], [conversations],
); );
const visibleNotifications = useMemo(
() => (unreadOnly ? notifications.filter((m) => !m.is_read) : notifications),
[notifications, unreadOnly],
);
const refreshUnreadSplit = useCallback(async () => { const refreshUnreadSplit = useCallback(async () => {
try { try {
const r = await api.messageUnreadCount(); const r = await api.messageUnreadCount();
@@ -173,18 +258,9 @@ export default function MessagesPage() {
} }
}, []); }, []);
// 通知列表不走 session 短路,保证 related_status 实时
const loadNotifications = useCallback(async (page = 1, append = false, kind = 'all') => { const loadNotifications = useCallback(async (page = 1, append = false, kind = 'all') => {
const key = `messages:notify:${kind}:${page}`; const seq = ++notifyLoadSeq.current;
if (!append) {
const hit = getSessionSnapshot<NotifySnap>(key);
if (hit) {
setNotifications(hit.notifications);
setNotifyTotal(hit.total);
setNotifyPage(hit.page);
setNotifyLoading(false);
return;
}
}
setNotifyLoading(true); setNotifyLoading(true);
try { try {
const r = await api.messageNotifications({ const r = await api.messageNotifications({
@@ -192,24 +268,16 @@ export default function MessagesPage() {
size: 30, size: 30,
kind: kind === 'all' ? undefined : kind, kind: kind === 'all' ? undefined : kind,
}); });
if (seq !== notifyLoadSeq.current) return;
const next = r.notifications || []; const next = r.notifications || [];
setNotifyTotal(r.total || 0); setNotifyTotal(r.total || 0);
setNotifyPage(r.page || page); setNotifyPage(r.page || page);
// 打开通知页时标已读(首屏)
if (!append && page === 1) {
await api.markNotificationsRead().catch(() => undefined);
const marked = next.map((m) => ({ ...m, is_read: true }));
setNotifications(marked);
setSessionSnapshot(key, { notifications: marked, total: r.total || 0, page: r.page || page });
setNotifyUnread(0);
window.dispatchEvent(new Event('messages-unread-refresh'));
} else {
setNotifications((prev) => (append ? [...prev, ...next] : next)); setNotifications((prev) => (append ? [...prev, ...next] : next));
}
} catch (e: unknown) { } catch (e: unknown) {
if (seq !== notifyLoadSeq.current) return;
notify.error(e instanceof Error ? e.message : '加载通知失败'); notify.error(e instanceof Error ? e.message : '加载通知失败');
} finally { } finally {
setNotifyLoading(false); if (seq === notifyLoadSeq.current) setNotifyLoading(false);
} }
}, []); }, []);
@@ -221,18 +289,16 @@ export default function MessagesPage() {
nav(loginPath('/messages')); nav(loginPath('/messages'));
return; return;
} }
void refreshUnreadSplit();
if (tab === 'dm') { if (tab === 'dm') {
if (!getSessionSnapshot('messages:conv:1')) void refreshUnreadSplit();
loadConversations(1); loadConversations(1);
} else { } else {
if (!getSessionSnapshot(`messages:notify:${notifyKind}:1`)) void refreshUnreadSplit();
loadNotifications(1, false, notifyKind); loadNotifications(1, false, notifyKind);
} }
}, [user, authLoading, nav, tab, notifyKind, loadConversations, loadNotifications, refreshUnreadSplit]); }, [user, authLoading, nav, tab, notifyKind, loadConversations, loadNotifications, refreshUnreadSplit]);
useEffect(() => { useEffect(() => {
const onForce = () => { const onForce = () => {
// 下拉预热会话列表后直接重读;线程快照需作废以便重拉
void refreshUnreadSplit(); void refreshUnreadSplit();
if (tab === 'dm') { if (tab === 'dm') {
void loadConversations(1); void loadConversations(1);
@@ -241,8 +307,6 @@ export default function MessagesPage() {
setThreadEpoch(n => n + 1); setThreadEpoch(n => n + 1);
} }
} else { } else {
// 通知列表:预热未覆盖 kind作废后重拉
deleteSessionSnapshot(`messages:notify:${notifyKind}:1`);
void loadNotifications(1, false, notifyKind); void loadNotifications(1, false, notifyKind);
} }
}; };
@@ -365,6 +429,23 @@ export default function MessagesPage() {
} }
}; };
const openNotification = async (m: PrivateMessage) => {
const target = notifyTarget(m);
if (!m.is_read) {
setNotifications((prev) => prev.map((item) => (item.id === m.id ? { ...item, is_read: true } : item)));
setNotifyUnread((n) => Math.max(0, n - 1));
api.markMessageRead(m.id)
.then(() => {
window.dispatchEvent(new Event('messages-unread-refresh'));
void refreshUnreadSplit();
})
.catch(() => undefined);
}
if (target) {
nav(target.to);
}
};
const loadOlder = async () => { const loadOlder = async () => {
if (!peerSelected || selectedPeer === null || messages.length === 0) return; if (!peerSelected || selectedPeer === null || messages.length === 0) return;
const oldest = messages[0]?.id; const oldest = messages[0]?.id;
@@ -452,15 +533,10 @@ export default function MessagesPage() {
return ( return (
<div className="page-wrap"> <div className="page-wrap">
<div className="page-inner-wide"> <div className="page-inner-wide">
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
<ArrowLeft />
</Button>
<div className="pm-page-head"> <div className="pm-page-head">
<div> <div>
<h1 className="page-title"></h1> <h1 className="page-title"></h1>
<p className="page-desc"></p> <p className="page-desc"></p>
</div> </div>
{unreadForTab > 0 && ( {unreadForTab > 0 && (
<Button variant="outline" size="sm" onClick={markAll}> <Button variant="outline" size="sm" onClick={markAll}>
@@ -470,6 +546,7 @@ export default function MessagesPage() {
)} )}
</div> </div>
<div className="pm-workspace content-surface">
<div className="pm-tabs" role="tablist" aria-label="消息类型"> <div className="pm-tabs" role="tablist" aria-label="消息类型">
<button <button
type="button" type="button"
@@ -496,7 +573,8 @@ export default function MessagesPage() {
</div> </div>
{tab === 'notify' ? ( {tab === 'notify' ? (
<div className="pm-notify content-surface"> <div className="pm-notify">
<div className="pm-notify-toolbar">
<div className="pm-notify-filters" role="tablist" aria-label="通知类型"> <div className="pm-notify-filters" role="tablist" aria-label="通知类型">
{NOTIFY_KINDS.map((k) => ( {NOTIFY_KINDS.map((k) => (
<button <button
@@ -504,38 +582,80 @@ export default function MessagesPage() {
type="button" type="button"
role="tab" role="tab"
aria-selected={notifyKind === k.key} aria-selected={notifyKind === k.key}
className={cn('pm-notify-filter', notifyKind === k.key && 'active')} className={cn(
'pm-notify-filter',
notifyKind === k.key && 'active',
)}
onClick={() => setKind(k.key)} onClick={() => setKind(k.key)}
> >
{k.label} {k.label}
</button> </button>
))} ))}
</div> </div>
<button
type="button"
className={cn('pm-notify-unread-toggle', unreadOnly && 'active')}
aria-pressed={unreadOnly}
onClick={() => setUnreadOnly((v) => !v)}
>
</button>
</div>
{notifyLoading && notifications.length === 0 ? ( {notifyLoading && notifications.length === 0 ? (
<div className="flex justify-center py-16"><Spinner /></div> <div className="flex justify-center py-16"><Spinner /></div>
) : notifications.length === 0 ? ( ) : visibleNotifications.length === 0 ? (
<div className="pm-empty"> <div className="pm-empty">
<Bell size={28} strokeWidth={1.5} aria-hidden /> <Bell size={28} strokeWidth={1.5} aria-hidden />
<p></p> <p>{unreadOnly ? '没有未读通知' : '暂无通知'}</p>
<span></span> <span>{unreadOnly ? '切换筛选查看全部通知' : '有人回复你、审核结果等会出现在这里'}</span>
</div> </div>
) : ( ) : (
<ul className="pm-notify-list"> <ul className="pm-notify-list">
{notifications.map((m) => ( {visibleNotifications.map((m) => {
<li key={m.id} className={cn('pm-notify-item', !m.is_read && 'unread')}> const target = notifyTarget(m);
<div className="pm-notify-item__kind">{kindLabel(m.kind)}</div> const pendingMod = isPendingModeration(m);
const st = statusLabel(m.related_status);
const clickable = !!target || !m.is_read;
return (
<li key={m.id}>
<button
type="button"
className={cn(
'pm-notify-item',
!m.is_read && 'unread',
pendingMod && 'pm-notify-item--moderation',
clickable && 'pm-notify-item--clickable',
)}
onClick={() => void openNotification(m)}
disabled={!clickable}
>
<span className="pm-notify-item__icon" aria-hidden>
<KindIcon kind={m.kind} />
</span>
<div className="pm-notify-item__body">
<div className="pm-notify-item__top">
<span className="pm-notify-item__kind">
{kindLabel(m.kind, m.related_status)}
</span>
{m.kind === 'moderation' && st && m.related_status && m.related_status !== 'pending' && (
<span className={cn('pm-notify-status', `pm-notify-status--${m.related_status}`)}>
{st}
</span>
)}
{!m.is_read && <span className="pm-notify-item__dot" aria-label="未读" />}
<time className="pm-notify-item__time">{formatTime(m.created_at)}</time>
</div>
{m.subject && <div className="pm-notify-item__subject">{m.subject}</div>} {m.subject && <div className="pm-notify-item__subject">{m.subject}</div>}
<div className="pm-notify-item__text">{m.content}</div> <div className="pm-notify-item__text">{m.content}</div>
<div className="pm-notify-item__meta"> {target && (
<time>{formatTime(m.created_at)}</time> <span className="pm-notify-item__cta">{target.label} </span>
{m.related_post_id ? ( )}
<Link className="pm-notify-item__link" to={postPath(m.related_post_id)}>
</Link>
) : null}
</div> </div>
</button>
</li> </li>
))} );
})}
</ul> </ul>
)} )}
{notifyTotal > notifications.length && ( {notifyTotal > notifications.length && (
@@ -552,7 +672,7 @@ export default function MessagesPage() {
)} )}
</div> </div>
) : ( ) : (
<div className={cn('pm-layout content-surface', peerSelected && 'pm-layout--thread')}> <div className={cn('pm-layout', peerSelected && 'pm-layout--thread')}>
<aside className="pm-list" aria-label="会话列表"> <aside className="pm-list" aria-label="会话列表">
{listLoading && dmConversations.length === 0 ? ( {listLoading && dmConversations.length === 0 ? (
<div className="flex justify-center py-10"><Spinner /></div> <div className="flex justify-center py-10"><Spinner /></div>
@@ -573,15 +693,12 @@ export default function MessagesPage() {
className={cn('pm-conv-item', active && 'active', c.unread_count > 0 && 'unread')} className={cn('pm-conv-item', active && 'active', c.unread_count > 0 && 'unread')}
onClick={() => openPeer(c.peer_user_id)} onClick={() => openPeer(c.peer_user_id)}
> >
<AvatarBubble <AvatarBubble name={name} avatar={c.peer_user?.avatar} />
name={name}
avatar={c.peer_user?.avatar}
/>
<div className="pm-conv-item__body"> <div className="pm-conv-item__body">
<div className="pm-conv-item__top"> <div className="pm-conv-item__top">
<span className="pm-conv-item__name">{name}</span> <span className="pm-conv-item__name">{name}</span>
<span className="pm-conv-item__time"> <span className="pm-conv-item__time">
{formatTime(c.last_message?.created_at || c.updated_at)} {formatDateTime(c.last_message?.created_at || c.updated_at)}
</span> </span>
</div> </div>
<div className="pm-conv-item__preview"> <div className="pm-conv-item__preview">
@@ -666,7 +783,7 @@ export default function MessagesPage() {
<div className={cn('pm-bubble', mine && 'pm-bubble--mine')}> <div className={cn('pm-bubble', mine && 'pm-bubble--mine')}>
<div className="pm-bubble__text">{m.content}</div> <div className="pm-bubble__text">{m.content}</div>
<div className="pm-bubble__meta"> <div className="pm-bubble__meta">
<time>{formatTime(m.created_at)}</time> <time>{formatDateTime(m.created_at)}</time>
</div> </div>
</div> </div>
</div> </div>
@@ -710,6 +827,7 @@ export default function MessagesPage() {
</section> </section>
</div> </div>
)} )}
</div>
<InFlowSiteFooter /> <InFlowSiteFooter />
</div> </div>
</div> </div>

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Trash2, RotateCcw } from 'lucide-react'; import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
export default function AdminCommentsPage() { export default function AdminCommentsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [comments, setComments] = useState<Comment[]>([]); const [comments, setComments] = useState<Comment[]>([]);
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [revComment, setRevComment] = useState<Comment | null>(null); const [revComment, setRevComment] = useState<Comment | null>(null);
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadList = (p = page, st: Tab = tab) => { const loadList = (p = page, st: Tab = tab) => {
setLoading(true); setLoading(true);
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, tab]); }, [ready, tab]);
// 从通知深链 ?id= 定位并高亮待审行
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = comments.find((c) => c.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-comment-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
// pending 未找到则切到全部再试一次
if (tab === 'pending') {
setTab('all');
setPage(1);
return;
}
focusTriedRef.current = true;
notify.warning('该评论可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, comments, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const approve = async (id: number) => { const approve = async (id: number) => {
try { try {
const r = await api.adminApproveComment(id); const r = await api.adminApproveComment(id);
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
</thead> </thead>
<tbody> <tbody>
{comments.map(c => ( {comments.map(c => (
<tr key={c.id}> <tr
key={c.id}
id={`admin-comment-row-${c.id}`}
className={cn(highlightId === c.id && 'admin-row-highlight')}
>
<td>{c.id}</td> <td>{c.id}</td>
<td>#{c.floor}</td> <td>#{c.floor}</td>
<td> <td>

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react'; import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -32,6 +32,8 @@ function formatAdminTime(iso: string) {
export default function AdminPostsPage() { export default function AdminPostsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [posts, setPosts] = useState<PostItem[]>([]); const [posts, setPosts] = useState<PostItem[]>([]);
@@ -42,6 +44,9 @@ export default function AdminPostsPage() {
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => { const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
setLoading(true); setLoading(true);
@@ -92,6 +97,43 @@ export default function AdminPostsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新 // eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
}, [ready, search, tab]); }, [ready, search, tab]);
// 从通知深链 ?id= 定位并高亮
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = posts.find((p) => p.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-post-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
if (tab === 'pending') {
setTab('active');
return;
}
focusTriedRef.current = true;
notify.warning('该帖子可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, posts, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const switchTab = (next: Tab) => { const switchTab = (next: Tab) => {
if (next === tab) return; if (next === tab) return;
setTab(next); setTab(next);
@@ -352,7 +394,11 @@ export default function AdminPostsPage() {
{posts.map(p => { {posts.map(p => {
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at); const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
return ( return (
<tr key={p.id}> <tr
key={p.id}
id={`admin-post-row-${p.id}`}
className={cn(highlightId === p.id && 'admin-row-highlight')}
>
<td>{p.id}</td> <td>{p.id}</td>
<td className="max-w-[200px] truncate"> <td className="max-w-[200px] truncate">
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}> <button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>

View File

@@ -12608,6 +12608,10 @@ button.profile-stat:hover strong {
.admin-table th, .admin-table td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--j13-border); } .admin-table th, .admin-table td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--j13-border); }
.admin-table th { font-weight: 600; color: hsl(var(--muted-foreground)); background: hsl(var(--muted) / 0.3); } .admin-table th { font-weight: 600; color: hsl(var(--muted-foreground)); background: hsl(var(--muted) / 0.3); }
.admin-table tr:last-child td { border-bottom: none; } .admin-table tr:last-child td { border-bottom: none; }
.admin-table tr.admin-row-highlight td {
background: color-mix(in srgb, #f97316 14%, transparent);
transition: background 0.4s ease;
}
.admin-table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; } .admin-table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.admin-table-email { max-width: 200px; word-break: break-all; } .admin-table-email { max-width: 200px; word-break: break-all; }
.admin-table-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; } .admin-table-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
@@ -12783,37 +12787,50 @@ button.profile-stat:hover strong {
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
margin-bottom: 12px; margin-bottom: 14px;
}
.pm-page-head .page-desc {
margin-bottom: 0;
}
.pm-workspace {
overflow: hidden;
padding: 0;
} }
.pm-tabs { .pm-tabs {
display: flex; display: flex;
gap: 0.35rem; gap: 0;
margin-bottom: 0.85rem; padding: 0 1rem;
border-bottom: 1px solid var(--j13-border-light);
background: var(--j13-bg-surface);
} }
.pm-tab { .pm-tab {
position: relative;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 0.35rem; gap: 0.4rem;
padding: 0.4rem 0.85rem; padding: 0.75rem 1rem;
border: 1px solid var(--j13-border, #e2e8f0); border: 0;
border-radius: 0.4rem; border-bottom: 2px solid transparent;
margin-bottom: -1px;
background: transparent; background: transparent;
color: var(--color-text-2, #475569); color: var(--color-text-3);
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 560; font-weight: 560;
cursor: pointer; cursor: pointer;
} }
.pm-tab:hover { .pm-tab:hover {
border-color: color-mix(in srgb, var(--j13-green, #18a058) 40%, var(--j13-border, #e2e8f0)); color: var(--color-text-1);
} }
.pm-tab.active { .pm-tab.active {
border-color: color-mix(in srgb, var(--j13-green, #18a058) 45%, transparent); color: var(--j13-green);
background: color-mix(in srgb, var(--j13-green, #18a058) 10%, transparent); border-bottom-color: var(--j13-green);
color: var(--j13-green, #18a058); font-weight: 650;
} }
.pm-tab__badge { .pm-tab__badge {
@@ -12828,30 +12845,60 @@ button.profile-stat:hover strong {
} }
.pm-notify { .pm-notify {
padding: 0.85rem 1rem 1rem; padding: 0;
border-radius: 0.5rem; }
.pm-notify-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem 1rem;
padding: 0.65rem 1rem 0;
border-bottom: 1px solid var(--j13-border-light);
} }
.pm-notify-filters { .pm-notify-filters {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 0.35rem; gap: 0;
margin-bottom: 0.85rem;
} }
.pm-notify-filter { .pm-notify-filter {
padding: 0.25rem 0.65rem; padding: 0.45rem 0.7rem;
border: 0; border: 0;
border-radius: 999px; border-bottom: 2px solid transparent;
background: color-mix(in srgb, var(--j13-muted, #94a3b8) 14%, transparent); margin-bottom: -1px;
color: var(--color-text-3, #64748b); background: transparent;
font-size: 0.78rem; color: var(--color-text-3);
font-size: 0.8rem;
cursor: pointer; cursor: pointer;
} }
.pm-notify-filter:hover {
color: var(--color-text-1);
}
.pm-notify-filter.active { .pm-notify-filter.active {
background: color-mix(in srgb, var(--j13-green, #18a058) 16%, transparent); color: var(--j13-green);
color: var(--j13-green, #18a058); border-bottom-color: var(--j13-green);
font-weight: 650;
}
.pm-notify-unread-toggle {
padding: 0.35rem 0.55rem;
border: 0;
background: transparent;
color: var(--color-text-3);
font-size: 0.78rem;
cursor: pointer;
user-select: none;
white-space: nowrap;
}
.pm-notify-unread-toggle:hover,
.pm-notify-unread-toggle.active {
color: var(--j13-green);
font-weight: 600; font-weight: 600;
} }
@@ -12859,68 +12906,182 @@ button.profile-stat:hover strong {
list-style: none; list-style: none;
margin: 0; margin: 0;
padding: 0; padding: 0;
display: flex;
flex-direction: column;
gap: 0.65rem;
} }
.pm-notify-item { .pm-notify-item {
padding: 0.75rem 0.85rem; display: flex;
border: 1px solid var(--j13-border, #e2e8f0); align-items: flex-start;
border-radius: 0.45rem; gap: 0.75rem;
background: var(--j13-card, #fff); width: 100%;
padding: 0.9rem 1rem;
border: 0;
border-bottom: 1px solid var(--j13-border-light);
border-left: 3px solid transparent;
background: transparent;
text-align: left;
font: inherit;
color: inherit;
cursor: default;
transition: background 0.12s;
}
.pm-notify-item--clickable {
cursor: pointer;
}
.pm-notify-item--clickable:hover {
background: color-mix(in srgb, var(--j13-green) 5%, transparent);
} }
.pm-notify-item.unread { .pm-notify-item.unread {
border-color: color-mix(in srgb, var(--j13-green, #18a058) 35%, var(--j13-border, #e2e8f0)); border-left-color: var(--j13-green);
background: color-mix(in srgb, var(--j13-green, #18a058) 5%, var(--j13-card, #fff)); background: color-mix(in srgb, var(--j13-green) 4%, transparent);
}
.pm-notify-item.unread .pm-notify-item__subject {
font-weight: 700;
color: var(--color-text-1);
}
.pm-notify-item:not(.unread) .pm-notify-item__subject {
font-weight: 560;
color: var(--color-text-2);
}
.pm-notify-item:not(.unread) .pm-notify-item__text {
color: var(--color-text-3);
}
/* 仅仍待审:极淡警示底与左侧细条 */
.pm-notify-item--moderation.unread {
border-left-color: color-mix(in srgb, #f97316 55%, var(--j13-border-light));
background: color-mix(in srgb, #f97316 4%, transparent);
}
.pm-notify-item--moderation:not(.unread) {
background: color-mix(in srgb, #f97316 3%, transparent);
}
.pm-notify-item__icon {
flex-shrink: 0;
width: 1.85rem;
height: 1.85rem;
border-radius: 0.4rem;
display: inline-flex;
align-items: center;
justify-content: center;
margin-top: 0.1rem;
background: color-mix(in srgb, var(--j13-muted, #94a3b8) 12%, transparent);
color: var(--color-text-3);
}
.pm-notify-item__body {
flex: 1;
min-width: 0;
}
.pm-notify-item__top {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.35rem 0.45rem;
margin-bottom: 0.2rem;
} }
.pm-notify-item__kind { .pm-notify-item__kind {
font-size: 0.72rem; font-size: 0.72rem;
font-weight: 650; font-weight: 600;
color: var(--j13-green, #18a058); color: var(--color-text-3);
margin-bottom: 0.25rem; }
.pm-notify-item--moderation .pm-notify-item__kind {
color: color-mix(in srgb, #c2410c 70%, var(--color-text-3));
}
.pm-notify-status {
display: inline-flex;
align-items: center;
padding: 0.05rem 0.35rem;
border-radius: 0.2rem;
font-size: 0.66rem;
font-weight: 600;
line-height: 1.35;
letter-spacing: 0.01em;
}
.pm-notify-status--pending {
background: color-mix(in srgb, #f97316 10%, transparent);
color: color-mix(in srgb, #c2410c 75%, var(--color-text-2));
}
.pm-notify-status--published {
background: color-mix(in srgb, var(--j13-green) 10%, transparent);
color: color-mix(in srgb, var(--j13-green) 80%, var(--color-text-2));
}
.pm-notify-status--rejected {
background: color-mix(in srgb, var(--j13-muted, #94a3b8) 14%, transparent);
color: var(--color-text-3);
}
.pm-notify-status--deleted {
background: color-mix(in srgb, var(--j13-muted, #94a3b8) 12%, transparent);
color: var(--color-text-4);
}
.pm-notify-item__dot {
width: 0.4rem;
height: 0.4rem;
border-radius: 50%;
background: var(--j13-green);
flex-shrink: 0;
}
.pm-notify-item--moderation .pm-notify-item__dot {
background: color-mix(in srgb, #f97316 70%, var(--j13-muted, #94a3b8));
}
.pm-notify-item__time {
margin-left: auto;
font-size: 0.72rem;
color: var(--color-text-4);
} }
.pm-notify-item__subject { .pm-notify-item__subject {
font-weight: 650; margin-bottom: 0.15rem;
margin-bottom: 0.25rem; font-size: 0.92rem;
line-height: 1.4;
} }
.pm-notify-item__text { .pm-notify-item__text {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-word; word-break: break-word;
color: var(--color-text-2, #475569); color: var(--color-text-2);
font-size: 0.9rem; font-size: 0.84rem;
line-height: 1.5; line-height: 1.5;
} }
.pm-notify-item__meta { .pm-notify-item__cta {
display: flex; display: inline-block;
flex-wrap: wrap; margin-top: 0.4rem;
align-items: center; font-size: 0.78rem;
gap: 0.75rem; font-weight: 600;
margin-top: 0.55rem; color: var(--j13-green);
font-size: 0.75rem;
color: var(--color-text-4, #94a3b8);
} }
.pm-notify-item__link { .pm-notify-item--moderation .pm-notify-item__cta {
color: var(--j13-green, #18a058); color: color-mix(in srgb, #c2410c 65%, var(--color-text-2));
text-decoration: none;
font-weight: 560;
}
.pm-notify-item__link:hover {
text-decoration: underline;
} }
.pm-layout { .pm-layout {
display: grid; display: grid;
grid-template-columns: minmax(200px, 240px) 1fr; grid-template-columns: 280px 1fr;
height: min(72vh, 680px); height: min(70vh, 640px);
min-height: 480px; min-height: 460px;
overflow: hidden; overflow: hidden;
} }
@@ -12931,8 +13092,8 @@ button.profile-stat:hover strong {
} }
.pm-avatar { .pm-avatar {
width: 40px; width: 36px;
height: 40px; height: 36px;
border-radius: 50%; border-radius: 50%;
object-fit: cover; object-fit: cover;
flex-shrink: 0; flex-shrink: 0;
@@ -12944,7 +13105,7 @@ button.profile-stat:hover strong {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 15px; font-size: 14px;
font-weight: 600; font-weight: 600;
color: var(--j13-green); color: var(--j13-green);
background: var(--j13-green-bg); background: var(--j13-green-bg);
@@ -12958,9 +13119,9 @@ button.profile-stat:hover strong {
.pm-conv-item { .pm-conv-item {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 10px;
width: 100%; width: 100%;
padding: 12px 14px; padding: 11px 12px;
border: none; border: none;
border-bottom: 1px solid var(--j13-border-light); border-bottom: 1px solid var(--j13-border-light);
background: transparent; background: transparent;
@@ -12968,26 +13129,20 @@ button.profile-stat:hover strong {
font: inherit; font: inherit;
color: inherit; color: inherit;
cursor: pointer; cursor: pointer;
transition: background 0.15s; transition: background 0.12s;
} }
.pm-conv-item:hover { .pm-conv-item:hover {
background: color-mix(in srgb, var(--j13-bg-surface) 70%, transparent); background: color-mix(in srgb, var(--j13-bg-surface) 75%, transparent);
} }
.pm-conv-item.active { .pm-conv-item.active {
background: var(--j13-bg-surface); background: var(--j13-bg-surface);
box-shadow: inset 3px 0 0 var(--j13-green); box-shadow: inset 2px 0 0 var(--j13-green);
} }
.pm-conv-item.unread .pm-conv-item__name { .pm-conv-item.unread .pm-conv-item__name {
font-weight: 700; font-weight: 700;
color: var(--color-text-1);
}
.pm-conv-item.unread .pm-conv-item__preview > span:first-child {
color: var(--color-text-1);
font-weight: 500;
} }
.pm-conv-item__body { .pm-conv-item__body {
@@ -13000,22 +13155,25 @@ button.profile-stat:hover strong {
justify-content: space-between; justify-content: space-between;
align-items: baseline; align-items: baseline;
gap: 8px; gap: 8px;
margin-bottom: 3px; margin-bottom: 2px;
} }
.pm-conv-item__name { .pm-conv-item__name {
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
font-size: 14px; font-size: 13.5px;
font-weight: 600; font-weight: 600;
color: var(--color-text-1); color: var(--color-text-1);
} }
.pm-conv-item__time { .pm-conv-item__time {
flex-shrink: 0; flex-shrink: 0;
font-size: 11px; font-size: 10.5px;
color: var(--color-text-4); color: var(--color-text-4);
text-align: right;
max-width: 7.5rem;
line-height: 1.25;
} }
.pm-conv-item__preview { .pm-conv-item__preview {
@@ -13039,7 +13197,7 @@ button.profile-stat:hover strong {
height: 18px; height: 18px;
padding: 0 5px; padding: 0 5px;
border-radius: 999px; border-radius: 999px;
background: #e11d48; background: hsl(var(--destructive));
color: #fff; color: #fff;
font-size: 10px; font-size: 10px;
font-weight: 700; font-weight: 700;
@@ -13064,7 +13222,7 @@ button.profile-stat:hover strong {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
padding: 12px 16px; padding: 11px 14px;
border-bottom: 1px solid var(--j13-border-light); border-bottom: 1px solid var(--j13-border-light);
flex-shrink: 0; flex-shrink: 0;
} }
@@ -13116,10 +13274,8 @@ a.pm-thread-head__name:hover {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
overflow-y: auto; overflow-y: auto;
padding: 16px 18px; padding: 16px 16px;
background: background: var(--j13-bg-workspace);
radial-gradient(ellipse at top, var(--j13-green-bg), transparent 55%),
var(--j13-bg-workspace);
} }
.pm-thread-older { .pm-thread-older {
@@ -13138,70 +13294,33 @@ a.pm-thread-head__name:hover {
justify-content: flex-end; justify-content: flex-end;
} }
.pm-bubble-row--system {
justify-content: center;
}
.pm-bubble { .pm-bubble {
max-width: min(78%, 480px); max-width: min(78%, 480px);
padding: 10px 12px; padding: 9px 12px;
border-radius: 14px 14px 14px 4px; border-radius: 12px 12px 12px 4px;
background: var(--j13-bg-surface); background: var(--j13-bg-block-muted);
border: 1px solid var(--j13-border-light); border: 1px solid transparent;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
} }
.pm-bubble--mine { .pm-bubble--mine {
border-radius: 14px 14px 4px 14px; border-radius: 12px 12px 4px 12px;
background: var(--j13-green-soft); background: var(--j13-green-soft);
border-color: color-mix(in srgb, var(--j13-green) 22%, var(--j13-border-light)); border-color: color-mix(in srgb, var(--j13-green) 18%, transparent);
}
.pm-bubble--system {
max-width: min(92%, 520px);
border-radius: 12px;
background: var(--j13-bg-surface);
border-color: var(--j13-border);
}
.pm-bubble__kind {
display: inline-block;
margin-bottom: 6px;
padding: 1px 7px;
border-radius: 999px;
background: var(--j13-bg-block-muted);
color: var(--color-text-2);
font-size: 11px;
font-weight: 600;
}
.pm-bubble__subject {
margin-bottom: 4px;
font-size: 13px;
font-weight: 600;
color: var(--color-text-1);
} }
.pm-bubble__text { .pm-bubble__text {
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-word; word-break: break-word;
font-size: 14px; font-size: 14px;
line-height: 1.65; line-height: 1.6;
color: var(--color-text-1); color: var(--color-text-1);
} }
.pm-bubble__link {
display: inline-block;
margin-top: 8px;
font-size: 12px;
font-weight: 500;
}
.pm-bubble__meta { .pm-bubble__meta {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
margin-top: 6px; margin-top: 5px;
font-size: 11px; font-size: 11px;
color: var(--color-text-4); color: var(--color-text-4);
} }
@@ -13234,7 +13353,7 @@ a.pm-thread-head__name:hover {
max-height: 140px; max-height: 140px;
resize: none; resize: none;
border: 1px solid var(--j13-border); border: 1px solid var(--j13-border);
border-radius: 12px; border-radius: 10px;
padding: 10px 12px; padding: 10px 12px;
font: inherit; font: inherit;
font-size: 14px; font-size: 14px;
@@ -13295,22 +13414,20 @@ a.pm-thread-head__name:hover {
} }
.pm-field input, .pm-field input,
.pm-field textarea, .pm-field select,
.pm-field select { .pm-field textarea {
width: 100%;
border: 1px solid var(--j13-border); border: 1px solid var(--j13-border);
border-radius: 6px; border-radius: 8px;
padding: 8px 10px; padding: 8px 10px;
font: inherit; font: inherit;
font-size: 13px;
color: var(--color-text-1);
background: var(--j13-bg-surface); background: var(--j13-bg-surface);
outline: none; color: var(--color-text-1);
} }
.pm-field input:focus, .pm-field input:focus,
.pm-field textarea:focus, .pm-field select:focus,
.pm-field select:focus { .pm-field textarea:focus {
outline: none;
border-color: var(--j13-green); border-color: var(--j13-green);
} }
@@ -13340,6 +13457,14 @@ a.pm-thread-head__name:hover {
.pm-thread-back { .pm-thread-back {
display: inline-flex; display: inline-flex;
} }
.pm-composer {
flex-wrap: wrap;
}
.pm-composer__send {
width: 100%;
}
} }
/* —— 用户徽章 / 等级 —— */ /* —— 用户徽章 / 等级 —— */

View File

@@ -421,13 +421,18 @@ func (h *Handlers) APIAdminRejectComment(c *gin.Context) {
title = "未知帖子" title = "未知帖子"
} }
pid := comment.PostID pid := comment.PostID
_, _ = h.Message.SendSystem( cid := comment.ID
floor := comment.Floor
_, _ = h.Message.SendSystemWithRefs(
comment.UserID, comment.UserID,
"评论未通过审核", "评论未通过审核",
service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason), service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason),
model.MessageKindReject, model.MessageKindReject,
&pid, service.SystemNotifyRefs{
nil, PostID: &pid,
CommentID: &cid,
Floor: &floor,
},
) )
} }
c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected}) c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected})

View File

@@ -136,6 +136,20 @@ func (h *Handlers) APIMarkNotificationsRead(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"}) c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"})
} }
// APIMarkMessageRead 单条消息已读
func (h *Handlers) APIMarkMessageRead(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的消息"})
return
}
if err := h.Message.MarkMessageRead(h.currentUserID(c), uint(id)); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "已标为已读"})
}
// APISendMessage 发送私信 // APISendMessage 发送私信
func (h *Handlers) APISendMessage(c *gin.Context) { func (h *Handlers) APISendMessage(c *gin.Context) {
var req struct { var req struct {

View File

@@ -234,8 +234,12 @@ type PrivateMessage struct {
Kind string `gorm:"size:32;default:user;index" json:"kind"` Kind string `gorm:"size:32;default:user;index" json:"kind"`
RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"` RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"`
RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"` RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"`
RelatedCommentID *uint `gorm:"index" json:"related_comment_id,omitempty"`
RelatedFloor *int `json:"related_floor,omitempty"` // 评论自身楼号,对应 #floor-N
IsRead bool `gorm:"default:false;index" json:"is_read"` IsRead bool `gorm:"default:false;index" json:"is_read"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
// RelatedStatus 列表接口实时回填pending|published|rejected|deleted不落库
RelatedStatus string `json:"related_status,omitempty" gorm:"-"`
FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"` FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"`
ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"` ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"`

View File

@@ -195,6 +195,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
api.GET("/messages/unread-count", h.APIMessageUnreadCount) api.GET("/messages/unread-count", h.APIMessageUnreadCount)
api.GET("/messages/notifications", h.APIMessageNotifications) api.GET("/messages/notifications", h.APIMessageNotifications)
api.POST("/messages/notifications/read", h.APIMarkNotificationsRead) api.POST("/messages/notifications/read", h.APIMarkNotificationsRead)
api.POST("/messages/:id/read", h.APIMarkMessageRead)
api.GET("/messages/conversations", h.APIMessageConversations) api.GET("/messages/conversations", h.APIMessageConversations)
api.GET("/messages/conversations/:peerId", h.APIConversationMessages) api.GET("/messages/conversations/:peerId", h.APIConversationMessages)
api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead) api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead)

View File

@@ -3,11 +3,13 @@ package service
import ( import (
"errors" "errors"
"fmt" "fmt"
"regexp"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
"git.iioio.com/freefire/jiang13-forum/model" "git.iioio.com/freefire/jiang13-forum/model"
"gorm.io/gorm"
) )
var ( var (
@@ -31,6 +33,8 @@ type MessageSendInput struct {
Kind string Kind string
RelatedPostID *uint RelatedPostID *uint
RelatedReportID *uint RelatedReportID *uint
RelatedCommentID *uint
RelatedFloor *int
} }
// Send 发送私信(用户互发或系统通知) // Send 发送私信(用户互发或系统通知)
@@ -89,6 +93,8 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
Kind: kind, Kind: kind,
RelatedPostID: in.RelatedPostID, RelatedPostID: in.RelatedPostID,
RelatedReportID: in.RelatedReportID, RelatedReportID: in.RelatedReportID,
RelatedCommentID: in.RelatedCommentID,
RelatedFloor: in.RelatedFloor,
IsRead: false, IsRead: false,
} }
if err := model.DB.Create(msg).Error; err != nil { if err := model.DB.Create(msg).Error; err != nil {
@@ -98,8 +104,24 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
return msg, nil return msg, nil
} }
// SystemNotifyRefs 系统通知关联目标(帖子 / 评论 / 举报)
type SystemNotifyRefs struct {
PostID *uint
ReportID *uint
CommentID *uint
Floor *int
}
// SendSystem 系统私信(管理员/系统 → 用户) // SendSystem 系统私信(管理员/系统 → 用户)
func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) { func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) {
return s.SendSystemWithRefs(toUserID, subject, content, kind, SystemNotifyRefs{
PostID: relatedPostID,
ReportID: relatedReportID,
})
}
// SendSystemWithRefs 系统私信(可附带评论楼层深链)
func (s *MessageService) SendSystemWithRefs(toUserID uint, subject, content, kind string, refs SystemNotifyRefs) (*model.PrivateMessage, error) {
if kind == "" { if kind == "" {
kind = model.MessageKindSystem kind = model.MessageKindSystem
} }
@@ -109,11 +131,27 @@ func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string
Subject: subject, Subject: subject,
Content: content, Content: content,
Kind: kind, Kind: kind,
RelatedPostID: relatedPostID, RelatedPostID: refs.PostID,
RelatedReportID: relatedReportID, RelatedReportID: refs.ReportID,
RelatedCommentID: refs.CommentID,
RelatedFloor: refs.Floor,
}) })
} }
// MarkMessageRead 将单条消息标为已读(仅收件人本人)
func (s *MessageService) MarkMessageRead(userID, messageID uint) error {
if messageID == 0 {
return errors.New("无效的消息")
}
res := model.DB.Model(&model.PrivateMessage{}).
Where("id = ? AND to_user_id = ? AND is_read = ?", messageID, userID, false).
Update("is_read", true)
if res.Error != nil {
return res.Error
}
return nil
}
// MarkAllRead 全部标为已读 // MarkAllRead 全部标为已读
func (s *MessageService) MarkAllRead(userID uint) error { func (s *MessageService) MarkAllRead(userID uint) error {
return model.DB.Model(&model.PrivateMessage{}). return model.DB.Model(&model.PrivateMessage{}).
@@ -175,9 +213,212 @@ func (s *MessageService) ListNotifications(userID uint, page, size int, kind str
if list == nil { if list == nil {
list = []model.PrivateMessage{} list = []model.PrivateMessage{}
} }
s.enrichModerationStatus(list)
return list, total, nil return list, total, nil
} }
// enrichModerationStatus 为待审通知回填目标当前审核状态
func (s *MessageService) enrichModerationStatus(list []model.PrivateMessage) {
if len(list) == 0 {
return
}
resolvedByIndex := enrichModerationCommentIDs(list)
commentIDs := make([]uint, 0, len(list))
postIDs := make([]uint, 0, len(list))
// 历史评论通知:按帖+楼层回查(兜底)
type pfKey struct {
PostID uint
Floor int
}
pfNeeded := make([]pfKey, 0, len(list))
seenC := map[uint]struct{}{}
seenP := map[uint]struct{}{}
seenPF := map[pfKey]struct{}{}
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
id := *m.RelatedCommentID
if _, ok := seenC[id]; !ok {
seenC[id] = struct{}{}
commentIDs = append(commentIDs, id)
}
continue
}
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
if _, ok := seenC[cid]; !ok {
seenC[cid] = struct{}{}
commentIDs = append(commentIDs, cid)
}
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
pid := *m.RelatedPostID
if looksLikeModerationComment(m.Subject, m.Content) {
floor := 0
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
floor = *m.RelatedFloor
} else {
floor = parseNotifyFloor(m.Content)
}
if floor > 0 {
k := pfKey{PostID: pid, Floor: floor}
if _, ok := seenPF[k]; !ok {
seenPF[k] = struct{}{}
pfNeeded = append(pfNeeded, k)
}
}
continue
}
if _, ok := seenP[pid]; !ok {
seenP[pid] = struct{}{}
postIDs = append(postIDs, pid)
}
}
commentStatus := map[uint]string{}
if len(commentIDs) > 0 {
type row struct {
ID uint
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "status", "deleted_at").
Where("id IN ?", commentIDs).
Find(&rows)
for _, r := range rows {
commentStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, id := range commentIDs {
if _, ok := commentStatus[id]; !ok {
commentStatus[id] = "deleted"
}
}
}
statusByPF := map[pfKey]string{}
if len(pfNeeded) > 0 {
postSet := map[uint]struct{}{}
for _, k := range pfNeeded {
postSet[k.PostID] = struct{}{}
}
pids := make([]uint, 0, len(postSet))
for id := range postSet {
pids = append(pids, id)
}
type row struct {
PostID uint
Floor int
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("post_id", "floor", "status", "deleted_at").
Where("post_id IN ?", pids).
Find(&rows)
for _, r := range rows {
k := pfKey{PostID: r.PostID, Floor: r.Floor}
// 同楼多条时后者覆盖;正常业务一帖一楼唯一
statusByPF[k] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, k := range pfNeeded {
if _, ok := statusByPF[k]; !ok {
statusByPF[k] = "deleted"
}
}
}
postStatus := map[uint]string{}
if len(postIDs) > 0 {
type row struct {
ID uint
Status string
DeletedAt gorm.DeletedAt
}
var rows []row
_ = model.DB.Unscoped().Model(&model.Post{}).
Select("id", "status", "deleted_at").
Where("id IN ?", postIDs).
Find(&rows)
for _, r := range rows {
postStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
}
for _, id := range postIDs {
if _, ok := postStatus[id]; !ok {
postStatus[id] = "deleted"
}
}
}
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
m.RelatedStatus = commentStatus[*m.RelatedCommentID]
continue
}
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
m.RelatedStatus = commentStatus[cid]
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
pid := *m.RelatedPostID
if looksLikeModerationComment(m.Subject, m.Content) {
floor := 0
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
floor = *m.RelatedFloor
} else {
floor = parseNotifyFloor(m.Content)
}
if floor > 0 {
m.RelatedStatus = statusByPF[pfKey{PostID: pid, Floor: floor}]
}
continue
}
m.RelatedStatus = postStatus[pid]
}
}
var notifyFloorRe = regexp.MustCompile(`#(\d+)\s*楼`)
// parseNotifyFloor 从待审评论文案解析楼号(如「#2 楼评论」「#1 楼下」)
func parseNotifyFloor(content string) int {
m := notifyFloorRe.FindStringSubmatch(content)
if len(m) < 2 {
return 0
}
var n int
_, _ = fmt.Sscanf(m[1], "%d", &n)
if n < 0 {
return 0
}
return n
}
func contentStatusOrDeleted(status string, deletedAt gorm.DeletedAt) string {
if deletedAt.Valid {
return "deleted"
}
if status != "" {
return status
}
return model.ContentStatusPublished
}
// MarkNotificationsRead 将系统通知全部标为已读 // MarkNotificationsRead 将系统通知全部标为已读
func (s *MessageService) MarkNotificationsRead(userID uint) error { func (s *MessageService) MarkNotificationsRead(userID uint) error {
return s.MarkConversationRead(userID, 0) return s.MarkConversationRead(userID, 0)

View File

@@ -0,0 +1,166 @@
package service
import (
"math"
"strings"
"time"
"git.iioio.com/freefire/jiang13-forum/model"
)
// looksLikeModerationComment 判断待审通知是否指向评论(含嵌套回复)
func looksLikeModerationComment(subject, content string) bool {
if strings.Contains(subject, "评论") || strings.Contains(content, "评论") {
return true
}
return strings.Contains(content, "回复") || strings.Contains(content, "楼下")
}
// isNestedModerationContent 嵌套回复待审(正文为「#N 楼下…」)
func isNestedModerationContent(content string) bool {
return strings.Contains(content, "楼下")
}
// resolveModerationCommentRef 为历史待审评论通知推断目标评论 ID 与自身楼号
func resolveModerationCommentRef(postID uint, content string, notifyAt time.Time) (commentID uint, floor int) {
if postID == 0 || model.DB == nil {
return 0, 0
}
displayFloor := parseNotifyFloor(content)
if displayFloor <= 0 {
return 0, 0
}
if isNestedModerationContent(content) {
var parent struct {
ID uint
}
err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id").
Where("post_id = ? AND floor = ?", postID, displayFloor).
First(&parent).Error
if err != nil || parent.ID == 0 {
return 0, 0
}
type childRow struct {
ID uint
Floor int
CreatedAt time.Time
}
var children []childRow
_ = model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "floor", "created_at").
Where("post_id = ? AND reply_to = ?", postID, parent.ID).
Find(&children).Error
if len(children) == 0 {
return 0, 0
}
if len(children) == 1 {
return children[0].ID, children[0].Floor
}
best := children[0]
bestDiff := math.MaxFloat64
for _, c := range children {
diff := math.Abs(float64(c.CreatedAt.Sub(notifyAt)))
if diff < bestDiff {
bestDiff = diff
best = c
}
}
// 通知与评论创建时间相差超过 7 天则放弃,避免误配旧回复
if bestDiff > float64(7*24*time.Hour) {
return 0, 0
}
return best.ID, best.Floor
}
var row struct {
ID uint
Floor int
}
err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id", "floor").
Where("post_id = ? AND floor = ?", postID, displayFloor).
First(&row).Error
if err != nil || row.ID == 0 {
return 0, 0
}
return row.ID, row.Floor
}
// BackfillModerationNotifyRefs 为历史 moderation 通知补写 related_comment_id / related_floor
func BackfillModerationNotifyRefs() error {
if model.DB == nil {
return nil
}
var rows []model.PrivateMessage
err := model.DB.Where("kind = ? AND (related_comment_id IS NULL OR related_comment_id = 0)", model.MessageKindModeration).
Find(&rows).Error
if err != nil {
return err
}
for _, m := range rows {
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
if !looksLikeModerationComment(m.Subject, m.Content) {
continue
}
cid, fl := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid == 0 {
continue
}
floor := fl
updates := map[string]interface{}{
"related_comment_id": cid,
"related_floor": floor,
}
_ = model.DB.Model(&model.PrivateMessage{}).Where("id = ?", m.ID).Updates(updates).Error
}
return nil
}
// enrichModerationCommentIDs 为无 related_comment_id 的评论类待审通知解析评论 ID
func enrichModerationCommentIDs(list []model.PrivateMessage) map[int]uint {
out := make(map[int]uint)
for i := range list {
m := &list[i]
if m.Kind != model.MessageKindModeration {
continue
}
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
continue
}
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
continue
}
if !looksLikeModerationComment(m.Subject, m.Content) {
continue
}
// 嵌套回复优先按子评论匹配,避免 displayFloor 查到父评论状态
if isNestedModerationContent(m.Content) {
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid > 0 {
out[i] = cid
}
continue
}
// 顶层评论:有 related_floor 时按楼号查 ID
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
var row struct{ ID uint }
if err := model.DB.Unscoped().Model(&model.Comment{}).
Select("id").
Where("post_id = ? AND floor = ?", *m.RelatedPostID, *m.RelatedFloor).
First(&row).Error; err == nil && row.ID > 0 {
out[i] = row.ID
}
continue
}
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
if cid > 0 {
out[i] = cid
}
}
return out
}

View File

@@ -0,0 +1,61 @@
package service
import (
"os"
"path/filepath"
"testing"
"git.iioio.com/freefire/jiang13-forum/model"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
// TestProductionDBModerationEnrich 用本地生产库拷贝验证 related_status 回填(无库则跳过)
func TestProductionDBModerationEnrich(t *testing.T) {
dbPath := filepath.Join("..", "dist", "data", "jiang13.db")
if _, err := os.Stat(dbPath); err != nil {
t.Skip("dist/data/jiang13.db 不存在,跳过")
}
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
model.DB = db
if err := BackfillModerationNotifyRefs(); err != nil {
t.Fatal(err)
}
var adminID uint
if err := db.Model(&model.User{}).Where("role = ?", model.RoleAdmin).Order("id asc").Limit(1).Pluck("id", &adminID).Error; err != nil || adminID == 0 {
t.Skip("无管理员用户,跳过")
}
svc := &MessageService{}
list, _, err := svc.ListNotifications(adminID, 1, 100, "moderation")
if err != nil {
t.Fatal(err)
}
if len(list) == 0 {
t.Skip("无 moderation 通知")
}
pendingUI := 0
published := 0
for _, m := range list {
if m.RelatedStatus == model.ContentStatusPublished {
published++
} else if m.RelatedStatus == "" || m.RelatedStatus == model.ContentStatusPending {
pendingUI++
t.Logf("仍无 published 状态: id=%d subject=%q status=%q content=%q", m.ID, m.Subject, m.RelatedStatus, m.Content)
}
}
t.Logf("moderation=%d published=%d pending_or_empty=%d", len(list), published, pendingUI)
if published == 0 {
t.Fatal("没有任何 moderation 通知回填为 published")
}
if pendingUI > 0 {
t.Fatalf("%d 条通知仍会被 UI 判为待审", pendingUI)
}
}

View File

@@ -0,0 +1,102 @@
package service
import (
"testing"
"time"
"git.iioio.com/freefire/jiang13-forum/model"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestParseNotifyFloor(t *testing.T) {
cases := map[string]int{
"用户 X 在《Y》提交了待审核 #2 楼评论": 2,
"用户 X 在《Y》#3 楼下提交了待审核回复": 3,
"无楼号": 0,
}
for content, want := range cases {
if got := parseNotifyFloor(content); got != want {
t.Errorf("parseNotifyFloor(%q) = %d, want %d", content, got, want)
}
}
}
func TestEnrichModerationStatusPublished(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.User{}, &model.Post{}, &model.Comment{}, &model.PrivateMessage{}); err != nil {
t.Fatal(err)
}
model.DB = db
post := model.Post{Title: "测试帖", Status: model.ContentStatusPublished, UserID: 1}
if err := db.Create(&post).Error; err != nil {
t.Fatal(err)
}
comment := model.Comment{
PostID: post.ID, UserID: 2, Floor: 2,
Status: model.ContentStatusPublished,
}
if err := db.Create(&comment).Error; err != nil {
t.Fatal(err)
}
pid := post.ID
msg := model.PrivateMessage{
FromUserID: 0,
ToUserID: 1,
Subject: "新的待审核评论",
Content: "用户 A 在《测试帖》提交了待审核 #2 楼评论",
Kind: model.MessageKindModeration,
RelatedPostID: &pid,
CreatedAt: time.Now(),
}
if err := db.Create(&msg).Error; err != nil {
t.Fatal(err)
}
svc := &MessageService{}
list := []model.PrivateMessage{msg}
svc.enrichModerationStatus(list)
if list[0].RelatedStatus != model.ContentStatusPublished {
t.Fatalf("RelatedStatus = %q, want published", list[0].RelatedStatus)
}
}
func TestResolveNestedModerationCommentRef(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Post{}, &model.Comment{}); err != nil {
t.Fatal(err)
}
model.DB = db
post := model.Post{Title: "嵌套", Status: model.ContentStatusPublished}
if err := db.Create(&post).Error; err != nil {
t.Fatal(err)
}
parent := model.Comment{PostID: post.ID, Floor: 1, Status: model.ContentStatusPublished}
child := model.Comment{
PostID: post.ID, Floor: 3, Status: model.ContentStatusPublished,
}
if err := db.Create(&parent).Error; err != nil {
t.Fatal(err)
}
rt := parent.ID
child.ReplyTo = &rt
child.CreatedAt = time.Now()
if err := db.Create(&child).Error; err != nil {
t.Fatal(err)
}
notifyAt := child.CreatedAt.Add(2 * time.Second)
cid, floor := resolveModerationCommentRef(post.ID, "用户 A 在《嵌套》#1 楼下提交了待审核回复", notifyAt)
if cid != child.ID || floor != 3 {
t.Fatalf("resolve = (%d, %d), want (%d, 3)", cid, floor, child.ID)
}
}

View File

@@ -96,9 +96,15 @@ func (s *NotifyService) NotifyCommentPublished(comment *model.Comment) {
subject := "收到新回复" subject := "收到新回复"
content := FormatReplyContent(authorName, title, displayFloor, isNested) content := FormatReplyContent(authorName, title, displayFloor, isNested)
pid := comment.PostID pid := comment.PostID
_, _ = s.messages.SendSystem(toUserID, subject, content, model.MessageKindReply, &pid, nil) cid := comment.ID
floor := comment.Floor
_, _ = s.messages.SendSystemWithRefs(toUserID, subject, content, model.MessageKindReply, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
})
s.sendReplyMail(toUserID, authorName, title, comment.PostID, displayFloor, isNested, comment.Content) s.sendReplyMail(toUserID, authorName, title, comment.PostID, comment.Floor, displayFloor, isNested, comment.Content)
} }
// NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人) // NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人)
@@ -125,6 +131,8 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
} }
displayFloor := s.resolveDisplayFloor(comment) displayFloor := s.resolveDisplayFloor(comment)
pid := comment.PostID pid := comment.PostID
cid := comment.ID
floor := comment.Floor
subject := "有人 @了你" subject := "有人 @了你"
content := FormatMentionContent(authorName, title, displayFloor) content := FormatMentionContent(authorName, title, displayFloor)
@@ -132,7 +140,11 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
if uid == 0 || uid == comment.UserID || uid == replyTo { if uid == 0 || uid == comment.UserID || uid == replyTo {
continue continue
} }
_, _ = s.messages.SendSystem(uid, subject, content, model.MessageKindMention, &pid, nil) _, _ = s.messages.SendSystemWithRefs(uid, subject, content, model.MessageKindMention, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
})
} }
} }
@@ -149,8 +161,9 @@ func (s *NotifyService) NotifyPendingPost(post *model.Post) {
subject := "新的待审核帖子" subject := "新的待审核帖子"
content := FormatPendingPostContent(authorName, title, post.ID) content := FormatPendingPostContent(authorName, title, post.ID)
pid := post.ID pid := post.ID
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) { s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{PostID: &pid}, func(siteName, baseURL string) (string, string, string) {
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, "/admin/posts")) adminPath := fmt.Sprintf("/admin/posts?id=%d", post.ID)
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, adminPath))
}) })
} }
@@ -173,14 +186,21 @@ func (s *NotifyService) NotifyPendingComment(comment *model.Comment) {
isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0 isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0
content := FormatPendingCommentContent(authorName, title, displayFloor, isNested) content := FormatPendingCommentContent(authorName, title, displayFloor, isNested)
pid := comment.PostID pid := comment.PostID
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) { cid := comment.ID
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, "/admin/comments")) floor := comment.Floor
adminPath := fmt.Sprintf("/admin/comments?id=%d", comment.ID)
s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{
PostID: &pid,
CommentID: &cid,
Floor: &floor,
}, func(siteName, baseURL string) (string, string, string) {
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, adminPath))
}) })
} }
func (s *NotifyService) notifyAdmins( func (s *NotifyService) notifyAdmins(
subject, content, kind string, subject, content, kind string,
relatedPostID *uint, refs SystemNotifyRefs,
buildMail func(siteName, baseURL string) (subj, text, html string), buildMail func(siteName, baseURL string) (subj, text, html string),
) { ) {
admins, err := s.listAdmins() admins, err := s.listAdmins()
@@ -197,7 +217,7 @@ func (s *NotifyService) notifyAdmins(
} }
for _, admin := range admins { for _, admin := range admins {
_, _ = s.messages.SendSystem(admin.ID, subject, content, kind, relatedPostID, nil) _, _ = s.messages.SendSystemWithRefs(admin.ID, subject, content, kind, refs)
email := strings.TrimSpace(admin.Email) email := strings.TrimSpace(admin.Email)
if email == "" || mailSubj == "" { if email == "" || mailSubj == "" {
continue continue
@@ -211,7 +231,7 @@ func (s *NotifyService) notifyAdmins(
} }
} }
func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, displayFloor int, isNested bool, rawContent string) { func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, ownFloor, displayFloor int, isNested bool, rawContent string) {
if s.mail == nil || !s.settings.MailReady() { if s.mail == nil || !s.settings.MailReady() {
return return
} }
@@ -227,6 +247,10 @@ func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle strin
baseURL := s.settings.SitePublicBaseURL("") baseURL := s.settings.SitePublicBaseURL("")
postPath := s.settings.Permalink().PostPath(postID) postPath := s.settings.Permalink().PostPath(postID)
link := AbsoluteURL(baseURL, postPath) link := AbsoluteURL(baseURL, postPath)
// 直达评论自身楼层(嵌套回复也有独立 floor
if ownFloor > 0 {
link = fmt.Sprintf("%s#floor-%d", link, ownFloor)
}
excerpt := truncateNotifyExcerpt(rawContent, 120) excerpt := truncateNotifyExcerpt(rawContent, 120)
subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link) subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link)
_ = s.mail.SendHTML(email, subj, text, html) _ = s.mail.SendHTML(email, subj, text, html)

View File

@@ -305,14 +305,20 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
if commentAuthorID > 0 { if commentAuthorID > 0 {
pid := postID pid := postID
rid := rep.ID rid := rep.ID
cid := *rep.CommentID
floor := commentFloor
body := fmt.Sprintf("你在帖子《%s》下的评论#%d未通过审核。\n\n原因\n%s", postTitle, commentFloor, reason) body := fmt.Sprintf("你在帖子《%s》下的评论#%d未通过审核。\n\n原因\n%s", postTitle, commentFloor, reason)
_, _ = s.messages.SendSystem( _, _ = s.messages.SendSystemWithRefs(
commentAuthorID, commentAuthorID,
fmt.Sprintf("评论未通过审核 · 《%s》", postTitle), fmt.Sprintf("评论未通过审核 · 《%s》", postTitle),
body, body,
model.MessageKindReject, model.MessageKindReject,
&pid, SystemNotifyRefs{
&rid, PostID: &pid,
ReportID: &rid,
CommentID: &cid,
Floor: &floor,
},
) )
} }
default: default:
@@ -345,13 +351,19 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
} }
pid := postID pid := postID
rid := rep.ID rid := rep.ID
_, _ = s.messages.SendSystem( resultRefs := SystemNotifyRefs{PostID: &pid, ReportID: &rid}
if isCommentReport && rep.CommentID != nil {
cid := *rep.CommentID
floor := commentFloor
resultRefs.CommentID = &cid
resultRefs.Floor = &floor
}
_, _ = s.messages.SendSystemWithRefs(
rep.ReporterID, rep.ReporterID,
"举报处理结果通知", "举报处理结果通知",
content, content,
model.MessageKindReportResult, model.MessageKindReportResult,
&pid, resultRefs,
&rid,
) )
_ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB { _ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB {