feat(dashboard): 仪表盘模块审计重构 — 权限校验 + i18n + 逻辑抽离

基于 dashboard-audit-report.md 审计结论,对仪表盘模块进行 P0/P1 级修复:

- 新增 4 个 dashboard 权限点(DASHBOARD_ADMIN/TEACHER/STUDENT/PARENT_READ),补充到 permissions.ts 和角色-权限映射

- 新建 actions.ts:4 个 Server Action 均调用 requirePermission() 校验权限,消除 admin 页面零鉴权、teacher/student/parent 仅 requireAuth 的安全隐患

- 根重定向页 /dashboard 改用 resolvePermissions() + 权限点判断,不再 role === xxx 硬编码

- 新建 lib/dashboard-utils.ts:抽取 toWeekday / countStudentAssignments / sortUpcomingAssignments / filterTodaySchedule / computeTeacherMetrics / getGreetingKey 纯函数,与 UI 分离,便于单测

- 新建 messages/{zh-CN,en}/dashboard.json 翻译文件,i18n request.ts 加载 dashboard 命名空间;所有视图组件接入 useTranslations / getTranslations,消除中英混杂硬编码

- 重构 4 个角色 page.tsx:通过 actions 获取数据,generateMetadata 使用 i18n

- 同步更新架构图 004 / 005 文档(dashboard exports / permissions / 文件清单)
This commit is contained in:
SpecialX
2026-06-22 15:50:56 +08:00
parent 2548f70f40
commit 868ac5f9cf
28 changed files with 1507 additions and 399 deletions

View File

@@ -1,17 +1,21 @@
import type { Metadata } from "next"
import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { AdminDashboardView } from "@/modules/dashboard/components/admin-dashboard/admin-dashboard"
import { getAdminDashboardData } from "@/modules/dashboard/data-access"
export const metadata: Metadata = {
title: "管理控制台 - Next_Edu",
description: "系统管理总览",
}
import { getAdminDashboardAction } from "@/modules/dashboard/actions"
export const dynamic = "force-dynamic"
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("dashboard")
return {
title: t("title.admin"),
description: t("description.admin"),
}
}
export default async function AdminDashboardPage(): Promise<JSX.Element> {
const data = await getAdminDashboardData()
const data = await getAdminDashboardAction()
return <AdminDashboardView data={data} />
}

View File

