feat: 新增备课模块并修复全模块 P0/P1/P2 缺陷
Some checks failed
Security / deep-security-scan (push) Failing after 20m5s
DR Drill / dr-drill (push) Failing after 1m31s
CI / scheduled-backup (push) Failing after 1m31s
CI / backup-verify (push) Has been skipped
CI / weekly-dr-drill (push) Failing after 0s
CI / build-deploy (push) Has been cancelled
CI / security-scan (push) Has been cancelled

主要变更:

- 新增 lesson-preparation 模块: 备课编辑器、节点编辑、AI 建议、知识点选择、版本历史、作业发布

- 新增 shared 通用组件: charts/question-bank-filters/schedule-list/ui (chip-nav/filter-bar/page-header/stat-card/stat-item)

- 新增 student/admin 端 loading.tsx 与 error.tsx, 优化加载与错误态体验

- 新增 teacher/lesson-plans 页面 (列表/新建/编辑)

- 新增 drizzle 迁移 0002_tiny_lionheart 及 snapshot

- 新增 textbooks/schema.ts 与 exams/utils/normalize-structure.ts

- 修复 Tiptap v3 SSR hydration 崩溃 (rich-text-block immediatelyRender: false)

- 重构多模块 data-access/actions/组件, 修复权限校验与类型规范

- 同步架构文档 004/005 反映新增模块、导出、依赖关系

