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

@@ -2,8 +2,10 @@
import { revalidatePath } from "next/cache"
import { createId } from "@paralleldrive/cuid2"
import { getTranslations } from "next-intl/server"
import { requirePermission, PermissionDeniedError } 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 { sendBatchNotifications } from "@/modules/notifications"
@@ -69,10 +71,14 @@ async function notifyAnnouncementPublished(announcement: Announcement): Promise<
const targetUserIds = await resolveTargetUserIds(announcement)
if (targetUserIds.length === 0) return
const t = await getTranslations("announcements")
const title = t("notification.publishedTitle", { title: announcement.title })
const content = t("notification.publishedContent")
const payloads: NotificationPayload[] = targetUserIds.map((userId) => ({
userId,
title: `新公告:${announcement.title}`,
content: announcement.content.slice(0, 200),
title,
content,
type: "info",
actionUrl: `/announcements/${announcement.id}`,
metadata: {
@@ -146,6 +152,14 @@ export async function createAnnouncementAction(
revalidatePath("/admin/announcements")
revalidatePath("/announcements")
void trackEvent({
event: isPublished ? "announcement.published" : "announcement.created",
userId: ctx.userId,
targetId: id,
targetType: "announcement",
properties: { type: input.type, status: input.status },
})
return { success: true, message: "Announcement created", data: id }
} catch (e) {
return handleActionError(e)
@@ -215,6 +229,13 @@ export async function updateAnnouncementAction(
revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements")
void trackEvent({
event: isPublished && !wasPublished ? "announcement.published" : "announcement.updated",
targetId: id,
targetType: "announcement",
properties: { type: input.type, status: input.status, wasPublished },
})
return { success: true, message: "Announcement updated", data: id }
} catch (e) {
return handleActionError(e)
@@ -233,6 +254,13 @@ export async function deleteAnnouncementAction(id: string): Promise<ActionState<
revalidatePath("/admin/announcements")
revalidatePath("/announcements")
void trackEvent({
event: "announcement.deleted",
targetId: id,
targetType: "announcement",
properties: { type: existing.type, status: existing.status },
})
return { success: true, message: "Announcement deleted" }
} catch (e) {
return handleActionError(e)
@@ -258,6 +286,13 @@ export async function publishAnnouncementAction(id: string): Promise<ActionState
revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements")
void trackEvent({
event: "announcement.published",
targetId: id,
targetType: "announcement",
properties: { type: existing.type },
})
return { success: true, message: "Announcement published" }
} catch (e) {
return handleActionError(e)
@@ -277,6 +312,13 @@ export async function archiveAnnouncementAction(id: string): Promise<ActionState
revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements")
void trackEvent({
event: "announcement.archived",
targetId: id,
targetType: "announcement",
properties: { type: existing.type },
})
return { success: true, message: "Announcement archived" }
} catch (e) {
return handleActionError(e)

View File

@@ -23,6 +23,8 @@ import type { Announcement } from "../types"
type Mode = "create" | "edit"
type FieldErrors = Record<string, string[]>
export function AnnouncementForm({
mode,
announcement,
@@ -37,14 +39,21 @@ export function AnnouncementForm({
const t = useTranslations("announcements")
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})
const [type, setType] = useState<string>(announcement?.type ?? "school")
const [status, setStatus] = useState<string>(announcement?.status ?? "draft")
const [targetGradeId, setTargetGradeId] = useState<string>(announcement?.targetGradeId ?? "")
const [targetClassId, setTargetClassId] = useState<string>(announcement?.targetClassId ?? "")
const getFieldError = (field: string): string | null => {
const errs = fieldErrors[field]
return errs && errs.length > 0 ? errs[0] : null
}
const handleSubmit = async (formData: FormData) => {
setIsWorking(true)
setFieldErrors({})
try {
formData.set("type", type)
formData.set("status", status)
@@ -72,6 +81,10 @@ export function AnnouncementForm({
router.push("/admin/announcements")
router.refresh()
} else {
// 展示字段级错误(来自 Zod superRefine 校验)
if (res.errors) {
setFieldErrors(res.errors)
}
toast.error(res.message || t("messages.updateFailed"))
}
} catch {
@@ -98,7 +111,11 @@ export function AnnouncementForm({
placeholder={t("form.titlePlaceholder")}
defaultValue={announcement?.title ?? ""}
required
aria-invalid={!!getFieldError("title")}
/>
{getFieldError("title") ? (
<p className="text-destructive text-xs">{getFieldError("title")}</p>
) : null}
</div>
<div className="grid gap-2">
@@ -110,7 +127,11 @@ export function AnnouncementForm({
className="min-h-[160px]"
defaultValue={announcement?.content ?? ""}
required
aria-invalid={!!getFieldError("content")}
/>
{getFieldError("content") ? (
<p className="text-destructive text-xs">{getFieldError("content")}</p>
) : null}
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
@@ -148,7 +169,7 @@ export function AnnouncementForm({
<div className="grid gap-2 md:col-span-2">
<Label>{t("form.targetGrade")}</Label>
<Select value={targetGradeId} onValueChange={setTargetGradeId}>
<SelectTrigger>
<SelectTrigger aria-invalid={!!getFieldError("targetGradeId")}>
<SelectValue placeholder={t("form.targetGradePlaceholder")} />
</SelectTrigger>
<SelectContent>
@@ -160,6 +181,9 @@ export function AnnouncementForm({
</SelectContent>
</Select>
<input type="hidden" name="targetGradeId" value={targetGradeId} />
{getFieldError("targetGradeId") ? (
<p className="text-destructive text-xs">{getFieldError("targetGradeId")}</p>
) : null}
</div>
) : null}
@@ -167,7 +191,7 @@ export function AnnouncementForm({
<div className="grid gap-2 md:col-span-2">
<Label>{t("form.targetClass")}</Label>
<Select value={targetClassId} onValueChange={setTargetClassId}>
<SelectTrigger>
<SelectTrigger aria-invalid={!!getFieldError("targetClassId")}>
<SelectValue placeholder={t("form.targetClassPlaceholder")} />
</SelectTrigger>
<SelectContent>
@@ -179,6 +203,9 @@ export function AnnouncementForm({
</SelectContent>
</Select>
<input type="hidden" name="targetClassId" value={targetClassId} />
{getFieldError("targetClassId") ? (
<p className="text-destructive text-xs">{getFieldError("targetClassId")}</p>
) : null}
</div>
) : null}
</div>

View File

@@ -1,6 +1,5 @@
"use client"
import { useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { Plus, Megaphone } from "lucide-react"
@@ -21,6 +20,14 @@ import type { Announcement, AnnouncementStatus } from "../types"
type Filter = "all" | AnnouncementStatus
/**
* 公告列表组件。
*
* 过滤模式:纯服务端过滤。
* - Select 切换时更新 URL `?status=`,触发 RSC 重新渲染
* - 父页面根据 `?status=` 查询并传入 `announcements` prop
* - 组件不再做客户端二次过滤,避免双重过滤逻辑冗余
*/
export function AnnouncementList({
announcements,
canManage,
@@ -36,7 +43,7 @@ export function AnnouncementList({
}) {
const t = useTranslations("announcements")
const router = useRouter()
const [filter, setFilter] = useState<Filter>(initialStatus ?? "all")
const filter: Filter = initialStatus ?? "all"
const filterOptions: { value: Filter; label: string }[] = [
{ value: "all", label: t("filter.all") },
@@ -45,13 +52,7 @@ export function AnnouncementList({
{ value: "archived", label: t("filter.archived") },
]
const filtered = useMemo(() => {
if (filter === "all") return announcements
return announcements.filter((a) => a.status === filter)
}, [announcements, filter])
const handleFilterChange = (value: string) => {
setFilter(value as Filter)
const handleFilterChange = (value: string): void => {
const params = new URLSearchParams()
if (value !== "all") params.set("status", value)
const qs = params.toString()
@@ -83,11 +84,11 @@ export function AnnouncementList({
) : null}
</div>
{filtered.length === 0 ? (
{announcements.length === 0 ? (
<EmptyState
title={t("empty.noAnnouncements")}
description={
announcements.length === 0
filter === "all"
? t("empty.noAnnouncementsDesc")
: t("empty.noMatch")
}
@@ -96,7 +97,7 @@ export function AnnouncementList({
/>
) : (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{filtered.map((a) => (
{announcements.map((a) => (
<AnnouncementCard
key={a.id}
announcement={a}

View File

@@ -8,6 +8,7 @@ import { announcements, users } from "@/shared/db/schema"
import type {
Announcement,
AnnouncementInsertData,
AnnouncementStatus,
AnnouncementUpdateData,
GetAnnouncementsParams,
} from "./types"
@@ -195,3 +196,49 @@ export async function archiveAnnouncementById(id: string): Promise<void> {
})
.where(eq(announcements.id, id))
}
/**
* 管理端公告列表页编排函数:一次性获取公告列表、年级列表、班级列表。
* 将原本散落在 page.tsx 中的多模块编排逻辑下沉到 data-access 层,
* 页面层只需调用单一函数,提升可复用性与可测试性。
*/
export async function getAdminAnnouncementsPageData(status?: AnnouncementStatus): Promise<{
announcements: Announcement[]
grades: { id: string; name: string }[]
classes: { id: string; name: string }[]
}> {
const { getGrades } = await import("@/modules/school/data-access")
const { getAdminClasses } = await import("@/modules/classes/data-access")
const [announcementList, gradeList, classList] = await Promise.all([
getAnnouncements({ status }),
getGrades(),
getAdminClasses(),
])
return {
announcements: announcementList,
grades: gradeList.map((g) => ({ id: g.id, name: g.name })),
classes: classList.map((c) => ({ id: c.id, name: c.name })),
}
}
/**
* 管理端公告编辑页编排函数:一次性获取公告详情和年级列表。
*/
export async function getEditAnnouncementPageData(id: string): Promise<{
announcement: Announcement | null
grades: { id: string; name: string }[]
}> {
const { getGrades } = await import("@/modules/school/data-access")
const [announcement, gradeList] = await Promise.all([
getAnnouncementById(id),
getGrades(),
])
return {
announcement,
grades: gradeList.map((g) => ({ id: g.id, name: g.name })),
}
}

View File

@@ -1,5 +1,53 @@
import { z } from "zod"
/**
* 公告类型与目标受众的联合校验:
* - type=schooltargetGradeId / targetClassId 必须为空
* - type=gradetargetGradeId 必填targetClassId 必须为空
* - type=classtargetClassId 必填
*
* 避免"创建无受众公告"的数据完整性问题。
*/
const refineAudience = (
data: {
type?: "school" | "grade" | "class"
targetGradeId?: string | null
targetClassId?: string | null
},
ctx: z.RefinementCtx
): void => {
const type = data.type ?? "school"
const hasGrade = (data.targetGradeId ?? "").trim().length > 0
const hasClass = (data.targetClassId ?? "").trim().length > 0
if (type === "school" && (hasGrade || hasClass)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetGradeId"],
message: "全校公告不应指定目标年级或班级",
})
return
}
if (type === "grade" && !hasGrade) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetGradeId"],
message: "年级公告必须指定目标年级",
})
return
}
if (type === "class" && !hasClass) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetClassId"],
message: "班级公告必须指定目标班级",
})
return
}
}
export const CreateAnnouncementSchema = z
.object({
title: z.string().trim().min(1).max(255),
@@ -10,6 +58,7 @@ export const CreateAnnouncementSchema = z
targetClassId: z.string().trim().optional().nullable(),
publishedAt: z.string().optional().nullable(),
})
.superRefine(refineAudience)
.transform((v) => ({
title: v.title,
content: v.content,
@@ -32,6 +81,7 @@ export const UpdateAnnouncementSchema = z
targetClassId: z.string().trim().optional().nullable(),
publishedAt: z.string().optional().nullable(),
})
.superRefine(refineAudience)
.transform((v) => ({
title: v.title,
content: v.content,

View File

@@ -36,6 +36,26 @@ export type NavItem = {
items?: { title: string; href: string; permission?: Permission }[]
}
/**
* 公共导航项:所有已登录用户均可访问的功能模块。
* 通过权限点permission控制可见性新增角色只需在 NAV_CONFIG 中引用这些公共项,
* 无需复制粘贴。符合"配置驱动设计"和"严禁 role === 'xxx' 硬编码"的规则。
*/
const COMMON_NAV_ITEMS: NavItem[] = [
{
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
]
export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
admin: [
{
@@ -118,12 +138,7 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
{ title: "Data Changes", href: "/admin/audit-logs/data-changes" },
]
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
...COMMON_NAV_ITEMS,
{
title: "Settings",
icon: Settings,
@@ -243,18 +258,85 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
{ title: "年级洞察", href: "/management/grade/insights" },
]
},
...COMMON_NAV_ITEMS,
],
grade_head: [
{
title: "公告",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
title: "仪表盘",
icon: LayoutDashboard,
href: "/management",
permission: Permissions.GRADE_MANAGE,
},
{
title: "消息",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
title: "年级管理",
icon: Briefcase,
href: "/management",
permission: Permissions.GRADE_MANAGE,
items: [
{ title: "年级班级", href: "/management/grade/classes" },
{ title: "年级洞察", href: "/management/grade/insights" },
]
},
{
title: "考勤",
icon: CalendarCheck,
href: "/teacher/attendance",
permission: Permissions.ATTENDANCE_READ,
items: [
{ title: "考勤记录", href: "/teacher/attendance" },
{ title: "考勤统计", href: "/teacher/attendance/stats", permission: Permissions.ATTENDANCE_READ },
]
},
{
title: "成绩",
icon: GraduationCap,
href: "/teacher/grades",
permission: Permissions.GRADE_RECORD_READ,
items: [
{ title: "成绩统计", href: "/teacher/grades/stats", permission: Permissions.GRADE_RECORD_READ },
{ title: "成绩分析", href: "/teacher/grades/analytics", permission: Permissions.GRADE_RECORD_READ },
]
},
...COMMON_NAV_ITEMS,
],
teaching_head: [
{
title: "仪表盘",
icon: LayoutDashboard,
href: "/management",
permission: Permissions.GRADE_MANAGE,
},
{
title: "年级管理",
icon: Briefcase,
href: "/management",
permission: Permissions.GRADE_MANAGE,
items: [
{ title: "年级班级", href: "/management/grade/classes" },
{ title: "年级洞察", href: "/management/grade/insights" },
]
},
{
title: "考勤",
icon: CalendarCheck,
href: "/teacher/attendance",
permission: Permissions.ATTENDANCE_READ,
items: [
{ title: "考勤记录", href: "/teacher/attendance" },
{ title: "考勤统计", href: "/teacher/attendance/stats", permission: Permissions.ATTENDANCE_READ },
]
},
{
title: "成绩",
icon: GraduationCap,
href: "/teacher/grades",
permission: Permissions.GRADE_RECORD_READ,
items: [
{ title: "成绩统计", href: "/teacher/grades/stats", permission: Permissions.GRADE_RECORD_READ },
{ title: "成绩分析", href: "/teacher/grades/analytics", permission: Permissions.GRADE_RECORD_READ },
]
},
...COMMON_NAV_ITEMS,
],
student: [
{
@@ -303,18 +385,7 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
href: "/student/elective",
permission: Permissions.ELECTIVE_SELECT,
},
{
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
...COMMON_NAV_ITEMS,
],
parent: [
{
@@ -339,17 +410,6 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
icon: CalendarRange,
href: "/parent/leave",
},
{
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
...COMMON_NAV_ITEMS,
]
}

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

@@ -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,
}
}

View File

@@ -5,21 +5,31 @@
*
* - sendNotificationAction: 发送通知给指定用户(需要 MESSAGE_SEND 权限)
* - sendClassNotificationAction: 发送班级通知(教师权限,按班级查询学生后批量发送)
* - getNotificationsAction / markNotificationAsReadAction / markAllNotificationsAsReadAction / getUnreadNotificationCountAction: 站内通知 CRUD
*
* 权限说明:
* 项目无独立 NOTIFICATION_SEND 权限点,复用 MESSAGE_SEND教师/管理员/年级主任均拥有)。
* 班级通知按教师所教班级过滤,确保教师只能给自己班级发通知。
* 站内通知读取/标记已读复用 MESSAGE_READ 权限(任何能读消息的用户都能查看通知)。
*/
import { revalidatePath } from "next/cache"
import { z } from "zod"
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 { getClassExists, getStudentIdsByClassId } from "@/modules/classes/data-access"
import { sendNotification, sendBatchNotifications } from "./dispatcher"
import type { NotificationPayload, ChannelSendResult } from "./types"
import {
getNotifications,
markNotificationAsRead,
markAllNotificationsAsRead,
getUnreadNotificationCount,
} from "./data-access"
import type { NotificationPayload, ChannelSendResult, Notification } from "./types"
/**
* Zod 校验通知负载sendNotificationAction 入参)
@@ -157,3 +167,101 @@ export async function sendClassNotificationAction(
return { success: false, message: "Unexpected error" }
}
}
// ---------------------------------------------------------------------------
// 站内通知 CRUD Server Actions
//
// 这些 Action 从 messaging/actions.ts 迁移而来,使 notifications 模块成为
// 通知相关 UI 组件的唯一数据来源,消除 messaging 与 notifications 在 UI 层
// 的双向耦合。权限复用 MESSAGE_READ任何能读消息的用户都能查看通知
// ---------------------------------------------------------------------------
/** Zod 校验:通知 ID 路径参数 */
const NotificationIdSchema = z.string().trim().min(1)
/**
* 获取当前用户的通知列表(分页)。
*/
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 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 markNotificationAsReadAction(
notificationId: string
): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const parsed = NotificationIdSchema.safeParse(notificationId)
if (!parsed.success) {
return { success: false, message: "Invalid notification id" }
}
await markNotificationAsRead(parsed.data, ctx.userId)
revalidatePath("/messages")
void trackEvent({
event: "notification.marked_read",
userId: ctx.userId,
targetId: parsed.data,
targetType: "notification",
})
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")
void trackEvent({
event: "notification.marked_all_read",
userId: ctx.userId,
targetType: "notification",
})
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" }
}
}

View File

@@ -0,0 +1,2 @@
export { NotificationList } from "./notification-list"
export { NotificationDropdown } from "./notification-dropdown"

View File

@@ -25,7 +25,7 @@ import {
markAllNotificationsAsReadAction,
markNotificationAsReadAction,
} from "../actions"
import type { Notification, NotificationType } from "@/modules/notifications/types"
import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
@@ -34,8 +34,11 @@ const TYPE_ICON: Record<NotificationType, typeof Bell> = {
grade: GraduationCap,
}
/** 通知下拉菜单轮询间隔(毫秒) */
const POLL_INTERVAL_MS = 30_000
export function NotificationDropdown() {
const t = useTranslations("messages")
const t = useTranslations("notifications")
const router = useRouter()
const [notifications, setNotifications] = useState<Notification[]>([])
const [unreadCount, setUnreadCount] = useState(0)
@@ -63,11 +66,11 @@ export function NotificationDropdown() {
void fetchNotifications()
void fetchUnreadCount()
// 每 30 秒轮询刷新通知和未读计数
// 每 POLL_INTERVAL_MS 毫秒轮询刷新通知和未读计数
const timer = setInterval(() => {
void fetchNotifications()
void fetchUnreadCount()
}, 30_000)
}, POLL_INTERVAL_MS)
return () => {
active = false
@@ -98,7 +101,7 @@ export function NotificationDropdown() {
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.notifications")}>
<Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.dropdown")}>
<Bell className="size-5" aria-hidden="true" />
{unreadCount > 0 ? (
<Badge
@@ -108,12 +111,12 @@ export function NotificationDropdown() {
{unreadCount > 9 ? "9+" : unreadCount}
</Badge>
) : null}
<span className="sr-only">{t("title.notifications")}</span>
<span className="sr-only">{t("title.dropdown")}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-0">
<DropdownMenuLabel className="flex items-center justify-between">
<span>{t("title.notifications")}</span>
<span>{t("title.dropdown")}</span>
{unreadCount > 0 ? (
<button
type="button"

View File

@@ -14,7 +14,7 @@ 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"
import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
@@ -24,7 +24,7 @@ const TYPE_ICON: Record<NotificationType, typeof Bell> = {
}
export function NotificationList({ notifications }: { notifications: Notification[] }) {
const t = useTranslations("messages")
const t = useTranslations("notifications")
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const hasUnread = notifications.some((n) => !n.isRead)
@@ -61,8 +61,8 @@ export function NotificationList({ notifications }: { notifications: Notificatio
<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>
<h2 className="text-2xl font-bold tracking-tight">{t("title.list")}</h2>
<p className="text-muted-foreground text-sm">{t("description.list")}</p>
</div>
{hasUnread ? (
<Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
@@ -106,7 +106,7 @@ export function NotificationList({ notifications }: { notifications: Notificatio
) : null}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Badge variant="outline" className="text-xs">
{t(`notificationType.${n.type}`)}
{t(`type.${n.type}`)}
</Badge>
<span>{formatDate(n.createdAt)}</span>
{!n.isRead ? (

View File

@@ -5,6 +5,8 @@
* - sendNotification / sendBatchNotifications: 分发器入口
* - createNotification / getNotifications / markNotificationAsRead / markAllNotificationsAsRead / getUnreadNotificationCount: 站内通知 CRUD
* - getNotificationPreferences / upsertNotificationPreferences: 通知偏好 CRUD
* - Server Actions: sendNotificationAction / sendClassNotificationAction / getNotificationsAction / markNotificationAsReadAction / markAllNotificationsAsReadAction / getUnreadNotificationCountAction
* - UI 组件: NotificationList / NotificationDropdown
* - 类型定义: NotificationPayload, ChannelSendResult, NotificationChannel, NotificationType, Notification, NotificationPreferences 等
* - 渠道发送器工厂: createSmsSender, createWechatSender, createEmailSender, createInAppSender
*
@@ -36,6 +38,15 @@ export {
getNotificationPreferences,
upsertNotificationPreferences,
} from "./preferences"
export {
sendNotificationAction,
sendClassNotificationAction,
getNotificationsAction,
getUnreadNotificationCountAction,
markNotificationAsReadAction,
markAllNotificationsAsReadAction,
} from "./actions"
export { NotificationList, NotificationDropdown } from "./components"
export type {
NotificationChannel,
NotificationPayload,