refactor(announcements,messaging,notifications): V1+V2 审计重构 — i18n 命名空间独立 + 通知标题 i18n 化 + 服务端过滤 + 编排下沉 + 表单错误展示 + 架构图同步

V1 改进(已完成):
- P0-4/P1-4/P1-5: 通知组件和 CRUD Action 从 messaging 迁移至 notifications 模块
- P1-5: 新增 getMessagesPageData / getAdminAnnouncementsPageData 编排函数
- P1-6: announcements schema 添加 superRefine 条件校验
- P1-7: 新增 useMessageSearch hook(防抖 + 请求竞态取消)+ 客户端分页 UI
- P1-9: deleteMessage 事务化
- P2-11: 全模块 trackEvent 埋点
- 全模块 i18n 接入 + Error Boundary + a11y 改进

V2 改进(本次完成):
- V2-P0-1: 通知 i18n 命名空间独立(notifications.json),useTranslations 从 "messages" 切换到 "notifications"
- V2-P0-2: 公告/消息通知标题 i18n 化,Server Action 中使用 getTranslations 生成通知标题
- V2-P1-1: AnnouncementList 纯服务端过滤,移除客户端 useState/useMemo
- V2-P1-2: MessageList 客户端过滤仅在初始数据时执行,搜索结果由服务端按 tab 过滤
- V2-P1-3: 消息详情页编排下沉,新增 getMessageDetailPageData 编排函数
- V2-P1-4: 表单服务端校验错误展示(fieldErrors + aria-invalid)
- V2-P2-1: 轮询间隔常量化(POLL_INTERVAL_MS)
- V2-P2-2: 架构图同步(004 + 005)
This commit is contained in:
SpecialX
2026-06-22 18:43:12 +08:00
parent 6d7838a210
commit 1fe30984b6
29 changed files with 1252 additions and 351 deletions

View File