- 归档 bugs/* 测试报告与 e2e 测试脚本 (admin/parent/student/teacher web_test)
This commit is contained in:
SpecialX
2026-06-22 01:06:16 +08:00
parent d8962aba96
commit 978d9a8309
327 changed files with 34070 additions and 5642 deletions

View File

@@ -24,8 +24,8 @@ import {
import {
exportGradeRecordsToExcel,
exportClassGradeReportToExcel,
formatDateForFile,
} from "./export"
import { formatDateForFile } from "@/shared/lib/utils"
import type { GradeQueryParams, GradeRecordListItem, GradeStats } from "./types"
export async function createGradeRecordAction(

View File

@@ -0,0 +1,90 @@
import type { JSX } from "react"
import { ChipNav } from "@/shared/components/ui/chip-nav"
interface AnalyticsFiltersProps {
classes: Array<{ id: string; name: string }>
grades: Array<{ id: string; name: string }>
subjects: Array<{ id: string; name: string }>
currentClassId: string
currentSubjectId: string
currentGradeId: string
}
export function AnalyticsFilters({
classes,
grades,
subjects,
currentClassId,
currentSubjectId,
currentGradeId,
}: AnalyticsFiltersProps): JSX.Element {
const buildHref = (overrides: {
classId?: string
subjectId?: string
gradeId?: string
}): string => {
const params = new URLSearchParams()
params.set(
"classId",
overrides.classId !== undefined ? overrides.classId : currentClassId
)
params.set(
"subjectId",
overrides.subjectId !== undefined ? overrides.subjectId : currentSubjectId
)
if (
overrides.gradeId !== undefined
? overrides.gradeId
: currentGradeId
) {
params.set(
"gradeId",
overrides.gradeId !== undefined ? overrides.gradeId : currentGradeId
)
}
return `/teacher/grades/analytics?${params.toString()}`
}
return (
<div className="rounded-lg border bg-card p-4">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground">Class</div>
<ChipNav
options={classes}
currentId={currentClassId}
buildHref={(id) => buildHref({ classId: id })}
size="xs"
className="gap-1.5"
/>
</div>
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground">Subject</div>
<ChipNav
options={subjects}
currentId={currentSubjectId}
buildHref={(id) => buildHref({ subjectId: id })}
size="xs"
allOption={{ id: "all", label: "All" }}
className="gap-1.5"
/>
</div>
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground">
Grade (for class comparison)
</div>
<ChipNav
options={grades}
currentId={currentGradeId}
buildHref={(id) => buildHref({ gradeId: id })}
size="xs"
className="gap-1.5"
/>
</div>
</div>
</div>
)
}

View File

@@ -1,132 +1,60 @@
"use client"
import { BarChart3 } from "lucide-react"
import {
Bar,
BarChart,
CartesianGrid,
Legend,
XAxis,
YAxis,
} from "recharts"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/shared/components/ui/chart"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { SimpleBarChart } from "@/shared/components/charts/simple-bar-chart"
import type { ClassComparisonItem } from "@/modules/grades/types"
const chartConfig = {
averageScore: { label: "Average (%)", color: "hsl(var(--primary))" },
passRate: { label: "Pass Rate (%)", color: "hsl(var(--chart-2))" },
excellentRate: { label: "Excellent (%)", color: "hsl(var(--chart-3))" },
}
interface ClassComparisonChartProps {
data: ClassComparisonItem[]
}
export function ClassComparisonChart({ data }: ClassComparisonChartProps) {
if (!data || data.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-4 w-4" />
Class Comparison
</CardTitle>
<CardDescription>
Compare average, pass rate, and excellent rate across classes.
</CardDescription>
</CardHeader>
<CardContent>
<EmptyState
icon={BarChart3}
title="No comparison data"
description="Select a grade and subject to compare classes."
className="border-none h-60"
/>
</CardContent>
</Card>
)
}
const isEmpty = !data || data.length === 0
const chartData = data.map((d) => ({
name: d.className,
averageScore: d.averageScore,
passRate: d.passRate,
excellentRate: d.excellentRate,
count: d.count,
studentCount: d.studentCount,
}))
const chartData = isEmpty
? []
: data.map((d) => ({
name: d.className,
averageScore: d.averageScore,
passRate: d.passRate,
excellentRate: d.excellentRate,
count: d.count,
studentCount: d.studentCount,
}))
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-4 w-4" />
Class Comparison
</CardTitle>
<CardDescription>
Average score, pass rate (60%), and excellent rate (85%) per class.
</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[300px] w-full">
<BarChart
data={chartData}
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
>
<CartesianGrid
vertical={false}
strokeDasharray="4 4"
strokeOpacity={0.4}
/>
<XAxis
dataKey="name"
tickLine={false}
axisLine={false}
tickMargin={8}
tickFormatter={(value: string) =>
value.length > 8 ? `${value.slice(0, 8)}...` : value
}
/>
<YAxis
domain={[0, 100]}
tickLine={false}
axisLine={false}
tickFormatter={(value: number) => `${value}%`}
width={36}
/>
<ChartTooltip content={<ChartTooltipContent className="w-[240px]" />} />
<Legend />
<Bar
dataKey="averageScore"
fill="var(--color-averageScore)"
radius={[4, 4, 0, 0]}
/>
<Bar
dataKey="passRate"
fill="var(--color-passRate)"
radius={[4, 4, 0, 0]}
/>
<Bar
dataKey="excellentRate"
fill="var(--color-excellentRate)"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ChartContainer>
</CardContent>
</Card>
<ChartCardShell
title="Class Comparison"
description={
isEmpty
? "Compare average, pass rate, and excellent rate across classes."
: "Average score, pass rate (≥60%), and excellent rate (≥85%) per class."
}
icon={BarChart3}
isEmpty={isEmpty}
emptyTitle="No comparison data"
emptyDescription="Select a grade and subject to compare classes."
emptyClassName="h-60"
>
<SimpleBarChart
data={chartData}
bars={[
{ dataKey: "averageScore", name: "Average (%)", color: "hsl(var(--primary))" },
{ dataKey: "passRate", name: "Pass Rate (%)", color: "hsl(var(--chart-2))" },
{ dataKey: "excellentRate", name: "Excellent (%)", color: "hsl(var(--chart-3))" },
]}
xKey="name"
xTruncateLength={8}
yDomain={[0, 100]}
yTickFormatter={(value: number) => `${value}%`}
yWidth={36}
heightClassName="h-[300px]"
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
showLegend
tooltipClassName="w-[240px]"
/>
</ChartCardShell>
)
}

View File

@@ -11,25 +11,9 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { downloadBase64File } from "@/shared/lib/download"
import { exportGradesAction } from "../actions"
function downloadBase64File(base64: string, filename: string) {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
const blob = new Blob([bytes], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
})
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
type ExportButtonProps = {
classId: string
subjectId?: string

View File

@@ -1,21 +1,9 @@
"use client"
import { PieChart as PieChartIcon } from "lucide-react"
import { Bar, BarChart, CartesianGrid, Cell, XAxis, YAxis } from "recharts"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/shared/components/ui/chart"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { SimpleBarChart } from "@/shared/components/charts/simple-bar-chart"
import type { GradeDistributionResult } from "@/modules/grades/types"
const BUCKET_COLORS: Record<string, string> = {
@@ -26,113 +14,68 @@ const BUCKET_COLORS: Record<string, string> = {
"<60": "hsl(0, 84%, 60%)",
}
const chartConfig = {
count: { label: "Students", color: "hsl(var(--primary))" },
}
interface GradeDistributionChartProps {
data: GradeDistributionResult | null
}
export function GradeDistributionChart({ data }: GradeDistributionChartProps) {
if (!data || data.totalCount === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<PieChartIcon className="h-4 w-4" />
Score Distribution
</CardTitle>
<CardDescription>
Number of students in each score range (normalized to 0-100).
</CardDescription>
</CardHeader>
<CardContent>
<EmptyState
icon={PieChartIcon}
title="No distribution data"
description="Select a class and subject to view score distribution."
className="border-none h-60"
/>
</CardContent>
</Card>
)
}
const isEmpty = !data || data.totalCount === 0
const chartData = data.buckets.map((b) => ({
label: b.label,
count: b.count,
percentage:
data.totalCount > 0
? Math.round((b.count / data.totalCount) * 1000) / 10
: 0,
}))
const chartData = isEmpty
? []
: data.buckets.map((b) => ({
label: b.label,
count: b.count,
percentage:
data.totalCount > 0
? Math.round((b.count / data.totalCount) * 1000) / 10
: 0,
}))
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<PieChartIcon className="h-4 w-4" />
Score Distribution
</CardTitle>
<CardDescription>
{data.totalCount} grade record{data.totalCount === 1 ? "" : "s"} across
score ranges.
</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[280px] w-full">
<BarChart
data={chartData}
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
>
<CartesianGrid
vertical={false}
strokeDasharray="4 4"
strokeOpacity={0.4}
/>
<XAxis
dataKey="label"
tickLine={false}
axisLine={false}
tickMargin={8}
/>
<YAxis
allowDecimals={false}
tickLine={false}
axisLine={false}
width={32}
/>
<ChartTooltip
content={
<ChartTooltipContent
className="w-[200px]"
formatter={(payload: unknown) => {
const item = (payload as { payload?: (typeof chartData)[number] })?.payload
if (!item) return null
return (
<div className="flex w-full flex-col gap-0.5">
<span className="text-sm font-medium">
{item.label}: {item.count} student
{item.count === 1 ? "" : "s"}
</span>
<span className="text-xs text-muted-foreground">
{item.percentage}% of total
</span>
</div>
)
}}
/>
}
/>
<Bar dataKey="count" radius={[4, 4, 0, 0]}>
{chartData.map((entry) => (
<Cell key={entry.label} fill={BUCKET_COLORS[entry.label]} />
))}
</Bar>
</BarChart>
</ChartContainer>
</CardContent>
</Card>
<ChartCardShell
title="Score Distribution"
description={
isEmpty
? "Number of students in each score range (normalized to 0-100)."
: `${data.totalCount} grade record${data.totalCount === 1 ? "" : "s"} across score ranges.`
}
icon={PieChartIcon}
isEmpty={isEmpty}
emptyTitle="No distribution data"
emptyDescription="Select a class and subject to view score distribution."
emptyClassName="h-60"
>
<SimpleBarChart
data={chartData}
bars={[
{
dataKey: "count",
name: "Students",
color: "hsl(var(--primary))",
},
]}
xKey="label"
xTickFormatter={null}
yAllowDecimals={false}
yWidth={32}
heightClassName="h-[280px]"
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
tooltipClassName="w-[200px]"
cellColors={BUCKET_COLORS}
tooltipFormatter={(payload: unknown) => {
const item = (payload as { payload?: { label: string; count: number; percentage: number } })?.payload
if (!item) return null
return (
<div className="flex w-full flex-col gap-0.5">
<span className="text-sm font-medium">
{item.label}: {item.count} student{item.count === 1 ? "" : "s"}
</span>
<span className="text-xs text-muted-foreground">{item.percentage}% of total</span>
</div>
)
}}
/>
</ChartCardShell>
)
}

View File

@@ -1,27 +1,8 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { StatItem } from "@/shared/components/ui/stat-item"
import { TrendingUp, TrendingDown, BarChart3, Target, Award, CheckCircle2 } from "lucide-react"
import type { GradeStats } from "../types"
interface StatItemProps {
label: string
value: string | number
icon: React.ReactNode
hint?: string
}
function StatItem({ label, value, icon, hint }: StatItemProps) {
return (
<div className="flex flex-col gap-1 rounded-lg border bg-card p-4">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
<span className="text-muted-foreground">{icon}</span>
</div>
<span className="text-2xl font-bold">{value}</span>
{hint ? <span className="text-xs text-muted-foreground">{hint}</span> : null}
</div>
)
}
export function GradeStatsCard({ stats }: { stats: GradeStats | null }) {
if (!stats || stats.count === 0) {
return (

View File

@@ -1,137 +1,61 @@
"use client"
import { BarChart3 } from "lucide-react"
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/shared/components/ui/chart"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { TrendLineChart } from "@/shared/components/charts/trend-line-chart"
import { formatDate } from "@/shared/lib/utils"
import type { GradeTrendResult } from "@/modules/grades/types"
const chartConfig = {
normalizedScore: {
label: "Score (%)",
color: "hsl(var(--primary))",
},
}
interface GradeTrendChartProps {
data: GradeTrendResult | null
}
export function GradeTrendChart({ data }: GradeTrendChartProps) {
if (!data || data.points.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-4 w-4" />
Grade Trend
</CardTitle>
<CardDescription>
Score progression over time (normalized to 0-100).
</CardDescription>
</CardHeader>
<CardContent>
<EmptyState
icon={BarChart3}
title="No trend data"
description="Select a class and subject to view the grade trend."
className="border-none h-60"
/>
</CardContent>
</Card>
)
}
const isEmpty = !data || data.points.length === 0
const chartData = data.points.map((p) => ({
title: p.title,
normalizedScore: p.normalizedScore,
fullTitle: p.title,
date: formatDate(p.date),
rawScore: p.score,
fullScore: p.fullScore,
type: p.type,
}))
const chartData = isEmpty
? []
: data.points.map((p) => ({
title: p.title,
normalizedScore: p.normalizedScore,
fullTitle: p.title,
date: formatDate(p.date),
rawScore: p.score,
fullScore: p.fullScore,
type: p.type,
}))
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-4 w-4" />
Grade Trend
</CardTitle>
<CardDescription>
{data.label} · avg {data.averageScore.toFixed(1)}%
</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[280px] w-full">
<LineChart
data={chartData}
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
>
<CartesianGrid
vertical={false}
strokeDasharray="4 4"
strokeOpacity={0.4}
/>
<XAxis
dataKey="title"
tickLine={false}
axisLine={false}
tickMargin={8}
tickFormatter={(value: string) =>
value.length > 10 ? `${value.slice(0, 10)}...` : value
}
/>
<YAxis
domain={[0, 100]}
tickLine={false}
axisLine={false}
tickFormatter={(value: number) => `${value}%`}
width={36}
/>
<ChartTooltip
cursor={{
stroke: "hsl(var(--muted-foreground))",
strokeWidth: 1,
strokeDasharray: "4 4",
}}
content={
<ChartTooltipContent
indicator="line"
labelKey="fullTitle"
className="w-[220px]"
/>
}
/>
<Line
dataKey="normalizedScore"
type="monotone"
stroke="var(--color-normalizedScore)"
strokeWidth={2}
dot={{
fill: "var(--color-normalizedScore)",
r: 3,
strokeWidth: 2,
}}
activeDot={{ r: 5, strokeWidth: 0 }}
/>
</LineChart>
</ChartContainer>
</CardContent>
</Card>
<ChartCardShell
title="Grade Trend"
description={
isEmpty
? "Score progression over time (normalized to 0-100)."
: `${data.label} · avg ${data.averageScore.toFixed(1)}%`
}
icon={BarChart3}
isEmpty={isEmpty}
emptyTitle="No trend data"
emptyDescription="Select a class and subject to view the grade trend."
emptyClassName="h-60"
>
<TrendLineChart
data={chartData}
series={[
{
dataKey: "normalizedScore",
name: "Score (%)",
color: "hsl(var(--primary))",
dotRadius: 3,
activeDotRadius: 5,
},
]}
heightClassName="h-[280px]"
margin={{ left: 8, right: 8, top: 8, bottom: 8 }}
yWidth={36}
tooltipClassName="w-[220px]"
/>
</ChartCardShell>
)
}

View File

@@ -0,0 +1,41 @@
import type { JSX } from "react"
import { ChipNav } from "@/shared/components/ui/chip-nav"
interface StatsClassSelectorProps {
classes: Array<{ id: string; name: string }>
subjects: Array<{ id: string; name: string }>
currentClassId: string
currentSubjectId: string
}
export function StatsClassSelector({
classes,
subjects,
currentClassId,
currentSubjectId,
}: StatsClassSelectorProps): JSX.Element {
return (
<div className="flex flex-wrap gap-2">
<ChipNav
options={classes}
currentId={currentClassId}
buildHref={(id) =>
`/teacher/grades/stats?classId=${id}${currentSubjectId !== "all" ? `&subjectId=${currentSubjectId}` : ""}`
}
/>
<div className="ml-auto">
<ChipNav
options={subjects}
currentId={currentSubjectId}
buildHref={(id) =>
id === "all"
? `/teacher/grades/stats?classId=${currentClassId}`
: `/teacher/grades/stats?classId=${currentClassId}&subjectId=${id}`
}
allOption={{ id: "all", label: "All Subjects" }}
/>
</div>
</div>
)
}

View File

@@ -1,116 +1,64 @@
"use client"
import { Radar } from "lucide-react"
import {
PolarAngleAxis,
PolarGrid,
PolarRadiusAxis,
Radar as RechartsRadar,
RadarChart,
} from "recharts"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from "@/shared/components/ui/chart"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { ComparisonRadarChart } from "@/shared/components/charts/comparison-radar-chart"
import type { SubjectComparisonItem } from "@/modules/grades/types"
const chartConfig = {
averageScore: { label: "Average (%)", color: "hsl(var(--primary))" },
passRate: { label: "Pass Rate (%)", color: "hsl(var(--chart-2))" },
}
interface SubjectComparisonChartProps {
data: SubjectComparisonItem[]
}
export function SubjectComparisonChart({ data }: SubjectComparisonChartProps) {
if (!data || data.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Radar className="h-4 w-4" />
Subject Comparison
</CardTitle>
<CardDescription>
Compare performance across subjects for the selected class.
</CardDescription>
</CardHeader>
<CardContent>
<EmptyState
icon={Radar}
title="No comparison data"
description="Select a class to compare subject performance."
className="border-none h-60"
/>
</CardContent>
</Card>
)
}
const isEmpty = !data || data.length === 0
const chartData = data.map((d) => ({
subject: d.subjectName,
averageScore: d.averageScore,
passRate: d.passRate,
excellentRate: d.excellentRate,
count: d.count,
}))
const chartData = isEmpty
? []
: data.map((d) => ({
subject: d.subjectName,
averageScore: d.averageScore,
passRate: d.passRate,
excellentRate: d.excellentRate,
count: d.count,
}))
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Radar className="h-4 w-4" />
Subject Comparison
</CardTitle>
<CardDescription>
Average score and pass rate per subject (normalized to 0-100).
</CardDescription>
</CardHeader>
<CardContent>
<ChartContainer config={chartConfig} className="h-[300px] w-full">
<RadarChart data={chartData} outerRadius="75%">
<PolarGrid strokeOpacity={0.4} />
<PolarAngleAxis
dataKey="subject"
tick={{ fontSize: 12 }}
tickFormatter={(value: string) =>
value.length > 6 ? `${value.slice(0, 6)}...` : value
}
/>
<PolarRadiusAxis
domain={[0, 100]}
tickFormatter={(value: number) => `${value}%`}
tick={{ fontSize: 10 }}
/>
<ChartTooltip content={<ChartTooltipContent className="w-[220px]" />} />
<RechartsRadar
name="Average"
dataKey="averageScore"
stroke="var(--color-averageScore)"
fill="var(--color-averageScore)"
fillOpacity={0.4}
/>
<RechartsRadar
name="Pass Rate"
dataKey="passRate"
stroke="var(--color-passRate)"
fill="var(--color-passRate)"
fillOpacity={0.2}
/>
</RadarChart>
</ChartContainer>
</CardContent>
</Card>
<ChartCardShell
title="Subject Comparison"
description={
isEmpty
? "Compare performance across subjects for the selected class."
: "Average score and pass rate per subject (normalized to 0-100)."
}
icon={Radar}
isEmpty={isEmpty}
emptyTitle="No comparison data"
emptyDescription="Select a class to compare subject performance."
emptyClassName="h-60"
>
<ComparisonRadarChart
data={chartData}
angleKey="subject"
angleTickFormatter={(value: string) =>
value.length > 6 ? `${value.slice(0, 6)}...` : value
}
heightClassName="h-[300px]"
series={[
{
dataKey: "averageScore",
name: "Average",
color: "hsl(var(--primary))",
fillOpacity: 0.4,
},
{
dataKey: "passRate",
name: "Pass Rate",
color: "hsl(var(--chart-2))",
fillOpacity: 0.2,
},
]}
/>
</ChartCardShell>
)
}

View File

@@ -1,7 +1,7 @@
import "server-only"
import { cache } from "react"
import { and, asc, eq, inArray, sql } from "drizzle-orm"
import { and, asc, eq, inArray, sql, type SQL } from "drizzle-orm"
import { db } from "@/shared/db"
import { gradeRecords } from "@/shared/db/schema"
@@ -31,7 +31,7 @@ const normalize = (score: number, fullScore: number): number => {
return Math.round((score / fullScore) * 10000) / 100
}
const buildScopeClassFilter = (scope: DataScope) => {
const buildScopeClassFilter = (scope: DataScope): SQL | null => {
if (scope.type === "all") return null
if (scope.type === "class_taught") {
return scope.classIds.length > 0 ? inArray(gradeRecords.classId, scope.classIds) : sql`1=0`
@@ -242,7 +242,6 @@ export const getSubjectComparison = cache(
if (rows.length === 0) return []
// Fetch subject names via cross-module interface
const subjectIds = Array.from(new Set(rows.map((r) => r.subjectId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const subjectOptions = await getSubjectOptions()
const subjectNameById = new Map<string, string>()
for (const s of subjectOptions) subjectNameById.set(s.id, s.name)

View File

@@ -2,7 +2,7 @@ import "server-only"
import { cache } from "react"
import { createId } from "@paralleldrive/cuid2"
import { and, count, desc, eq, inArray, sql } from "drizzle-orm"
import { and, count, desc, eq, inArray, sql, type SQL } from "drizzle-orm"
import { db } from "@/shared/db"
import { gradeRecords } from "@/shared/db/schema"
@@ -54,7 +54,7 @@ const serializeRecord = (r: typeof gradeRecords.$inferSelect): GradeRecord => ({
updatedAt: r.updatedAt.toISOString(),
})
const buildScopeClassFilter = (scope: DataScope) => {
const buildScopeClassFilter = (scope: DataScope): SQL | null => {
if (scope.type === "all") return null
if (scope.type === "class_taught") {
return scope.classIds.length > 0 ? inArray(gradeRecords.classId, scope.classIds) : sql`1=0`
@@ -107,7 +107,6 @@ export const getGradeRecords = cache(
// Batch fetch display names via cross-module interfaces
const studentIds = Array.from(new Set(rows.map((r) => r.record.studentId)))
const classIds = Array.from(new Set(rows.map((r) => r.record.classId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const subjectIds = Array.from(new Set(rows.map((r) => r.record.subjectId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const recorderIds = Array.from(new Set(rows.map((r) => r.record.recordedBy)))
const [studentNameMap, classNameMap, subjectOptions, recorderNameMap] = await Promise.all([
@@ -270,9 +269,8 @@ export const getClassGradeStats = cache(
}
)
export async function getStudentGradeSummary(
studentId: string
): Promise<StudentGradeSummary | null> {
export const getStudentGradeSummary = cache(
async (studentId: string): Promise<StudentGradeSummary | null> => {
const studentNameMap = await getUserNamesByIds([studentId])
const studentName = studentNameMap.get(studentId)?.name ?? null
if (!studentName && !studentNameMap.has(studentId)) return null
@@ -297,7 +295,6 @@ export async function getStudentGradeSummary(
// Batch fetch display names via cross-module interfaces
const classIds = Array.from(new Set(records.map((r) => r.record.classId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const subjectIds = Array.from(new Set(records.map((r) => r.record.subjectId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const [classNameMap, subjectOptions] = await Promise.all([
getClassNamesByIds(classIds),
@@ -336,7 +333,8 @@ export async function getStudentGradeSummary(
averageScore: Math.round(avg * 100) / 100,
rank: 0,
}
}
}
)
export const getClassRanking = cache(
async (
@@ -374,9 +372,9 @@ export const getClassRanking = cache(
}
)
export async function getClassStudentsForEntry(classId: string): Promise<
export const getClassStudentsForEntry = cache(async (classId: string): Promise<
Array<{ id: string; name: string; email: string }>
> {
> => {
const studentIds = await getActiveStudentIdsByClassId(classId)
if (studentIds.length === 0) return []
@@ -392,42 +390,44 @@ export async function getClassStudentsForEntry(classId: string): Promise<
}
})
.sort((a, b) => a.name.localeCompare(b.name))
}
})
export async function getClassGradeStatsWithMeta(
classId: string,
subjectId?: string,
examId?: string
): Promise<ClassGradeStats | null> {
const classExists = await getClassExists(classId)
if (!classExists) return null
export const getClassGradeStatsWithMeta = cache(
async (
classId: string,
subjectId?: string,
examId?: string
): Promise<ClassGradeStats | null> => {
const classExists = await getClassExists(classId)
if (!classExists) return null
const className = await getClassNameById(classId)
const stats = await getClassGradeStats(classId, subjectId, examId)
if (!stats) {
return {
classId,
className: className ?? "Unknown",
stats: {
average: 0,
median: 0,
max: 0,
min: 0,
stdDev: 0,
passRate: 0,
excellentRate: 0,
count: 0,
},
studentCount: 0,
}
}
const activeStudentIds = await getActiveStudentIdsByClassId(classId)
const className = await getClassNameById(classId)
const stats = await getClassGradeStats(classId, subjectId, examId)
if (!stats) {
return {
classId,
className: className ?? "Unknown",
stats: {
average: 0,
median: 0,
max: 0,
min: 0,
stdDev: 0,
passRate: 0,
excellentRate: 0,
count: 0,
},
studentCount: 0,
stats,
studentCount: activeStudentIds.length,
}
}
const activeStudentIds = await getActiveStudentIdsByClassId(classId)
return {
classId,
className: className ?? "Unknown",
stats,
studentCount: activeStudentIds.length,
}
}
)

View File

@@ -16,13 +16,6 @@ const TYPE_LABELS: Record<GradeRecordType, string> = {
other: "其他",
}
const formatDateForFile = (d = new Date()) => {
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, "0")
const day = String(d.getDate()).padStart(2, "0")
return `${y}-${m}-${day}`
}
/**
* 导出成绩单
* Sheet 1: 成绩明细
@@ -124,10 +117,13 @@ export async function exportClassGradeReportToExcel(params: {
getUserNamesByIds(studentIds),
])
const subjectNameById = new Map<string, string>()
for (const s of subjectOptions) subjectNameById.set(s.id, s.name)
const subjectRows = subjectIds
.map((id) => {
const subject = subjectOptions.find((s) => s.id === id)
return subject ? { id: subject.id, name: subject.name } : null
const name = subjectNameById.get(id)
return name ? { id, name } : null
})
.filter((s): s is { id: string; name: string } => s !== null)
@@ -202,5 +198,3 @@ export async function exportClassGradeReportToExcel(params: {
],
})
}
export { formatDateForFile }