refactor(grades,diagnostic): 完成成绩和学情诊断模块审计 P1+P2 改进项
P1-1: 抽取 stats-service.ts,将 8 个统计计算纯函数从 data-access 层分离 P1-5: 创建 WidgetBoundary 组件 + 补齐 teacher 路由 loading.tsx/error.tsx (14 文件) P1-6: 同步架构图文档 004/005,新增 stats-service 与 widget-boundary 节点 P2-1: 补充 a11y ARIA 属性(5 图表 role=img + aria-label,2 表格 caption,3 列表 role=list,3 按钮 aria-label) P2-3: 修复班级报告 studentId 字段语义错误(schema 改为可空 + 迁移 + 代码适配) P2-4: 修复 grade_managed scope 返回空数据(改为子查询 classes 表按 gradeId 过滤) P2-5: 新增 /parent/diagnostic/ 页面(多子女学情诊断聚合 + loading + error) P2-6: 统一 SearchParams 工具(student/grades 和 management/grade/insights 改用 @/shared/lib/search-params)
This commit is contained in:
@@ -35,35 +35,37 @@ export function MasteryRadarChart({ data }: MasteryRadarChartProps) {
|
||||
emptyDescription="No knowledge point mastery records found for this student."
|
||||
emptyClassName="h-60"
|
||||
>
|
||||
<ComparisonRadarChart
|
||||
data={chartData}
|
||||
angleKey="shortName"
|
||||
angleTickFontSize={11}
|
||||
domain={[0, 100]}
|
||||
tickCount={5}
|
||||
showLegend={hasClassAverage}
|
||||
heightClassName="mx-auto h-96 w-full max-w-lg"
|
||||
gridStrokeDasharray="4 4"
|
||||
series={[
|
||||
{
|
||||
dataKey: "student",
|
||||
name: "Student",
|
||||
color: "hsl(var(--primary))",
|
||||
fillOpacity: 0.35,
|
||||
strokeWidth: 2,
|
||||
show: true,
|
||||
},
|
||||
{
|
||||
dataKey: "classAverage",
|
||||
name: "Class Avg",
|
||||
color: "hsl(var(--chart-2))",
|
||||
fillOpacity: 0.15,
|
||||
strokeWidth: 2,
|
||||
strokeDasharray: "4 4",
|
||||
show: hasClassAverage,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<div role="img" aria-label={`知识点掌握度雷达图:${isEmpty ? "暂无数据" : `共 ${data.length} 个知识点的掌握度${hasClassAverage ? "(含班级平均对比)" : ""}`}`}>
|
||||
<ComparisonRadarChart
|
||||
data={chartData}
|
||||
angleKey="shortName"
|
||||
angleTickFontSize={11}
|
||||
domain={[0, 100]}
|
||||
tickCount={5}
|
||||
showLegend={hasClassAverage}
|
||||
heightClassName="mx-auto h-96 w-full max-w-lg"
|
||||
gridStrokeDasharray="4 4"
|
||||
series={[
|
||||
{
|
||||
dataKey: "student",
|
||||
name: "Student",
|
||||
color: "hsl(var(--primary))",
|
||||
fillOpacity: 0.35,
|
||||
strokeWidth: 2,
|
||||
show: true,
|
||||
},
|
||||
{
|
||||
dataKey: "classAverage",
|
||||
name: "Class Avg",
|
||||
color: "hsl(var(--chart-2))",
|
||||
fillOpacity: 0.15,
|
||||
strokeWidth: 2,
|
||||
strokeDasharray: "4 4",
|
||||
show: hasClassAverage,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</ChartCardShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,6 +157,7 @@ export function ReportList({ reports }: ReportListProps) {
|
||||
) : (
|
||||
<div className="rounded-md border bg-card">
|
||||
<Table>
|
||||
<caption className="sr-only">学情诊断报告列表</caption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Type</TableHead>
|
||||
@@ -175,7 +176,7 @@ export function ReportList({ reports }: ReportListProps) {
|
||||
<TableCell>
|
||||
<Badge variant="outline">{typeLabels[r.reportType] ?? r.reportType}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{r.studentName}</TableCell>
|
||||
<TableCell className="font-medium">{r.studentName ?? (r.reportType === "class" ? "(班级报告)" : r.reportType === "grade" ? "(年级报告)" : "-")}</TableCell>
|
||||
<TableCell>{r.period ?? "-"}</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{r.overallScore !== null ? `${r.overallScore.toFixed(1)}%` : "-"}
|
||||
@@ -195,6 +196,7 @@ export function ReportList({ reports }: ReportListProps) {
|
||||
className="h-8 w-8 text-green-600"
|
||||
onClick={() => setPublishId(r.id)}
|
||||
title="Publish"
|
||||
aria-label={`发布报告 ${r.studentName}`}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -205,6 +207,7 @@ export function ReportList({ reports }: ReportListProps) {
|
||||
className="h-8 w-8 text-destructive"
|
||||
onClick={() => setDeleteId(r.id)}
|
||||
title="Delete"
|
||||
aria-label={`删除报告 ${r.studentName}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
@@ -96,7 +96,7 @@ export function StudentDiagnosticView({ summary, reports, classAverageMastery }:
|
||||
{summary.strengths.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No strengths identified yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
<ul className="space-y-2" role="list" aria-label="优势知识点列表">
|
||||
{summary.strengths.map((m) => (
|
||||
<li key={m.knowledgePointId} className="flex items-center justify-between">
|
||||
<span className="text-sm">{m.knowledgePointName}</span>
|
||||
@@ -119,7 +119,7 @@ export function StudentDiagnosticView({ summary, reports, classAverageMastery }:
|
||||
{summary.weaknesses.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No weaknesses identified.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
<ul className="space-y-2" role="list" aria-label="薄弱知识点列表">
|
||||
{summary.weaknesses.map((m) => (
|
||||
<li key={m.knowledgePointId} className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
@@ -162,7 +162,7 @@ export function StudentDiagnosticView({ summary, reports, classAverageMastery }:
|
||||
{latestReport.recommendations && latestReport.recommendations.length > 0 ? (
|
||||
<div>
|
||||
<h4 className="mb-2 text-sm font-semibold">Recommendations</h4>
|
||||
<ul className="space-y-1.5">
|
||||
<ul className="space-y-1.5" role="list" aria-label="学习建议列表">
|
||||
{latestReport.recommendations.map((rec, i) => (
|
||||
<li key={i} className="text-sm text-muted-foreground">• {rec}</li>
|
||||
))}
|
||||
|
||||
@@ -109,7 +109,7 @@ export async function generateClassDiagnosticReport(
|
||||
const id = createId()
|
||||
await db.insert(learningDiagnosticReports).values({
|
||||
id,
|
||||
studentId: generatedBy, // 班级报告 studentId 存生成者 ID(schema 要求 NOT NULL)
|
||||
studentId: null, // 班级报告无单个学生,studentId 置空(P2-3 修复:不再存生成者 ID)
|
||||
generatedBy,
|
||||
reportType: "class",
|
||||
period,
|
||||
@@ -141,14 +141,16 @@ export const getDiagnosticReports = cache(
|
||||
// 收集所有需要查询姓名的用户 ID(学生 + 生成者),通过 users data-access 统一获取
|
||||
const userIds = new Set<string>()
|
||||
for (const r of rows) {
|
||||
userIds.add(r.report.studentId)
|
||||
if (r.report.studentId) userIds.add(r.report.studentId)
|
||||
if (r.report.generatedBy) userIds.add(r.report.generatedBy)
|
||||
}
|
||||
const userMap = await getUserNamesByIds(Array.from(userIds))
|
||||
|
||||
return rows.map((r) => ({
|
||||
...serializeReport(r.report),
|
||||
studentName: userMap.get(r.report.studentId)?.name ?? "Unknown",
|
||||
studentName: r.report.studentId
|
||||
? userMap.get(r.report.studentId)?.name ?? "Unknown"
|
||||
: null,
|
||||
generatedByName: r.report.generatedBy
|
||||
? userMap.get(r.report.generatedBy)?.name ?? "Unknown"
|
||||
: null,
|
||||
@@ -167,13 +169,16 @@ export const getDiagnosticReportById = cache(
|
||||
if (!row) return null
|
||||
|
||||
// 通过 users data-access 获取学生姓名和生成者姓名
|
||||
const userIds = [row.report.studentId]
|
||||
const userIds: string[] = []
|
||||
if (row.report.studentId) userIds.push(row.report.studentId)
|
||||
if (row.report.generatedBy) userIds.push(row.report.generatedBy)
|
||||
const userMap = await getUserNamesByIds(userIds)
|
||||
|
||||
return {
|
||||
...serializeReport(row.report),
|
||||
studentName: userMap.get(row.report.studentId)?.name ?? "Unknown",
|
||||
studentName: row.report.studentId
|
||||
? userMap.get(row.report.studentId)?.name ?? "Unknown"
|
||||
: null,
|
||||
generatedByName: row.report.generatedBy
|
||||
? userMap.get(row.report.generatedBy)?.name ?? null
|
||||
: null,
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface StudentMasterySummary {
|
||||
/** 诊断报告 */
|
||||
export interface DiagnosticReport {
|
||||
id: string
|
||||
studentId: string
|
||||
studentId: string | null
|
||||
generatedBy: string | null
|
||||
reportType: DiagnosticReportType
|
||||
period: string | null
|
||||
@@ -52,7 +52,7 @@ export interface DiagnosticReport {
|
||||
|
||||
/** 含学生名的诊断报告(join users 后) */
|
||||
export interface DiagnosticReportWithDetails extends DiagnosticReport {
|
||||
studentName: string
|
||||
studentName: string | null
|
||||
generatedByName: string | null
|
||||
}
|
||||
|
||||
|
||||
@@ -38,23 +38,25 @@ export function ClassComparisonChart({ data }: ClassComparisonChartProps) {
|
||||
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]"
|
||||
/>
|
||||
<div role="img" aria-label={`班级对比柱状图:${isEmpty ? "暂无数据" : `共 ${data.length} 个班级的均分、及格率与优秀率对比`}`}>
|
||||
<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]"
|
||||
/>
|
||||
</div>
|
||||
</ChartCardShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -70,37 +70,39 @@ export function GradeDistributionChart({ data }: GradeDistributionChartProps) {
|
||||
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) => {
|
||||
if (!isDistributionTooltipPayload(payload)) return null
|
||||
const item = payload.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>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<div role="img" aria-label={`分数分布柱状图:${isEmpty ? "暂无数据" : `共 ${data.totalCount} 条成绩记录分布在 5 个分数区间`}`}>
|
||||
<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) => {
|
||||
if (!isDistributionTooltipPayload(payload)) return null
|
||||
const item = payload.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>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</ChartCardShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Table,
|
||||
@@ -21,18 +20,13 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { StatusBadge } from "@/shared/components/ui/status-badge"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
import { Trash2 } from "lucide-react"
|
||||
|
||||
import { deleteGradeRecordAction } from "../actions"
|
||||
import type { GradeRecordListItem } from "../types"
|
||||
|
||||
const typeColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
exam: "default",
|
||||
quiz: "secondary",
|
||||
homework: "outline",
|
||||
other: "outline",
|
||||
}
|
||||
import { GRADE_TYPE_VARIANT } from "../types"
|
||||
|
||||
export function GradeRecordList({ records }: { records: GradeRecordListItem[] }) {
|
||||
const router = useRouter()
|
||||
@@ -65,6 +59,7 @@ export function GradeRecordList({ records }: { records: GradeRecordListItem[] })
|
||||
<>
|
||||
<div className="rounded-md border bg-card">
|
||||
<Table>
|
||||
<caption className="sr-only">成绩记录列表</caption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Student</TableHead>
|
||||
@@ -90,9 +85,7 @@ export function GradeRecordList({ records }: { records: GradeRecordListItem[] })
|
||||
{r.score} / {r.fullScore}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={typeColors[r.type]} className="capitalize">
|
||||
{r.type}
|
||||
</Badge>
|
||||
<StatusBadge status={r.type} variantMap={GRADE_TYPE_VARIANT} />
|
||||
</TableCell>
|
||||
<TableCell>S{r.semester}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{r.recorderName}</TableCell>
|
||||
@@ -103,6 +96,7 @@ export function GradeRecordList({ records }: { records: GradeRecordListItem[] })
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive"
|
||||
onClick={() => setDeleteId(r.id)}
|
||||
aria-label={`删除 ${r.studentName} 的 ${r.subjectName} 成绩记录`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
@@ -40,22 +40,24 @@ export function GradeTrendChart({ data }: GradeTrendChartProps) {
|
||||
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]"
|
||||
/>
|
||||
<div role="img" aria-label={`成绩趋势图:${isEmpty ? "暂无数据" : `${data.label},平均 ${data.averageScore.toFixed(1)}%`}`}>
|
||||
<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]"
|
||||
/>
|
||||
</div>
|
||||
</ChartCardShell>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -37,28 +37,30 @@ export function SubjectComparisonChart({ data }: SubjectComparisonChartProps) {
|
||||
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,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<div role="img" aria-label={`科目对比雷达图:${isEmpty ? "暂无数据" : `共 ${data.length} 个科目的均分与及格率对比`}`}>
|
||||
<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,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</ChartCardShell>
|
||||
)
|
||||
}
|
||||
|
||||
139
src/modules/grades/components/widget-boundary.tsx
Normal file
139
src/modules/grades/components/widget-boundary.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client"
|
||||
|
||||
/**
|
||||
* Grades/Diagnostic 模块通用 Widget 边界组件。
|
||||
*
|
||||
* 组合三个能力:
|
||||
* 1. Error Boundary — 隔离故障域,单个 Widget 抛错不影响其他区块
|
||||
* 2. Suspense — 流式渲染时显示骨架屏,避免白屏等待
|
||||
* 3. Skeleton — 与 Widget 尺寸匹配的占位
|
||||
*
|
||||
* 用法:
|
||||
* ```tsx
|
||||
* <WidgetBoundary title="成绩趋势">
|
||||
* <GradeTrendChart data={data} />
|
||||
* </WidgetBoundary>
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { Component, Suspense, type ReactNode } from "react"
|
||||
import { AlertCircle } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Skeleton } from "@/shared/components/ui/skeleton"
|
||||
|
||||
interface WidgetBoundaryProps {
|
||||
children: ReactNode
|
||||
/** Widget 标题(用于错误提示和 aria-label) */
|
||||
title?: string
|
||||
/** 骨架屏高度(默认 200px) */
|
||||
skeletonHeight?: number
|
||||
/** 自定义错误描述 */
|
||||
fallbackDescription?: string
|
||||
/** 重试按钮文案 */
|
||||
retryLabel?: string
|
||||
}
|
||||
|
||||
interface WidgetBoundaryState {
|
||||
hasError: boolean
|
||||
}
|
||||
|
||||
class WidgetErrorBoundary extends Component<
|
||||
Pick<
|
||||
WidgetBoundaryProps,
|
||||
"title" | "fallbackDescription" | "retryLabel" | "children"
|
||||
>,
|
||||
WidgetBoundaryState
|
||||
> {
|
||||
constructor(props: WidgetBoundaryProps) {
|
||||
super(props)
|
||||
this.state = { hasError: false }
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(): WidgetBoundaryState {
|
||||
return { hasError: true }
|
||||
}
|
||||
|
||||
handleReset = (): void => {
|
||||
this.setState({ hasError: false })
|
||||
}
|
||||
|
||||
render(): ReactNode {
|
||||
if (this.state.hasError) {
|
||||
const title = this.props.title ?? "区块"
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
aria-live="assertive"
|
||||
className="flex h-full min-h-[200px] flex-col items-center justify-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-6 text-center"
|
||||
>
|
||||
<AlertCircle className="h-8 w-8 text-destructive" aria-hidden="true" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{title}加载失败
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{this.props.fallbackDescription ?? "请重试或刷新页面"}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={this.handleReset}
|
||||
aria-label={`重试加载${title}`}
|
||||
>
|
||||
{this.props.retryLabel ?? "重试"}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
|
||||
function WidgetSkeleton({
|
||||
height,
|
||||
title,
|
||||
}: {
|
||||
height: number
|
||||
title?: string
|
||||
}): ReactNode {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label={`${title ?? "区块"}加载中`}
|
||||
aria-live="polite"
|
||||
className="space-y-3 p-4"
|
||||
style={{ minHeight: height }}
|
||||
>
|
||||
<Skeleton className="h-6 w-1/3" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
<Skeleton className="h-32 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function WidgetBoundary({
|
||||
children,
|
||||
title,
|
||||
skeletonHeight = 200,
|
||||
fallbackDescription,
|
||||
retryLabel,
|
||||
}: WidgetBoundaryProps): ReactNode {
|
||||
return (
|
||||
<WidgetErrorBoundary
|
||||
title={title}
|
||||
fallbackDescription={fallbackDescription}
|
||||
retryLabel={retryLabel}
|
||||
>
|
||||
<Suspense
|
||||
fallback={
|
||||
<WidgetSkeleton height={skeletonHeight} title={title} />
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Suspense>
|
||||
</WidgetErrorBoundary>
|
||||
)
|
||||
}
|
||||
@@ -13,11 +13,16 @@ import { getSubjectOptions } from "@/modules/school/data-access"
|
||||
import type { DataScope } from "@/shared/types/permissions"
|
||||
|
||||
import { buildScopeClassFilter, normalize, toNumber } from "./lib/grade-utils"
|
||||
import {
|
||||
buildGradeTrendPoints,
|
||||
computeClassComparisonStats,
|
||||
computeGradeDistribution,
|
||||
computeSubjectComparisonStats,
|
||||
computeTrendAverage,
|
||||
} from "./stats-service"
|
||||
import type {
|
||||
ClassComparisonItem,
|
||||
GradeDistributionBucket,
|
||||
GradeDistributionResult,
|
||||
GradeTrendPoint,
|
||||
GradeTrendResult,
|
||||
SubjectComparisonItem,
|
||||
} from "./types"
|
||||
@@ -64,20 +69,8 @@ export const getGradeTrend = cache(
|
||||
subjectName = subject?.name ?? "Unknown"
|
||||
}
|
||||
|
||||
const points: GradeTrendPoint[] = rows.map((r) => {
|
||||
const score = toNumber(r.record.score)
|
||||
const fullScore = toNumber(r.record.fullScore)
|
||||
return {
|
||||
date: r.record.createdAt.toISOString(),
|
||||
title: r.record.title,
|
||||
score,
|
||||
fullScore,
|
||||
normalizedScore: normalize(score, fullScore),
|
||||
type: r.record.type,
|
||||
}
|
||||
})
|
||||
|
||||
const avg = points.reduce((acc, p) => acc + p.normalizedScore, 0) / points.length
|
||||
const points = buildGradeTrendPoints(rows)
|
||||
const avg = computeTrendAverage(points)
|
||||
const finalClassName = className ?? "Class"
|
||||
const studentLabel = params.studentId
|
||||
? `Student ${params.studentId.slice(-4)}`
|
||||
@@ -88,7 +81,7 @@ export const getGradeTrend = cache(
|
||||
? `${finalClassName} · ${subjectName} · ${studentLabel}`
|
||||
: `${finalClassName} · ${studentLabel}`,
|
||||
points,
|
||||
averageScore: Math.round(avg * 100) / 100,
|
||||
averageScore: avg,
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -145,46 +138,11 @@ export const getClassComparison = cache(
|
||||
|
||||
const result: ClassComparisonItem[] = allowedClassRows.map((cls) => {
|
||||
const rows = byClass.get(cls.id) ?? []
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
classId: cls.id,
|
||||
className: cls.name,
|
||||
averageScore: 0,
|
||||
medianScore: 0,
|
||||
passRate: 0,
|
||||
excellentRate: 0,
|
||||
count: 0,
|
||||
studentCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = rows.map((r) =>
|
||||
normalize(toNumber(r.score), toNumber(r.fullScore))
|
||||
)
|
||||
const sorted = [...normalized].sort((a, b) => a - b)
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
const median =
|
||||
sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
|
||||
const avg = normalized.reduce((a, b) => a + b, 0) / normalized.length
|
||||
const uniqueStudents = new Set(rows.map((r) => r.studentId)).size
|
||||
|
||||
const { passCount, excellentCount } = normalized.reduce(
|
||||
(acc, s) => ({
|
||||
passCount: acc.passCount + (s >= 60 ? 1 : 0),
|
||||
excellentCount: acc.excellentCount + (s >= 85 ? 1 : 0),
|
||||
}),
|
||||
{ passCount: 0, excellentCount: 0 }
|
||||
)
|
||||
|
||||
const stats = computeClassComparisonStats(rows)
|
||||
return {
|
||||
classId: cls.id,
|
||||
className: cls.name,
|
||||
averageScore: Math.round(avg * 100) / 100,
|
||||
medianScore: Math.round(median * 100) / 100,
|
||||
passRate: Math.round((passCount / normalized.length) * 10000) / 100,
|
||||
excellentRate: Math.round((excellentCount / normalized.length) * 10000) / 100,
|
||||
count: normalized.length,
|
||||
studentCount: uniqueStudents,
|
||||
...stats,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -234,28 +192,11 @@ export const getSubjectComparison = cache(
|
||||
const result: SubjectComparisonItem[] = []
|
||||
for (const [subjectId, entry] of bySubject.entries()) {
|
||||
if (entry.scores.length === 0) continue
|
||||
const sorted = [...entry.scores].sort((a, b) => a - b)
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
const median =
|
||||
sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
|
||||
const avg = entry.scores.reduce((a, b) => a + b, 0) / entry.scores.length
|
||||
|
||||
const { passCount, excellentCount } = entry.scores.reduce(
|
||||
(acc, s) => ({
|
||||
passCount: acc.passCount + (s >= 60 ? 1 : 0),
|
||||
excellentCount: acc.excellentCount + (s >= 85 ? 1 : 0),
|
||||
}),
|
||||
{ passCount: 0, excellentCount: 0 }
|
||||
)
|
||||
|
||||
const stats = computeSubjectComparisonStats(entry.scores)
|
||||
result.push({
|
||||
subjectId,
|
||||
subjectName: entry.name,
|
||||
averageScore: Math.round(avg * 100) / 100,
|
||||
medianScore: Math.round(median * 100) / 100,
|
||||
passRate: Math.round((passCount / entry.scores.length) * 10000) / 100,
|
||||
excellentRate: Math.round((excellentCount / entry.scores.length) * 10000) / 100,
|
||||
count: entry.scores.length,
|
||||
...stats,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -289,24 +230,6 @@ export const getGradeDistribution = cache(
|
||||
.from(gradeRecords)
|
||||
.where(and(...conditions))
|
||||
|
||||
const buckets: GradeDistributionBucket[] = [
|
||||
{ label: "90-100", min: 90, max: 100, count: 0 },
|
||||
{ label: "80-89", min: 80, max: 89, count: 0 },
|
||||
{ label: "70-79", min: 70, max: 79, count: 0 },
|
||||
{ label: "60-69", min: 60, max: 69, count: 0 },
|
||||
{ label: "<60", min: 0, max: 59, count: 0 },
|
||||
]
|
||||
|
||||
for (const r of rows) {
|
||||
const normalized = normalize(toNumber(r.score), toNumber(r.fullScore))
|
||||
const rounded = Math.round(normalized)
|
||||
if (rounded >= 90) buckets[0].count++
|
||||
else if (rounded >= 80) buckets[1].count++
|
||||
else if (rounded >= 70) buckets[2].count++
|
||||
else if (rounded >= 60) buckets[3].count++
|
||||
else buckets[4].count++
|
||||
}
|
||||
|
||||
return { buckets, totalCount: rows.length }
|
||||
return computeGradeDistribution(rows)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -9,8 +9,8 @@ import { getStudentActiveClassId } from "@/modules/classes/data-access"
|
||||
import { getUserNamesByIds } from "@/modules/users/data-access"
|
||||
|
||||
import { normalize, toNumber } from "./lib/grade-utils"
|
||||
import { buildRankingTrendPoints, type RankingTrendEntry } from "./stats-service"
|
||||
import type {
|
||||
RankingTrendPoint,
|
||||
RankingTrendResult,
|
||||
} from "./types"
|
||||
|
||||
@@ -56,13 +56,7 @@ export const getRankingTrend = cache(
|
||||
.where(and(...conditions))
|
||||
.orderBy(asc(gradeRecords.createdAt))
|
||||
|
||||
const byTitle = new Map<
|
||||
string,
|
||||
{
|
||||
date: Date
|
||||
entries: Array<{ studentId: string; normalized: number }>
|
||||
}
|
||||
>()
|
||||
const byTitle = new Map<string, RankingTrendEntry>()
|
||||
|
||||
for (const r of rows) {
|
||||
const entry = byTitle.get(r.title) ?? { date: r.createdAt, entries: [] }
|
||||
@@ -73,33 +67,7 @@ export const getRankingTrend = cache(
|
||||
byTitle.set(r.title, entry)
|
||||
}
|
||||
|
||||
const points: RankingTrendPoint[] = []
|
||||
for (const [title, entry] of byTitle.entries()) {
|
||||
if (entry.entries.length === 0) continue
|
||||
const sorted = [...entry.entries].sort((a, b) => b.normalized - a.normalized)
|
||||
// Single traversal: find rank and student entry together
|
||||
let rank = 0
|
||||
let studentEntry: { studentId: string; normalized: number } | null = null
|
||||
for (let i = 0; i < sorted.length; i += 1) {
|
||||
const e = sorted[i]
|
||||
if (e.studentId === studentId) {
|
||||
rank = i + 1
|
||||
studentEntry = e
|
||||
break
|
||||
}
|
||||
}
|
||||
if (rank <= 0 || !studentEntry) continue
|
||||
|
||||
points.push({
|
||||
title,
|
||||
date: entry.date.toISOString(),
|
||||
score: studentEntry.normalized,
|
||||
rank,
|
||||
totalStudents: sorted.length,
|
||||
})
|
||||
}
|
||||
|
||||
points.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
|
||||
const points = buildRankingTrendPoints(byTitle, studentId)
|
||||
|
||||
return {
|
||||
studentId,
|
||||
|
||||
@@ -17,6 +17,7 @@ import { getUserNamesByIds } from "@/modules/users/data-access"
|
||||
import type { DataScope } from "@/shared/types/permissions"
|
||||
|
||||
import { buildScopeClassFilter, toNumber } from "./lib/grade-utils"
|
||||
import { computeAverageScore, computeGradeStats } from "./stats-service"
|
||||
import type {
|
||||
ClassGradeStats,
|
||||
ClassRankingItem,
|
||||
@@ -208,40 +209,7 @@ export const getClassGradeStats = cache(
|
||||
.from(gradeRecords)
|
||||
.where(and(...conditions))
|
||||
|
||||
if (rows.length === 0) return null
|
||||
|
||||
const scores = rows.map((r) => toNumber(r.score))
|
||||
const fullScores = rows.map((r) => toNumber(r.fullScore))
|
||||
const countN = scores.length
|
||||
const sum = scores.reduce((a, b) => a + b, 0)
|
||||
const average = sum / countN
|
||||
const sorted = [...scores].sort((a, b) => a - b)
|
||||
const mid = Math.floor(countN / 2)
|
||||
const median = countN % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
|
||||
const max = sorted[countN - 1]
|
||||
const min = sorted[0]
|
||||
const variance = scores.reduce((acc, s) => acc + Math.pow(s - average, 2), 0) / countN
|
||||
const stdDev = Math.sqrt(variance)
|
||||
|
||||
let passCount = 0
|
||||
let excellentCount = 0
|
||||
for (let i = 0; i < countN; i++) {
|
||||
if (fullScores[i] <= 0) continue
|
||||
const ratio = scores[i] / fullScores[i]
|
||||
if (ratio >= 0.6) passCount++
|
||||
if (ratio >= 0.85) excellentCount++
|
||||
}
|
||||
|
||||
return {
|
||||
average: Math.round(average * 100) / 100,
|
||||
median: Math.round(median * 100) / 100,
|
||||
max,
|
||||
min,
|
||||
stdDev: Math.round(stdDev * 100) / 100,
|
||||
passRate: Math.round((passCount / countN) * 10000) / 100,
|
||||
excellentRate: Math.round((excellentCount / countN) * 10000) / 100,
|
||||
count: countN,
|
||||
}
|
||||
return computeGradeStats(rows)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -300,13 +268,13 @@ export const getStudentGradeSummary = cache(
|
||||
createdAt: r.record.createdAt.toISOString(),
|
||||
}))
|
||||
|
||||
const avg = listItems.reduce((a, b) => a + b.score, 0) / listItems.length
|
||||
const avg = computeAverageScore(listItems.map((i) => i.score))
|
||||
|
||||
return {
|
||||
studentId,
|
||||
studentName: studentName ?? "Unknown",
|
||||
records: listItems,
|
||||
averageScore: Math.round(avg * 100) / 100,
|
||||
averageScore: avg,
|
||||
rank: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@ import "server-only"
|
||||
|
||||
import { eq, inArray, sql, type SQL } from "drizzle-orm"
|
||||
|
||||
import { gradeRecords } from "@/shared/db/schema"
|
||||
import { db } from "@/shared/db"
|
||||
import { classes, gradeRecords } from "@/shared/db/schema"
|
||||
import type { DataScope } from "@/shared/types/permissions"
|
||||
|
||||
/**
|
||||
@@ -39,7 +40,16 @@ export const buildScopeClassFilter = (scope: DataScope): SQL | null => {
|
||||
? inArray(gradeRecords.classId, scope.classIds)
|
||||
: sql`1=0`
|
||||
}
|
||||
if (scope.type === "grade_managed") return sql`1=0`
|
||||
if (scope.type === "grade_managed") {
|
||||
// P2-4 修复:grade_managed scope 应返回所管年级的班级成绩记录
|
||||
// 通过子查询过滤 classId IN (SELECT id FROM classes WHERE grade_id IN (...))
|
||||
return scope.gradeIds.length > 0
|
||||
? inArray(
|
||||
gradeRecords.classId,
|
||||
db.select({ id: classes.id }).from(classes).where(inArray(classes.gradeId, scope.gradeIds))
|
||||
)
|
||||
: sql`1=0`
|
||||
}
|
||||
if (scope.type === "class_members") return null
|
||||
if (scope.type === "children") {
|
||||
return scope.childrenIds.length > 0
|
||||
|
||||
305
src/modules/grades/stats-service.ts
Normal file
305
src/modules/grades/stats-service.ts
Normal file
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* Grade statistics pure functions.
|
||||
*
|
||||
* Extracted from data-access / data-access-analytics / data-access-ranking
|
||||
* to keep data-access layer focused on DB I/O and make statistics logic
|
||||
* independently testable. All functions are pure (no side effects, no I/O).
|
||||
*/
|
||||
|
||||
import { normalize, toNumber } from "./lib/grade-utils"
|
||||
import type {
|
||||
ClassComparisonItem,
|
||||
GradeDistributionBucket,
|
||||
GradeDistributionResult,
|
||||
GradeStats,
|
||||
GradeTrendPoint,
|
||||
RankingTrendPoint,
|
||||
} from "./types"
|
||||
|
||||
/** Round to 2 decimal places. */
|
||||
const round2 = (n: number): number => Math.round(n * 100) / 100
|
||||
|
||||
/** Pass threshold (60% of full score, normalized to 60/100). */
|
||||
export const PASS_THRESHOLD = 60
|
||||
|
||||
/** Excellent threshold (85% of full score, normalized to 85/100). */
|
||||
export const EXCELLENT_THRESHOLD = 85
|
||||
|
||||
/**
|
||||
* Raw score row from DB (numeric columns may be string | number depending on driver).
|
||||
*/
|
||||
export interface RawScoreRow {
|
||||
score: unknown
|
||||
fullScore: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute aggregate stats (average/median/max/min/stdDev/passRate/excellentRate/count)
|
||||
* from a list of raw score rows. Returns null when rows is empty.
|
||||
*/
|
||||
export function computeGradeStats(rows: RawScoreRow[]): GradeStats | null {
|
||||
if (rows.length === 0) return null
|
||||
|
||||
const scores = rows.map((r) => toNumber(r.score))
|
||||
const fullScores = rows.map((r) => toNumber(r.fullScore))
|
||||
const countN = scores.length
|
||||
const sum = scores.reduce((a, b) => a + b, 0)
|
||||
const average = sum / countN
|
||||
const sorted = [...scores].sort((a, b) => a - b)
|
||||
const mid = Math.floor(countN / 2)
|
||||
const median =
|
||||
countN % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
|
||||
const max = sorted[countN - 1]
|
||||
const min = sorted[0]
|
||||
const variance =
|
||||
scores.reduce((acc, s) => acc + Math.pow(s - average, 2), 0) / countN
|
||||
const stdDev = Math.sqrt(variance)
|
||||
|
||||
let passCount = 0
|
||||
let excellentCount = 0
|
||||
for (let i = 0; i < countN; i += 1) {
|
||||
if (fullScores[i] <= 0) continue
|
||||
const ratio = scores[i] / fullScores[i]
|
||||
if (ratio >= 0.6) passCount += 1
|
||||
if (ratio >= 0.85) excellentCount += 1
|
||||
}
|
||||
|
||||
return {
|
||||
average: round2(average),
|
||||
median: round2(median),
|
||||
max,
|
||||
min,
|
||||
stdDev: round2(stdDev),
|
||||
passRate: round2((passCount / countN) * 100),
|
||||
excellentRate: round2((excellentCount / countN) * 100),
|
||||
count: countN,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute average score from a list of grade record list items.
|
||||
*/
|
||||
export function computeAverageScore(scores: number[]): number {
|
||||
if (scores.length === 0) return 0
|
||||
return round2(scores.reduce((a, b) => a + b, 0) / scores.length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a grade trend point list from raw DB rows (already ordered by date asc).
|
||||
*/
|
||||
export function buildGradeTrendPoints(
|
||||
rows: Array<{
|
||||
record: {
|
||||
createdAt: Date
|
||||
title: string
|
||||
score: unknown
|
||||
fullScore: unknown
|
||||
type: string
|
||||
}
|
||||
}>
|
||||
): GradeTrendPoint[] {
|
||||
return rows.map((r) => {
|
||||
const score = toNumber(r.record.score)
|
||||
const fullScore = toNumber(r.record.fullScore)
|
||||
return {
|
||||
date: r.record.createdAt.toISOString(),
|
||||
title: r.record.title,
|
||||
score,
|
||||
fullScore,
|
||||
normalizedScore: normalize(score, fullScore),
|
||||
type: r.record.type as GradeTrendPoint["type"],
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the average of normalized scores from a list of trend points.
|
||||
*/
|
||||
export function computeTrendAverage(points: GradeTrendPoint[]): number {
|
||||
if (points.length === 0) return 0
|
||||
const avg =
|
||||
points.reduce((acc, p) => acc + p.normalizedScore, 0) / points.length
|
||||
return round2(avg)
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute class comparison stats for a single class from raw score rows.
|
||||
*/
|
||||
export function computeClassComparisonStats(
|
||||
rows: Array<{
|
||||
score: unknown
|
||||
fullScore: unknown
|
||||
studentId: string
|
||||
}>
|
||||
): Pick<
|
||||
ClassComparisonItem,
|
||||
| "averageScore"
|
||||
| "medianScore"
|
||||
| "passRate"
|
||||
| "excellentRate"
|
||||
| "count"
|
||||
| "studentCount"
|
||||
> {
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
averageScore: 0,
|
||||
medianScore: 0,
|
||||
passRate: 0,
|
||||
excellentRate: 0,
|
||||
count: 0,
|
||||
studentCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = rows.map((r) =>
|
||||
normalize(toNumber(r.score), toNumber(r.fullScore))
|
||||
)
|
||||
const sorted = [...normalized].sort((a, b) => a - b)
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
const median =
|
||||
sorted.length % 2 === 0
|
||||
? (sorted[mid - 1] + sorted[mid]) / 2
|
||||
: sorted[mid]
|
||||
const avg = normalized.reduce((a, b) => a + b, 0) / normalized.length
|
||||
const uniqueStudents = new Set(rows.map((r) => r.studentId)).size
|
||||
|
||||
let passCount = 0
|
||||
let excellentCount = 0
|
||||
for (const s of normalized) {
|
||||
if (s >= PASS_THRESHOLD) passCount += 1
|
||||
if (s >= EXCELLENT_THRESHOLD) excellentCount += 1
|
||||
}
|
||||
|
||||
return {
|
||||
averageScore: round2(avg),
|
||||
medianScore: round2(median),
|
||||
passRate: round2((passCount / normalized.length) * 100),
|
||||
excellentRate: round2((excellentCount / normalized.length) * 100),
|
||||
count: normalized.length,
|
||||
studentCount: uniqueStudents,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute subject comparison stats for a single subject from normalized scores.
|
||||
*/
|
||||
export function computeSubjectComparisonStats(
|
||||
scores: number[]
|
||||
): Pick<
|
||||
import("./types").SubjectComparisonItem,
|
||||
"averageScore" | "medianScore" | "passRate" | "excellentRate" | "count"
|
||||
> {
|
||||
if (scores.length === 0) {
|
||||
return {
|
||||
averageScore: 0,
|
||||
medianScore: 0,
|
||||
passRate: 0,
|
||||
excellentRate: 0,
|
||||
count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = [...scores].sort((a, b) => a - b)
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
const median =
|
||||
sorted.length % 2 === 0
|
||||
? (sorted[mid - 1] + sorted[mid]) / 2
|
||||
: sorted[mid]
|
||||
const avg = scores.reduce((a, b) => a + b, 0) / scores.length
|
||||
|
||||
let passCount = 0
|
||||
let excellentCount = 0
|
||||
for (const s of scores) {
|
||||
if (s >= PASS_THRESHOLD) passCount += 1
|
||||
if (s >= EXCELLENT_THRESHOLD) excellentCount += 1
|
||||
}
|
||||
|
||||
return {
|
||||
averageScore: round2(avg),
|
||||
medianScore: round2(median),
|
||||
passRate: round2((passCount / scores.length) * 100),
|
||||
excellentRate: round2((excellentCount / scores.length) * 100),
|
||||
count: scores.length,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Default distribution buckets (90-100, 80-89, 70-79, 60-69, <60).
|
||||
*/
|
||||
export function createDefaultBuckets(): GradeDistributionBucket[] {
|
||||
return [
|
||||
{ label: "90-100", min: 90, max: 100, count: 0 },
|
||||
{ label: "80-89", min: 80, max: 89, count: 0 },
|
||||
{ label: "70-79", min: 70, max: 79, count: 0 },
|
||||
{ label: "60-69", min: 60, max: 69, count: 0 },
|
||||
{ label: "<60", min: 0, max: 59, count: 0 },
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucketize raw score rows into a grade distribution result.
|
||||
*/
|
||||
export function computeGradeDistribution(
|
||||
rows: RawScoreRow[]
|
||||
): GradeDistributionResult {
|
||||
const buckets = createDefaultBuckets()
|
||||
for (const r of rows) {
|
||||
const normalized = normalize(toNumber(r.score), toNumber(r.fullScore))
|
||||
const rounded = Math.round(normalized)
|
||||
if (rounded >= 90) buckets[0].count += 1
|
||||
else if (rounded >= 80) buckets[1].count += 1
|
||||
else if (rounded >= 70) buckets[2].count += 1
|
||||
else if (rounded >= 60) buckets[3].count += 1
|
||||
else buckets[4].count += 1
|
||||
}
|
||||
return { buckets, totalCount: rows.length }
|
||||
}
|
||||
|
||||
/**
|
||||
* Ranking trend entry for a single assessment (grouped by title).
|
||||
*/
|
||||
export interface RankingTrendEntry {
|
||||
date: Date
|
||||
entries: Array<{ studentId: string; normalized: number }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Build ranking trend points from grouped entries.
|
||||
* Returns points sorted by date ascending.
|
||||
*/
|
||||
export function buildRankingTrendPoints(
|
||||
byTitle: Map<string, RankingTrendEntry>,
|
||||
targetStudentId: string
|
||||
): RankingTrendPoint[] {
|
||||
const points: RankingTrendPoint[] = []
|
||||
for (const [title, entry] of byTitle.entries()) {
|
||||
if (entry.entries.length === 0) continue
|
||||
const sorted = [...entry.entries].sort(
|
||||
(a, b) => b.normalized - a.normalized
|
||||
)
|
||||
let rank = 0
|
||||
let studentEntry: { studentId: string; normalized: number } | null = null
|
||||
for (let i = 0; i < sorted.length; i += 1) {
|
||||
const e = sorted[i]
|
||||
if (e.studentId === targetStudentId) {
|
||||
rank = i + 1
|
||||
studentEntry = e
|
||||
break
|
||||
}
|
||||
}
|
||||
if (rank <= 0 || !studentEntry) continue
|
||||
|
||||
points.push({
|
||||
title,
|
||||
date: entry.date.toISOString(),
|
||||
score: studentEntry.normalized,
|
||||
rank,
|
||||
totalStudents: sorted.length,
|
||||
})
|
||||
}
|
||||
|
||||
points.sort(
|
||||
(a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
|
||||
)
|
||||
return points
|
||||
}
|
||||
Reference in New Issue
Block a user