@@ -1,7 +1,9 @@
"use server"
import { revalidatePath } from "next/cache"
import { getTranslations } from "next-intl/server"
import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard"
import { trackEvent } from "@/shared/lib/track-event"
import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state"
import { sendNotification } from "@/modules/notifications/dispatcher"
@@ -20,19 +22,12 @@ import {
getRecipients,
getUnreadMessageCount,
} from "./data-access"
import {
getNotifications,
markNotificationAsRead,
markAllNotificationsAsRead,
getUnreadNotificationCount,
} from "@/modules/notifications/data-access"
import {
getNotificationPreferences,
upsertNotificationPreferences,
} from "@/modules/notifications/preferences"
import type { Message, MessageType, RecipientOption } from "./types"
import type {
Notification,
NotificationPreferences,
UpdateNotificationPreferencesInput,
} from "@/modules/notifications/types"
@@ -70,10 +65,14 @@ export async function sendMessageAction(
// Notify the receiver about the new message via the notifications dispatcher.
// This respects user notification preferences (SMS/WeChat/Email/In-App).
const t = await getTranslations("messages")
const notifyTitle = input.subject
? t("notification.messageTitle", { subject: input.subject })
: t("notification.messageTitleNoSubject")
await sendNotification({
userId: input.receiverId,
type: "info",
title: input.subject ? `New message: ${input.subject}` : "New message",
title: notifyTitle,
content: input.content.slice(0, 200),
actionUrl: `/messages/${id}`,
metadata: { messageType: "message", messageId: id },
@@ -82,6 +81,14 @@ export async function sendMessageAction(
revalidatePath("/messages")
revalidatePath(`/messages/${id}`)
void trackEvent({
event: "message.sent",
userId: ctx.userId,
targetId: id,
targetType: "message",
properties: { receiverId: input.receiverId, hasSubject: !!input.subject },
})
return { success: true, message: "Message sent", data: id }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -102,6 +109,14 @@ export async function markMessageAsReadAction(messageId: string): Promise<Action
await markMessageAsRead(parsed.data.messageId, ctx.userId)
revalidatePath("/messages")
revalidatePath(`/messages/${parsed.data.messageId}`)
void trackEvent({
event: "message.marked_read",
userId: ctx.userId,
targetId: parsed.data.messageId,
targetType: "message",
})
return { success: true, message: "Marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -122,6 +137,14 @@ export async function deleteMessageAction(messageId: string): Promise<ActionStat
await deleteMessage(parsed.data.messageId, ctx.userId)
revalidatePath("/messages")
revalidatePath(`/messages/${parsed.data.messageId}`)
void trackEvent({
event: "message.deleted",
userId: ctx.userId,
targetId: parsed.data.messageId,
targetType: "message",
})
return { success: true, message: "Message deleted" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -193,59 +216,11 @@ export async function getUnreadMessageCountAction(): Promise<ActionState<number>
}
}
export async function getUnreadNotificationCountAction(): Promise<ActionState<number>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const count = await getUnreadNotificationCount(ctx.userId)
return { success: true, data: count }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getNotificationsAction(
params?: { page?: number; pageSize?: number; unreadOnly?: boolean }
): Promise<ActionState<{ items: Notification[]; total: number; page: number; pageSize: number; totalPages: number }>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const result = await getNotifications(ctx.userId, params)
return { success: true, data: result }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markNotificationAsReadAction(
notificationId: string
): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markNotificationAsRead(notificationId, ctx.userId)
revalidatePath("/messages")
return { success: true, message: "Notification marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markAllNotificationsAsReadAction(): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markAllNotificationsAsRead(ctx.userId)
revalidatePath("/messages")
return { success: true, message: "All notifications marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
// ---------------------------------------------------------------------------
// 通知相关 Server ActionsgetNotificationsAction / markNotificationAsReadAction /
// markAllNotificationsAsReadAction / getUnreadNotificationCountAction已迁移至
// @/modules/notifications/actions。请直接从 notifications 模块导入。
// ---------------------------------------------------------------------------
export async function getNotificationPreferencesAction(): Promise<ActionState<NotificationPreferences>> {
try {

View File

@@ -23,6 +23,8 @@ import {
import { sendMessageAction } from "../actions"
import type { RecipientOption } from "../types"
type FieldErrors = Record<string, string[]>
export function MessageCompose({
recipients,
parentMessageId,
@@ -40,10 +42,16 @@ export function MessageCompose({
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "")
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})
const getFieldError = (field: string): string | null => {
const errs = fieldErrors[field]
return errs && errs.length > 0 ? errs[0] : null
}
const handleSubmit = async (formData: FormData) => {
if (!receiverId) {
toast.error(t("messages.selectRecipient"))
toast.error(t("form.selectRecipient"))
return
}
formData.set("receiverId", receiverId)
@@ -52,6 +60,7 @@ export function MessageCompose({
}
setIsWorking(true)
setFieldErrors({})
try {
const res = await sendMessageAction(null, formData)
if (res.success) {
@@ -59,6 +68,10 @@ export function MessageCompose({
router.push("/messages")
router.refresh()
} else {
// 展示字段级错误(来自 Zod 校验)
if (res.errors) {
setFieldErrors(res.errors)
}
toast.error(res.message || t("messages.sendFailed"))
}
} catch {
@@ -85,7 +98,7 @@ export function MessageCompose({
<div className="grid gap-2">
<Label htmlFor="receiverId">{t("form.to")}</Label>
<Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}>
<SelectTrigger>
<SelectTrigger aria-invalid={!!getFieldError("receiverId")}>
<SelectValue placeholder={t("form.toPlaceholder")} />
</SelectTrigger>
<SelectContent>
@@ -98,6 +111,9 @@ export function MessageCompose({
</SelectContent>
</Select>
<input type="hidden" name="receiverId" value={receiverId} />
{getFieldError("receiverId") ? (
<p className="text-destructive text-xs">{getFieldError("receiverId")}</p>
) : null}
</div>
<div className="grid gap-2">
@@ -108,7 +124,11 @@ export function MessageCompose({
placeholder={t("form.subjectPlaceholder")}
defaultValue={defaultSubject ?? ""}
maxLength={255}
aria-invalid={!!getFieldError("subject")}
/>
{getFieldError("subject") ? (
<p className="text-destructive text-xs">{getFieldError("subject")}</p>
) : null}
</div>
<div className="grid gap-2">
@@ -119,7 +139,11 @@ export function MessageCompose({
placeholder={t("form.contentPlaceholder")}
className="min-h-[200px]"
required
aria-invalid={!!getFieldError("content")}
/>
{getFieldError("content") ? (
<p className="text-destructive text-xs">{getFieldError("content")}</p>
) : null}
</div>
<CardFooter className="justify-end gap-2 px-0">

View File

@@ -1,8 +1,8 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import { useMemo, useState } from "react"
import Link from "next/link"
import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2 } from "lucide-react"
import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { useTranslations } from "next-intl"
import { Badge } from "@/shared/components/ui/badge"
@@ -16,10 +16,14 @@ import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import { getMessagesAction } from "../actions"
import { useMessageSearch } from "../hooks/use-message-search"
import type { Message, MessageType } from "../types"
type Tab = "inbox" | "sent"
/** 客户端分页大小 */
const PAGE_SIZE = 20
export function MessageList({
messages,
currentUserId,
@@ -31,54 +35,44 @@ export function MessageList({
}) {
const t = useTranslations("messages")
const [tab, setTab] = useState<Tab>(initialType === "sent" ? "sent" : "inbox")
const [keyword, setKeyword] = useState("")
const [searchResults, setSearchResults] = useState<{ kw: string; tab: Tab; items: Message[] } | null>(null)
const [currentPage, setCurrentPage] = useState(1)
const { hasPermission } = usePermission()
const canSend = hasPermission(Permissions.MESSAGE_SEND)
// 防抖搜索keyword 或 tab 变化时调用 getMessagesAction
useEffect(() => {
const kw = keyword.trim()
if (kw.length === 0) {
return
}
let cancelled = false
const timer = setTimeout(async () => {
if (cancelled) return
const res = await getMessagesAction({ type: tab, keyword: kw })
if (cancelled) return
if (res.success && res.data) {
setSearchResults({ kw, tab, items: res.data.items })
}
}, 400)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [keyword, tab])
// 当前搜索结果是否匹配最新的 keyword 和 tab
const currentResults = searchResults && searchResults.kw === keyword.trim() && searchResults.tab === tab
? searchResults.items
: null
// 搜索中keyword 非空且尚无匹配结果
const searching = keyword.trim().length > 0 && currentResults === null
// 当 keyword 为空时使用 prop messages否则使用搜索结果
const displayMessages = currentResults ?? messages
const { keyword, setKeyword, results, searching, isUsingInitial } = useMessageSearch({
searchAction: getMessagesAction,
tab,
})
// 客户端过滤仅在初始数据type=all时需要搜索结果已由服务端按 tab 过滤
const filtered = useMemo(() => {
const displayMessages = isUsingInitial ? messages : (results ?? [])
if (!isUsingInitial) return displayMessages
if (tab === "inbox") return displayMessages.filter((m) => m.receiverId === currentUserId)
return displayMessages.filter((m) => m.senderId === currentUserId)
}, [displayMessages, tab, currentUserId])
}, [messages, results, tab, currentUserId, isUsingInitial])
// 客户端分页:超过 PAGE_SIZE 条时显示分页 UI
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
const safePage = Math.min(currentPage, totalPages)
const paged = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE)
const showPagination = filtered.length > PAGE_SIZE
// 切换 tab 或搜索时重置分页
const handleTabChange = (v: string): void => {
setTab(v as Tab)
setCurrentPage(1)
}
const handleKeywordChange = (v: string): void => {
setKeyword(v)
setCurrentPage(1)
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}>
<Tabs value={tab} onValueChange={handleTabChange}>
<TabsList>
<TabsTrigger value="inbox" className="gap-2">
<Inbox className="h-4 w-4" />
@@ -108,7 +102,7 @@ export function MessageList({
aria-label={t("search.placeholder")}
placeholder={t("search.placeholder")}
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onChange={(e) => handleKeywordChange(e.target.value)}
className="pl-9"
/>
{searching ? (
@@ -116,7 +110,7 @@ export function MessageList({
) : null}
</div>
{filtered.length === 0 ? (
{paged.length === 0 ? (
<EmptyState
title={tab === "inbox" ? t("empty.inboxEmpty") : t("empty.sentEmpty")}
description={
@@ -128,45 +122,73 @@ export function MessageList({
className="h-auto border-none shadow-none"
/>
) : (
<div className="space-y-3">
{filtered.map((m) => {
const isReceived = m.receiverId === currentUserId
const counterpart = isReceived ? m.senderName : m.receiverName
const unread = isReceived && !m.isRead
return (
<Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}>
<Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}>
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
{unread ? (
<Mail className="h-4 w-4 text-primary" aria-hidden="true" />
) : (
<MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" />
)}
<span className={cn("text-sm font-medium", unread && "text-primary")}>
{m.subject ?? t("meta.noSubject")}
</span>
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
<>
<div className="space-y-3">
{paged.map((m) => {
const isReceived = m.receiverId === currentUserId
const counterpart = isReceived ? m.senderName : m.receiverName
const unread = isReceived && !m.isRead
return (
<Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}>
<Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}>
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
{unread ? (
<Mail className="h-4 w-4 text-primary" aria-hidden="true" />
) : (
<MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" />
)}
<span className={cn("text-sm font-medium", unread && "text-primary")}>
{m.subject ?? t("meta.noSubject")}
</span>
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
</div>
<p className="text-muted-foreground text-xs">
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")}
</p>
</div>
<p className="text-muted-foreground text-xs">
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")}
<span className="text-muted-foreground shrink-0 text-xs">
{formatDate(m.createdAt)}
</span>
</CardHeader>
<CardContent className="pt-0">
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{m.content}
</p>
</div>
<span className="text-muted-foreground shrink-0 text-xs">
{formatDate(m.createdAt)}
</span>
</CardHeader>
<CardContent className="pt-0">
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{m.content}
</p>
</CardContent>
</Card>
</Link>
)
})}
</div>
</CardContent>
</Card>
</Link>
)
})}
</div>
{showPagination ? (
<div className="flex items-center justify-center gap-4 pt-2" role="navigation" aria-label={t("tabs.inbox")}>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
disabled={safePage <= 1}
aria-label="Previous page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-muted-foreground text-sm" aria-live="polite">
{safePage} / {totalPages}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={safePage >= totalPages}
aria-label="Next page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
) : null}
</>
)}
</div>
)

View File

@@ -1,181 +0,0 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { cn, formatDate } from "@/shared/lib/utils"
import {
getNotificationsAction,
getUnreadNotificationCountAction,
markAllNotificationsAsReadAction,
markNotificationAsReadAction,
} from "../actions"
import type { Notification, NotificationType } from "@/modules/notifications/types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
announcement: Megaphone,
homework: PenTool,
grade: GraduationCap,
}
export function NotificationDropdown() {
const t = useTranslations("messages")
const router = useRouter()
const [notifications, setNotifications] = useState<Notification[]>([])
const [unreadCount, setUnreadCount] = useState(0)
const [open, setOpen] = useState(false)
useEffect(() => {
let active = true
const fetchNotifications = async () => {
const res = await getNotificationsAction({ pageSize: 10 })
if (!active) return
if (res.success && res.data) {
setNotifications(res.data.items)
}
}
const fetchUnreadCount = async () => {
const res = await getUnreadNotificationCountAction()
if (!active) return
if (res.success && typeof res.data === "number") {
setUnreadCount(res.data)
}
}
void fetchNotifications()
void fetchUnreadCount()
// 每 30 秒轮询刷新通知和未读计数
const timer = setInterval(() => {
void fetchNotifications()
void fetchUnreadCount()
}, 30_000)
return () => {
active = false
clearInterval(timer)
}
}, [])
const handleMarkAllRead = async () => {
const res = await markAllNotificationsAsReadAction()
if (res.success) {
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })))
setUnreadCount(0)
router.refresh()
}
}
const handleMarkRead = async (id: string) => {
const res = await markNotificationAsReadAction(id)
if (res.success) {
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
)
setUnreadCount((c) => Math.max(0, c - 1))
router.refresh()
}
}
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.notifications")}>
<Bell className="size-5" aria-hidden="true" />
{unreadCount > 0 ? (
<Badge
variant="destructive"
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center px-1 text-[10px]"
>
{unreadCount > 9 ? "9+" : unreadCount}
</Badge>
) : null}
<span className="sr-only">{t("title.notifications")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-0">
<DropdownMenuLabel className="flex items-center justify-between">
<span>{t("title.notifications")}</span>
{unreadCount > 0 ? (
<button
type="button"
onClick={handleMarkAllRead}
className="text-primary text-xs hover:underline"
>
<CheckCheck className="mr-1 inline h-3 w-3" aria-hidden="true" />
{t("actions.markAllRead")}
</button>
) : null}
</DropdownMenuLabel>
<DropdownMenuSeparator className="mb-0" />
<ScrollArea className="max-h-[320px]">
{notifications.length === 0 ? (
<div className="text-muted-foreground px-4 py-8 text-center text-sm">
{t("empty.noNotificationsDropdown")}
</div>
) : (
notifications.map((n) => {
const Icon = TYPE_ICON[n.type] ?? Bell
return (
<DropdownMenuItem
key={n.id}
className="flex items-start gap-2 py-3"
onSelect={(e) => {
if (!n.isRead) {
e.preventDefault()
handleMarkRead(n.id)
}
}}
>
<div className="bg-muted mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full">
<Icon className="h-3.5 w-3.5" aria-hidden="true" />
</div>
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex items-center gap-1.5">
{!n.isRead ? (
<span className="bg-primary size-1.5 shrink-0 rounded-full" aria-hidden="true" />
) : null}
<span className={cn("text-xs", !n.isRead ? "font-semibold" : "font-medium")}>
{n.title}
</span>
</div>
{n.content ? (
<p className="text-muted-foreground line-clamp-2 text-xs">{n.content}</p>
) : null}
<span className="text-muted-foreground text-[10px]">
{formatDate(n.createdAt)}
</span>
</div>
</DropdownMenuItem>
)
})
)}
</ScrollArea>
<DropdownMenuSeparator className="mt-0" />
<DropdownMenuItem asChild>
<Link href="/messages" className="text-primary justify-center text-xs">
{t("actions.viewAll")}
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}

View File

@@ -1,137 +0,0 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn, formatDate } from "@/shared/lib/utils"
import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions"
import type { Notification, NotificationType } from "@/modules/notifications/types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
announcement: Megaphone,
homework: PenTool,
grade: GraduationCap,
}
export function NotificationList({ notifications }: { notifications: Notification[] }) {
const t = useTranslations("messages")
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const hasUnread = notifications.some((n) => !n.isRead)
const handleMarkAllRead = async () => {
setIsWorking(true)
try {
const res = await markAllNotificationsAsReadAction()
if (res.success) {
toast.success(res.message)
router.refresh()
} else {
toast.error(res.message || t("messages.markReadFailed"))
}
} catch {
toast.error(t("messages.markReadFailed"))
} finally {
setIsWorking(false)
}
}
const handleMarkRead = async (id: string) => {
try {
const res = await markNotificationAsReadAction(id)
if (res.success) {
router.refresh()
}
} catch {
toast.error(t("messages.markReadFailed"))
}
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-2xl font-bold tracking-tight">{t("title.notifications")}</h2>
<p className="text-muted-foreground text-sm">{t("description.notifications")}</p>
</div>
{hasUnread ? (
<Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
<CheckCheck className="mr-2 h-4 w-4" />
{t("actions.markAllRead")}
</Button>
) : null}
</div>
{notifications.length === 0 ? (
<EmptyState
title={t("empty.noNotifications")}
description={t("empty.noNotificationsDesc")}
icon={Bell}
className="h-auto border-none shadow-none"
/>
) : (
<div className="space-y-3">
{notifications.map((n) => {
const Icon = TYPE_ICON[n.type] ?? Bell
return (
<Card
key={n.id}
className={cn("transition-colors", !n.isRead && "border-primary/40 bg-primary/5")}
>
<CardContent className="flex items-start gap-3 py-4">
<div className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
<Icon className="h-4 w-4" aria-hidden="true" />
</div>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className={cn("text-sm", !n.isRead ? "font-semibold" : "font-medium")}>
{n.title}
</span>
{!n.isRead ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
</div>
{n.content ? (
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{n.content}
</p>
) : null}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Badge variant="outline" className="text-xs">
{t(`notificationType.${n.type}`)}
</Badge>
<span>{formatDate(n.createdAt)}</span>
{!n.isRead ? (
<button
type="button"
onClick={() => handleMarkRead(n.id)}
className="text-primary hover:underline"
aria-label={t("actions.markRead")}
>
{t("actions.markRead")}
</button>
) : null}
{n.link ? (
<Link href={n.link} className="ml-auto text-primary hover:underline">
{t("actions.view")}
</Link>
) : null}
</div>
</div>
</CardContent>
</Card>
)
})}
</div>
)}
</div>
)
}

View File

@@ -6,11 +6,14 @@ import { Badge } from "@/shared/components/ui/badge"
import { getUnreadMessageCountAction } from "../actions"
/** 未读消息计数轮询间隔(毫秒) */
const POLL_INTERVAL_MS = 60_000
/**
* 未读消息计数徽章
*
* 在侧边栏 Messages 导航项旁显示未读私信数。
* 每 60 秒轮询一次以保持计数更新。
* 每 POLL_INTERVAL_MS 毫秒轮询一次以保持计数更新。
*/
export function UnreadMessageBadge() {
const [count, setCount] = useState(0)
@@ -30,7 +33,7 @@ export function UnreadMessageBadge() {
const timer = setInterval(() => {
void fetchCount()
}, 60_000)
}, POLL_INTERVAL_MS)
return () => {
active = false

View File

@@ -180,14 +180,17 @@ export async function markMessageAsRead(id: string, userId: string): Promise<voi
export async function deleteMessage(id: string, userId: string): Promise<void> {
const now = new Date()
// 软删除:发送方删除设置 senderDeletedAt接收方删除设置 receiverDeletedAt互不影响
await db
.update(messages)
.set({ senderDeletedAt: now })
.where(and(eq(messages.id, id), eq(messages.senderId, userId)))
await db
.update(messages)
.set({ receiverDeletedAt: now })
.where(and(eq(messages.id, id), eq(messages.receiverId, userId)))
// 使用事务保证两次 UPDATE 的原子性,避免部分失败导致数据不一致
await db.transaction(async (tx) => {
await tx
.update(messages)
.set({ senderDeletedAt: now })
.where(and(eq(messages.id, id), eq(messages.senderId, userId)))
await tx
.update(messages)
.set({ receiverDeletedAt: now })
.where(and(eq(messages.id, id), eq(messages.receiverId, userId)))
})
}
export const getUnreadMessageCount = cache(async (userId: string): Promise<number> => {
@@ -244,3 +247,44 @@ export const getRecipients = cache(
return []
}
)
/**
* 消息首页编排函数:一次性获取消息列表和通知列表。
* 将原本散落在 page.tsx 中的多模块编排逻辑下沉到 data-access 层,
* 页面层只需调用单一函数,提升可复用性与可测试性。
*/
export async function getMessagesPageData(userId: string): Promise<{
messages: { items: Message[]; total: number; page: number; pageSize: number; totalPages: number }
notifications: { items: import("@/modules/notifications/types").Notification[]; total: number; page: number; pageSize: number; totalPages: number }
}> {
const { getNotifications } = await import("@/modules/notifications/data-access")
const [messagesResult, notificationsResult] = await Promise.all([
getMessages({ userId, type: "all", page: 1, pageSize: 50 }),
getNotifications(userId, { page: 1, pageSize: 20 }),
])
return {
messages: messagesResult,
notifications: notificationsResult,
}
}
/**
* 消息详情页编排函数:获取消息详情,并自动标记为已读(若当前用户为接收方且未读)。
* 使用 next/server 的 after() 实现非阻塞标记,避免阻塞页面渲染。
*/
export async function getMessageDetailPageData(
id: string,
userId: string
): Promise<Message | null> {
const message = await getMessageById(id, userId)
if (!message) return null
// 自动标记已读:仅当当前用户为接收方且消息未读时
if (!message.isRead && message.receiverId === userId) {
await markMessageAsRead(id, userId)
}
return message
}

View File

@@ -0,0 +1,106 @@
"use client"
import { useEffect, useRef, useState } from "react"
import type { ActionState } from "@/shared/types/action-state"
import type { Message, MessageType } from "../types"
type SearchMessagesResult = ActionState<{
items: Message[]
total: number
page: number
pageSize: number
totalPages: number
}>
interface UseMessageSearchParams {
/** 搜索动作(注入的接口,避免组件直接依赖具体 action */
searchAction: (params: {
type: MessageType
keyword: string
page?: number
pageSize?: number
}) => Promise<SearchMessagesResult>
/** 当前标签页 */
tab: "inbox" | "sent"
/** 防抖延迟(毫秒),默认 400 */
debounceMs?: number
}
interface UseMessageSearchResult {
keyword: string
setKeyword: (v: string) => void
results: Message[] | null
searching: boolean
/** 当前 keyword 为空时为 true表示应使用 prop 传入的初始消息 */
isUsingInitial: boolean
}
/**
* 消息搜索 hook将搜索逻辑从 MessageList 组件抽离为独立 hook
* 提升可测试性与可复用性。支持防抖、请求取消、状态匹配。
*
* 使用方式:
* const { keyword, setKeyword, results, searching } = useMessageSearch({
* searchAction: getMessagesAction,
* tab,
* })
*/
export function useMessageSearch({
searchAction,
tab,
debounceMs = 400,
}: UseMessageSearchParams): UseMessageSearchResult {
const [keyword, setKeyword] = useState("")
const [results, setResults] = useState<Message[] | null>(null)
const [searching, setSearching] = useState(false)
const requestIdRef = useRef(0)
useEffect(() => {
const kw = keyword.trim()
if (kw.length === 0) {
setResults(null)
setSearching(false)
return
}
setSearching(true)
const currentRequestId = ++requestIdRef.current
const timer = setTimeout(async () => {
// 在异步执行前检查是否已被后续请求取代
if (currentRequestId !== requestIdRef.current) return
try {
const res = await searchAction({ type: tab, keyword: kw })
// 请求返回后再次检查,避免竞态
if (currentRequestId !== requestIdRef.current) return
if (res.success && res.data) {
setResults(res.data.items)
} else {
setResults([])
}
} catch {
if (currentRequestId !== requestIdRef.current) return
setResults([])
} finally {
if (currentRequestId === requestIdRef.current) {
setSearching(false)
}
}
}, debounceMs)
return () => {
clearTimeout(timer)
}
}, [keyword, tab, searchAction, debounceMs])
const isUsingInitial = keyword.trim().length === 0
return {
keyword,
setKeyword,
results,
searching,
isUsingInitial,
}
}