@@ -1,18 +1,20 @@
"use client"
import { AlertCircle } from "lucide-react"
import { useTranslations } from "next-intl"
import { EmptyState } from "@/shared/components/ui/empty-state"
export default function DashboardError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
const t = useTranslations("dashboard")
return (
<div className="flex h-full flex-col items-center justify-center space-y-4 p-8">
<EmptyState
icon={AlertCircle}
title="页面加载失败"
description="抱歉,页面加载时发生了意外错误。请稍后重试。"
title={t("error.loadFailed")}
description={t("error.loadFailedDesc")}
action={{
label: "重试",
label: t("error.retry"),
onClick: () => reset(),
}}
className="border-none shadow-none h-auto"

View File

@@ -1,16 +1,28 @@
import { redirect } from "next/navigation"
import { auth } from "@/auth"
import { Permissions } from "@/shared/types/permissions"
import { resolvePermissions } from "@/shared/lib/permissions"
import { isRole } from "@/shared/types/permissions"
export const dynamic = "force-dynamic"
export default async function DashboardPage() {
export default async function DashboardPage(): Promise<void> {
const session = await auth()
if (!session?.user) redirect("/login")
const roles = session.user.roles ?? []
const roles = (session.user.roles ?? []).filter(isRole)
const permissions = resolvePermissions(roles)
if (roles.includes("admin")) redirect("/admin/dashboard")
if (roles.includes("student")) redirect("/student/dashboard")
if (roles.includes("parent")) redirect("/parent/dashboard")
// 按优先级匹配仪表盘权限admin > student > parent > teacher
if (permissions.includes(Permissions.DASHBOARD_ADMIN_READ)) {
redirect("/admin/dashboard")
}
if (permissions.includes(Permissions.DASHBOARD_STUDENT_READ)) {
redirect("/student/dashboard")
}
if (permissions.includes(Permissions.DASHBOARD_PARENT_READ)) {
redirect("/parent/dashboard")
}
redirect("/teacher/dashboard")
}

View File

@@ -1,18 +1,20 @@
"use client"
import { AlertCircle } from "lucide-react"
import { useTranslations } from "next-intl"
import { EmptyState } from "@/shared/components/ui/empty-state"
export default function ParentDashboardError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
const t = useTranslations("dashboard")
return (
<div className="flex h-full flex-col items-center justify-center space-y-4 p-8">
<EmptyState
icon={AlertCircle}
title="页面加载失败"
description="抱歉,页面加载时发生了意外错误。请稍后重试。"
title={t("error.loadFailed")}
description={t("error.loadFailedDesc")}
action={{
label: "重试",
label: t("error.retry"),
onClick: () => reset(),
}}
className="border-none shadow-none h-auto"

View File

@@ -1,36 +1,40 @@
import { requireAuth } from "@/shared/lib/auth-guard"
import { getParentDashboardData } from "@/modules/parent/data-access"
import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { getParentDashboardAction } from "@/modules/dashboard/actions"
import { ParentDashboard } from "@/modules/parent/components/parent-dashboard"
import { ParentNoChildrenPage } from "@/modules/parent/components/parent-children-data-page"
import { Users } from "lucide-react"
export const dynamic = "force-dynamic"
export const metadata = { title: "Dashboard - Next_Edu" }
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("dashboard")
return {
title: t("title.parent"),
description: t("description.parent"),
}
}
export default async function ParentDashboardPage() {
const ctx = await requireAuth()
export default async function ParentDashboardPage(): Promise<JSX.Element> {
const t = await getTranslations("dashboard")
const { data, hasChildren } = await getParentDashboardAction()
// 非 admin 且 dataScope 非 children 类型时,显示空状态
if (
ctx.dataScope.type !== "all" &&
!(ctx.dataScope.type === "children" && ctx.dataScope.childrenIds.length > 0)
) {
if (!data || !hasChildren) {
return (
<div className="p-6 md:p-8">
<ParentNoChildrenPage
title="Parent Dashboard"
description="Here's an overview of your children."
title={t("title.parent")}
description={t("description.parent")}
icon={Users}
emptyTitle="No children linked"
emptyDescription="Your account is not linked to any student accounts yet. Please contact the school administrator."
emptyTitle={t("empty.noChildren")}
emptyDescription={t("empty.noChildrenDesc")}
/>
</div>
)
}
const data = await getParentDashboardData(ctx.userId)
return (
<div className="p-6 md:p-8">
<ParentDashboard data={data} />

View File

@@ -1,101 +1,42 @@
import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { StudentDashboard } from "@/modules/dashboard/components/student-dashboard/student-dashboard-view"
import { getStudentClasses, getStudentSchedule } from "@/modules/classes/data-access"
import { getStudentDashboardGrades, getStudentHomeworkAssignments } from "@/modules/homework/data-access"
import { getCurrentStudentUser } from "@/modules/users/data-access"
import { getStudentDashboardAction } from "@/modules/dashboard/actions"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { UserX } from "lucide-react"
import type { StudentHomeworkProgressStatus } from "@/modules/homework/types"
export const dynamic = "force-dynamic"
export const metadata = { title: "Dashboard - Next_Edu" }
const toWeekday = (d: Date): 1 | 2 | 3 | 4 | 5 | 6 | 7 => {
// getDay() 返回 0(周日)-6(周六),转换为 1-7周一为 1
const WEEKDAY_MAP = [7, 1, 2, 3, 4, 5, 6] as const
const day = d.getDay()
if (day < 0 || day > 6) {
throw new Error(`Invalid day from getDay(): ${day}`)
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("dashboard")
return {
title: t("title.student"),
description: t("description.student"),
}
return WEEKDAY_MAP[day]
}
export default async function StudentDashboardPage() {
const student = await getCurrentStudentUser()
if (!student) {
export default async function StudentDashboardPage(): Promise<JSX.Element> {
const t = await getTranslations("dashboard")
const { student, dashboardProps } = await getStudentDashboardAction()
if (!student || !dashboardProps) {
return (
<EmptyState
title="No user found"
description="Create a student user to see dashboard."
title={t("empty.noStudent")}
description={t("empty.noStudentDesc")}
icon={UserX}
className="border-none shadow-none h-auto"
/>
)
}
const [classes, schedule, assignments, grades] = await Promise.all([
getStudentClasses(student.id),
getStudentSchedule(student.id),
getStudentHomeworkAssignments(student.id),
getStudentDashboardGrades(student.id),
])
const now = new Date()
const in7Days = new Date(now)
in7Days.setDate(in7Days.getDate() + 7)
// 单次遍历统计,避免重复 filterPERF-04
let dueSoonCount = 0
let overdueCount = 0
let gradedCount = 0
for (const a of assignments) {
const status: StudentHomeworkProgressStatus = a.progressStatus
if (status === "graded") {
gradedCount++
continue
}
if (!a.dueAt) continue
const due = new Date(a.dueAt)
if (due >= now && due <= in7Days) {
dueSoonCount++
} else if (due < now) {
overdueCount++
}
}
const todayWeekday = toWeekday(now)
const todayScheduleItems = schedule
.filter((s) => s.weekday === todayWeekday)
.map((s) => ({
id: s.id,
classId: s.classId,
className: s.className,
course: s.course,
startTime: s.startTime,
endTime: s.endTime,
location: s.location ?? null,
}))
.sort((a, b) => a.startTime.localeCompare(b.startTime))
const upcomingAssignments = [...assignments]
.sort((a, b) => {
const aDue = a.dueAt ? new Date(a.dueAt).getTime() : Number.POSITIVE_INFINITY
const bDue = b.dueAt ? new Date(b.dueAt).getTime() : Number.POSITIVE_INFINITY
return aDue - bDue
})
.slice(0, 6)
return (
<div className="space-y-8">
<StudentDashboard
studentName={student.name}
enrolledClassCount={classes.length}
dueSoonCount={dueSoonCount}
overdueCount={overdueCount}
gradedCount={gradedCount}
todayScheduleItems={todayScheduleItems}
upcomingAssignments={upcomingAssignments}
grades={grades}
{...dashboardProps}
/>
</div>
)

View File

@@ -1,18 +1,20 @@
"use client"
import { AlertCircle } from "lucide-react"
import { useTranslations } from "next-intl"
import { EmptyState } from "@/shared/components/ui/empty-state"
export default function TeacherDashboardError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
const t = useTranslations("dashboard")
return (
<div className="flex h-full flex-col items-center justify-center space-y-4 p-8">
<EmptyState
icon={AlertCircle}
title="页面加载失败"
description="抱歉,页面加载时发生了意外错误。请稍后重试。"
title={t("error.loadFailed")}
description={t("error.loadFailedDesc")}
action={{
label: "重试",
label: t("error.retry"),
onClick: () => reset(),
}}
className="border-none shadow-none h-auto"

View File

@@ -1,37 +1,21 @@
import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { TeacherDashboardView } from "@/modules/dashboard/components/teacher-dashboard/teacher-dashboard-view"
import { getClassSchedule, getTeacherClasses, getTeacherIdForMutations } from "@/modules/classes/data-access"
import { getHomeworkAssignments, getHomeworkSubmissions, getTeacherGradeTrends } from "@/modules/homework/data-access"
import { getUserBasicInfo } from "@/modules/users/data-access"
import { getAuthContext } from "@/shared/lib/auth-guard"
import { getTeacherDashboardAction } from "@/modules/dashboard/actions"
export const dynamic = "force-dynamic"
export const metadata = { title: "Dashboard - Next_Edu" }
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("dashboard")
return {
title: t("title.teacher"),
description: t("description.teacher"),
}
}
export default async function TeacherDashboardPage(): Promise<JSX.Element> {
await getAuthContext()
const teacherId = await getTeacherIdForMutations()
const [classes, schedule, assignments, submissions, teacherProfile, gradeTrends] = await Promise.all([
getTeacherClasses({ teacherId }),
getClassSchedule({ teacherId }),
getHomeworkAssignments({ creatorId: teacherId }),
getHomeworkSubmissions({ creatorId: teacherId }),
getUserBasicInfo(teacherId),
getTeacherGradeTrends(teacherId),
])
return (
<TeacherDashboardView
data={{
classes,
schedule,
assignments,
submissions,
teacherName: teacherProfile?.name ?? "Teacher",
gradeTrends,
}}
/>
)
const data = await getTeacherDashboardAction()
return <TeacherDashboardView data={data} />
}