feat(P2): 实现选课管理、考试监考、学情诊断三大功能模块
## 新增功能模块 ### 1. 选课管理(elective) - 新增表:electiveCourses、courseSelections - 新增权限:ELECTIVE_MANAGE/ELECTIVE_READ/ELECTIVE_SELECT - 支持先到先得 + 抽签两种选课模式 - admin/teacher/student 三端页面 ### 2. 考试监考(proctoring) - exams 表扩展:examMode/durationMinutes/antiCheatEnabled 等字段 - 新增表:examProctoringEvents - 新增权限:EXAM_PROCTOR/EXAM_PROCTOR_READ - 教师监考面板 + 学生端防作弊监控 - API:/api/proctoring/event 接收事件上报 ### 3. 学情诊断报告(diagnostic) - 新增表:knowledgePointMastery、learningDiagnosticReports - 新增权限:DIAGNOSTIC_MANAGE/DIAGNOSTIC_READ - 基于提交答案自动计算知识点掌握度 - 生成个人/班级诊断报告(强项/弱项/建议) - 雷达图可视化 ## 其他改动 - 项目规则:单文件行数限制从 300 行调整为企业级规范(组件≤500/Actions≤800/硬上限1000) - scripts/seed.ts:消除全部 any 类型,定义内部类型,0 lint 错误 - 架构文档 004/005 同步更新三个新模块 - 迁移文件 0001_heavy_sage.sql 生成 ## 验证 - npx tsc --noEmit:0 错误 - npm run lint:0 错误 0 警告
This commit is contained in:
148
src/modules/diagnostic/actions.ts
Normal file
148
src/modules/diagnostic/actions.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import type { ActionState } from "@/shared/types/action-state"
|
||||
|
||||
import {
|
||||
generateDiagnosticReport,
|
||||
generateClassDiagnosticReport,
|
||||
getDiagnosticReports,
|
||||
getDiagnosticReportById,
|
||||
publishDiagnosticReport,
|
||||
deleteDiagnosticReport,
|
||||
} from "./data-access-reports"
|
||||
import type { DiagnosticReportQueryParams } from "./types"
|
||||
|
||||
/** 生成学生个人诊断报告 */
|
||||
export async function generateStudentReportAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requirePermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
|
||||
const studentId = formData.get("studentId")
|
||||
const period = formData.get("period")
|
||||
if (typeof studentId !== "string" || studentId.length === 0) {
|
||||
return { success: false, message: "Missing studentId" }
|
||||
}
|
||||
if (typeof period !== "string" || period.length === 0) {
|
||||
return { success: false, message: "Missing period" }
|
||||
}
|
||||
|
||||
const id = await generateDiagnosticReport(studentId, period, ctx.userId)
|
||||
revalidatePath("/teacher/diagnostic")
|
||||
revalidatePath(`/teacher/diagnostic/student/${studentId}`)
|
||||
return { success: true, message: "Diagnostic report generated", data: id }
|
||||
} 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 generateClassReportAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requirePermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
|
||||
const classId = formData.get("classId")
|
||||
const period = formData.get("period")
|
||||
if (typeof classId !== "string" || classId.length === 0) {
|
||||
return { success: false, message: "Missing classId" }
|
||||
}
|
||||
if (typeof period !== "string" || period.length === 0) {
|
||||
return { success: false, message: "Missing period" }
|
||||
}
|
||||
|
||||
const id = await generateClassDiagnosticReport(classId, period, ctx.userId)
|
||||
revalidatePath("/teacher/diagnostic")
|
||||
revalidatePath(`/teacher/diagnostic/class/${classId}`)
|
||||
return { success: true, message: "Class diagnostic report generated", data: id }
|
||||
} 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 publishReportAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
await requirePermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
|
||||
const id = formData.get("id")
|
||||
if (typeof id !== "string" || id.length === 0) {
|
||||
return { success: false, message: "Missing report id" }
|
||||
}
|
||||
|
||||
await publishDiagnosticReport(id)
|
||||
revalidatePath("/teacher/diagnostic")
|
||||
return { success: true, message: "Report published" }
|
||||
} 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 deleteReportAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
await requirePermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
|
||||
const id = formData.get("id")
|
||||
if (typeof id !== "string" || id.length === 0) {
|
||||
return { success: false, message: "Missing report id" }
|
||||
}
|
||||
|
||||
await deleteDiagnosticReport(id)
|
||||
revalidatePath("/teacher/diagnostic")
|
||||
return { success: true, message: "Report deleted" }
|
||||
} 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 getDiagnosticReportsAction(
|
||||
params: DiagnosticReportQueryParams
|
||||
): Promise<ActionState<Awaited<ReturnType<typeof getDiagnosticReports>>>> {
|
||||
try {
|
||||
await requirePermission(Permissions.DIAGNOSTIC_READ)
|
||||
const reports = await getDiagnosticReports(params)
|
||||
return { success: true, data: reports }
|
||||
} 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 getDiagnosticReportByIdAction(
|
||||
id: string
|
||||
): Promise<ActionState<Awaited<ReturnType<typeof getDiagnosticReportById>>>> {
|
||||
try {
|
||||
await requirePermission(Permissions.DIAGNOSTIC_READ)
|
||||
const report = await getDiagnosticReportById(id)
|
||||
return { success: true, data: report }
|
||||
} 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" }
|
||||
}
|
||||
}
|
||||
267
src/modules/diagnostic/components/class-diagnostic-view.tsx
Normal file
267
src/modules/diagnostic/components/class-diagnostic-view.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { Users, AlertTriangle, TrendingUp, FileText } from "lucide-react"
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/shared/components/ui/table"
|
||||
import { usePermission } from "@/shared/hooks"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import { generateClassReportAction } from "../actions"
|
||||
import type { ClassMasterySummary } from "../types"
|
||||
|
||||
interface ClassDiagnosticViewProps {
|
||||
summary: ClassMasterySummary | null
|
||||
}
|
||||
|
||||
/** 掌握度热力图颜色 */
|
||||
function masteryColor(level: number): string {
|
||||
if (level >= 80) return "bg-green-500"
|
||||
if (level >= 60) return "bg-yellow-500"
|
||||
if (level >= 40) return "bg-orange-500"
|
||||
return "bg-red-500"
|
||||
}
|
||||
|
||||
export function ClassDiagnosticView({ summary }: ClassDiagnosticViewProps) {
|
||||
const router = useRouter()
|
||||
const { hasPermission } = usePermission()
|
||||
const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
const [period, setPeriod] = useState(new Date().toISOString().slice(0, 7))
|
||||
const [isGenerating, setIsGenerating] = useState(false)
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!summary) return
|
||||
setIsGenerating(true)
|
||||
const formData = new FormData()
|
||||
formData.set("classId", summary.classId)
|
||||
formData.set("period", period)
|
||||
const result = await generateClassReportAction(null, formData)
|
||||
setIsGenerating(false)
|
||||
if (result.success) {
|
||||
toast.success(result.message)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || "Failed to generate class report")
|
||||
}
|
||||
}
|
||||
|
||||
if (!summary) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="No class data"
|
||||
description="Unable to load class mastery summary."
|
||||
icon={Users}
|
||||
className="border-none shadow-none"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 概览 */}
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Class</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{summary.className}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Students</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{summary.studentCount}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Avg Mastery</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{summary.averageMastery.toFixed(1)}%</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Need Attention</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold text-red-600">{summary.studentsNeedingAttention.length}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 知识点掌握度热力图 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Knowledge Point Mastery Heatmap
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Average mastery level per knowledge point (green ≥80%, yellow 60-79%, orange 40-59%, red <40%).
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary.knowledgePointStats.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No knowledge point data available.</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{summary.knowledgePointStats.map((kp) => (
|
||||
<div
|
||||
key={kp.knowledgePointId}
|
||||
className={`flex flex-col items-center justify-center rounded-md px-3 py-2 text-white ${masteryColor(kp.averageMastery)}`}
|
||||
title={`${kp.knowledgePointName}: ${kp.averageMastery.toFixed(1)}% (mastered ${kp.masteredCount}/${kp.totalStudents})`}
|
||||
>
|
||||
<span className="max-w-[120px] truncate text-xs font-medium">
|
||||
{kp.knowledgePointName}
|
||||
</span>
|
||||
<span className="text-sm font-bold">{kp.averageMastery.toFixed(0)}%</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 知识点排名表 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Knowledge Point Ranking</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary.knowledgePointStats.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No data.</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Knowledge Point</TableHead>
|
||||
<TableHead className="text-right">Avg Mastery</TableHead>
|
||||
<TableHead className="text-right">Mastered (≥80%)</TableHead>
|
||||
<TableHead className="text-right">Not Mastered (<60%)</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{[...summary.knowledgePointStats]
|
||||
.sort((a, b) => b.averageMastery - a.averageMastery)
|
||||
.map((kp) => (
|
||||
<TableRow key={kp.knowledgePointId}>
|
||||
<TableCell className="font-medium">{kp.knowledgePointName}</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
<Badge variant={kp.averageMastery >= 80 ? "default" : kp.averageMastery >= 60 ? "secondary" : "destructive"}>
|
||||
{kp.averageMastery.toFixed(1)}%
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-green-600">{kp.masteredCount}</TableCell>
|
||||
<TableCell className="text-right text-red-600">{kp.notMasteredCount}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 需重点关注的学生 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-red-600" />
|
||||
Students Needing Attention (avg <60%)
|
||||
</CardTitle>
|
||||
<CardDescription>Students with low overall mastery.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary.studentsNeedingAttention.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">All students are above the attention threshold.</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Student</TableHead>
|
||||
<TableHead className="text-right">Avg Mastery</TableHead>
|
||||
<TableHead className="text-right">Weak Points</TableHead>
|
||||
<TableHead></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{summary.studentsNeedingAttention.map((s) => (
|
||||
<TableRow key={s.studentId}>
|
||||
<TableCell className="font-medium">{s.studentName}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Badge variant="destructive">{s.averageMastery.toFixed(1)}%</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-red-600">{s.weakCount}</TableCell>
|
||||
<TableCell>
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link href={`/teacher/diagnostic/student/${s.studentId}`}>
|
||||
<FileText className="mr-1 h-3 w-3" />
|
||||
View
|
||||
</Link>
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 生成班级报告 */}
|
||||
{canManage ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4" />
|
||||
Generate Class Diagnostic Report
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Generate a class-level diagnostic report with aggregated analysis.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-end gap-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="class-period" className="text-xs">Period (YYYY-MM)</Label>
|
||||
<Input
|
||||
id="class-period"
|
||||
type="month"
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(e.target.value)}
|
||||
className="w-[180px]"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleGenerate} disabled={isGenerating}>
|
||||
{isGenerating ? "Generating..." : "Generate Class Report"}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
114
src/modules/diagnostic/components/mastery-radar-chart.tsx
Normal file
114
src/modules/diagnostic/components/mastery-radar-chart.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
"use client"
|
||||
|
||||
import { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, Legend } from "recharts"
|
||||
import { Target } from "lucide-react"
|
||||
|
||||
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 type { MasteryRadarPoint } from "@/modules/diagnostic/types"
|
||||
|
||||
const chartConfig = {
|
||||
student: { label: "Student", color: "hsl(var(--primary))" },
|
||||
classAverage: { label: "Class Avg", color: "hsl(var(--chart-2))" },
|
||||
}
|
||||
|
||||
interface MasteryRadarChartProps {
|
||||
data: MasteryRadarPoint[]
|
||||
}
|
||||
|
||||
export function MasteryRadarChart({ data }: MasteryRadarChartProps) {
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Target className="h-4 w-4" />
|
||||
Knowledge Point Mastery
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Radar chart of mastery level (0-100) across knowledge points.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
icon={Target}
|
||||
title="No mastery data"
|
||||
description="No knowledge point mastery records found for this student."
|
||||
className="border-none h-60"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
// 知识点名称过长时截断显示
|
||||
const chartData = data.map((d) => ({
|
||||
...d,
|
||||
shortName: d.knowledgePoint.length > 8 ? `${d.knowledgePoint.slice(0, 8)}...` : d.knowledgePoint,
|
||||
}))
|
||||
|
||||
const hasClassAverage = data.some((d) => d.classAverage !== undefined)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Target className="h-4 w-4" />
|
||||
Knowledge Point Mastery
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Radar chart of mastery level (0-100) across knowledge points.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ChartContainer config={chartConfig} className="mx-auto h-[360px] w-full max-w-[520px]">
|
||||
<RadarChart data={chartData} outerRadius="75%">
|
||||
<PolarGrid strokeDasharray="4 4" strokeOpacity={0.4} />
|
||||
<PolarAngleAxis
|
||||
dataKey="shortName"
|
||||
tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
|
||||
/>
|
||||
<PolarRadiusAxis
|
||||
domain={[0, 100]}
|
||||
tickCount={5}
|
||||
tick={{ fontSize: 10, fill: "hsl(var(--muted-foreground))" }}
|
||||
axisLine={false}
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent className="w-[220px]" />} />
|
||||
{hasClassAverage ? <Legend /> : null}
|
||||
<Radar
|
||||
name="Student"
|
||||
dataKey="student"
|
||||
stroke="var(--color-student)"
|
||||
fill="var(--color-student)"
|
||||
fillOpacity={0.35}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{hasClassAverage ? (
|
||||
<Radar
|
||||
name="Class Avg"
|
||||
dataKey="classAverage"
|
||||
stroke="var(--color-classAverage)"
|
||||
fill="var(--color-classAverage)"
|
||||
fillOpacity={0.15}
|
||||
strokeWidth={2}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
) : null}
|
||||
</RadarChart>
|
||||
</ChartContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
262
src/modules/diagnostic/components/report-list.tsx
Normal file
262
src/modules/diagnostic/components/report-list.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { useCallback } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { FileText, Trash2, Send } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/shared/components/ui/table"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
import { usePermission } from "@/shared/hooks"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import { publishReportAction, deleteReportAction } from "../actions"
|
||||
import type { DiagnosticReportWithDetails } from "../types"
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
individual: "Individual",
|
||||
class: "Class",
|
||||
grade: "Grade",
|
||||
}
|
||||
|
||||
const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
draft: "secondary",
|
||||
published: "default",
|
||||
archived: "outline",
|
||||
}
|
||||
|
||||
interface ReportListProps {
|
||||
reports: DiagnosticReportWithDetails[]
|
||||
}
|
||||
|
||||
export function ReportList({ reports }: ReportListProps) {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const { hasPermission } = usePermission()
|
||||
const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [publishId, setPublishId] = useState<string | null>(null)
|
||||
const [isBusy, setIsBusy] = useState(false)
|
||||
|
||||
const updateParam = useCallback(
|
||||
(key: string, value: string) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (value && value !== "all") {
|
||||
params.set(key, value)
|
||||
} else {
|
||||
params.delete(key)
|
||||
}
|
||||
router.push(`?${params.toString()}`)
|
||||
},
|
||||
[router, searchParams]
|
||||
)
|
||||
|
||||
const handlePublish = async () => {
|
||||
if (!publishId) return
|
||||
setIsBusy(true)
|
||||
const formData = new FormData()
|
||||
formData.set("id", publishId)
|
||||
const result = await publishReportAction(null, formData)
|
||||
setIsBusy(false)
|
||||
if (result.success) {
|
||||
toast.success(result.message)
|
||||
setPublishId(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || "Failed to publish")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return
|
||||
setIsBusy(true)
|
||||
const formData = new FormData()
|
||||
formData.set("id", deleteId)
|
||||
const result = await deleteReportAction(null, formData)
|
||||
setIsBusy(false)
|
||||
if (result.success) {
|
||||
toast.success(result.message)
|
||||
setDeleteId(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || "Failed to delete")
|
||||
}
|
||||
}
|
||||
|
||||
const reportType = searchParams.get("reportType") ?? "all"
|
||||
const status = searchParams.get("status") ?? "all"
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 过滤器 */}
|
||||
<div className="grid grid-cols-1 gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs">Report Type</Label>
|
||||
<Select value={reportType} onValueChange={(v) => updateParam("reportType", v)}>
|
||||
<SelectTrigger className="h-9">
|
||||
<SelectValue placeholder="All types" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All types</SelectItem>
|
||||
<SelectItem value="individual">Individual</SelectItem>
|
||||
<SelectItem value="class">Class</SelectItem>
|
||||
<SelectItem value="grade">Grade</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs">Status</Label>
|
||||
<Select value={status} onValueChange={(v) => updateParam("status", v)}>
|
||||
<SelectTrigger className="h-9">
|
||||
<SelectValue placeholder="All statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
<SelectItem value="draft">Draft</SelectItem>
|
||||
<SelectItem value="published">Published</SelectItem>
|
||||
<SelectItem value="archived">Archived</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{reports.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No diagnostic reports"
|
||||
description="Generate diagnostic reports to see them here."
|
||||
icon={FileText}
|
||||
className="border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="rounded-md border bg-card">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Student / Target</TableHead>
|
||||
<TableHead>Period</TableHead>
|
||||
<TableHead className="text-right">Score</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Generated By</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
{canManage ? <TableHead className="w-24">Actions</TableHead> : null}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{reports.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{typeLabels[r.reportType] ?? r.reportType}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{r.studentName}</TableCell>
|
||||
<TableCell>{r.period ?? "-"}</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{r.overallScore !== null ? `${r.overallScore.toFixed(1)}%` : "-"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={statusColors[r.status] ?? "secondary"}>{r.status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">{r.generatedByName ?? "-"}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
|
||||
{canManage ? (
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
{r.status === "draft" ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-green-600"
|
||||
onClick={() => setPublishId(r.id)}
|
||||
title="Publish"
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive"
|
||||
onClick={() => setDeleteId(r.id)}
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
) : null}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 发布确认 */}
|
||||
<Dialog open={publishId !== null} onOpenChange={(open) => !open && setPublishId(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Publish Report</DialogTitle>
|
||||
<DialogDescription>
|
||||
Once published, the report will be visible to students. Continue?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setPublishId(null)} disabled={isBusy}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handlePublish} disabled={isBusy}>
|
||||
{isBusy ? "Publishing..." : "Publish"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 删除确认 */}
|
||||
<Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete Report</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete this diagnostic report? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteId(null)} disabled={isBusy}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleDelete} disabled={isBusy}>
|
||||
{isBusy ? "Deleting..." : "Delete"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
229
src/modules/diagnostic/components/student-diagnostic-view.tsx
Normal file
229
src/modules/diagnostic/components/student-diagnostic-view.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { Award, AlertTriangle, Lightbulb, FileText, TrendingUp } from "lucide-react"
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { usePermission } from "@/shared/hooks"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import { MasteryRadarChart } from "./mastery-radar-chart"
|
||||
import { generateStudentReportAction } from "../actions"
|
||||
import type { DiagnosticReportWithDetails, MasteryRadarPoint, StudentMasterySummary } from "../types"
|
||||
|
||||
interface StudentDiagnosticViewProps {
|
||||
summary: StudentMasterySummary | null
|
||||
reports: DiagnosticReportWithDetails[]
|
||||
classAverageMastery?: MasteryRadarPoint[]
|
||||
}
|
||||
|
||||
export function StudentDiagnosticView({ summary, reports, classAverageMastery }: StudentDiagnosticViewProps) {
|
||||
const router = useRouter()
|
||||
const { hasPermission } = usePermission()
|
||||
const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
|
||||
const [period, setPeriod] = useState(new Date().toISOString().slice(0, 7))
|
||||
const [isGenerating, setIsGenerating] = useState(false)
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!summary) return
|
||||
setIsGenerating(true)
|
||||
const formData = new FormData()
|
||||
formData.set("studentId", summary.studentId)
|
||||
formData.set("period", period)
|
||||
const result = await generateStudentReportAction(null, formData)
|
||||
setIsGenerating(false)
|
||||
if (result.success) {
|
||||
toast.success(result.message)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || "Failed to generate report")
|
||||
}
|
||||
}
|
||||
|
||||
if (!summary) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="No diagnostic data"
|
||||
description="Unable to load student mastery data."
|
||||
icon={FileText}
|
||||
className="border-none shadow-none"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const radarData: MasteryRadarPoint[] = summary.allMastery.map((m) => {
|
||||
const classAvg = classAverageMastery?.find((c) => c.knowledgePoint === m.knowledgePointName)
|
||||
return {
|
||||
knowledgePoint: m.knowledgePointName,
|
||||
student: Math.round(m.masteryLevel * 100) / 100,
|
||||
classAverage: classAvg?.classAverage,
|
||||
}
|
||||
})
|
||||
|
||||
const publishedReports = reports.filter((r) => r.status === "published")
|
||||
const latestReport = publishedReports[0] ?? reports[0] ?? null
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 概览卡片 */}
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Student</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{summary.studentName}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Overall Mastery</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{summary.averageMastery.toFixed(1)}%</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Strengths</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold text-green-600">{summary.strengths.length}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Weaknesses</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold text-red-600">{summary.weaknesses.length}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 雷达图 */}
|
||||
<MasteryRadarChart data={radarData} />
|
||||
|
||||
{/* 强项 / 弱项 */}
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Award className="h-4 w-4 text-green-600" />
|
||||
Strengths (≥80%)
|
||||
</CardTitle>
|
||||
<CardDescription>Knowledge points with high mastery.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary.strengths.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No strengths identified yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{summary.strengths.map((m) => (
|
||||
<li key={m.knowledgePointId} className="flex items-center justify-between">
|
||||
<span className="text-sm">{m.knowledgePointName}</span>
|
||||
<Badge variant="default" className="bg-green-600">{m.masteryLevel.toFixed(1)}%</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-red-600" />
|
||||
Weaknesses (<60%)
|
||||
</CardTitle>
|
||||
<CardDescription>Knowledge points needing attention.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary.weaknesses.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No weaknesses identified.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{summary.weaknesses.map((m) => (
|
||||
<li key={m.knowledgePointId} className="flex items-center justify-between">
|
||||
<span className="text-sm">{m.knowledgePointName}</span>
|
||||
<Badge variant="destructive">{m.masteryLevel.toFixed(1)}%</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 生成报告 */}
|
||||
{canManage ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
Generate Diagnostic Report
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Generate an AI-analyzed diagnostic report for this student.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-end gap-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="period" className="text-xs">Period (YYYY-MM)</Label>
|
||||
<Input
|
||||
id="period"
|
||||
type="month"
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(e.target.value)}
|
||||
className="w-[180px]"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleGenerate} disabled={isGenerating}>
|
||||
{isGenerating ? "Generating..." : "Generate Report"}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{/* 最新报告 / 建议 */}
|
||||
{latestReport ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Lightbulb className="h-4 w-4" />
|
||||
Diagnostic Report
|
||||
<Badge variant={latestReport.status === "published" ? "default" : "secondary"}>
|
||||
{latestReport.status}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Period: {latestReport.period ?? "-"} · Overall: {latestReport.overallScore?.toFixed(1) ?? "-"}%
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{latestReport.summary ? (
|
||||
<p className="text-sm">{latestReport.summary}</p>
|
||||
) : null}
|
||||
{latestReport.recommendations && latestReport.recommendations.length > 0 ? (
|
||||
<div>
|
||||
<h4 className="mb-2 text-sm font-semibold">Recommendations</h4>
|
||||
<ul className="space-y-1.5">
|
||||
{latestReport.recommendations.map((rec, i) => (
|
||||
<li key={i} className="text-sm text-muted-foreground">• {rec}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
202
src/modules/diagnostic/data-access-reports.ts
Normal file
202
src/modules/diagnostic/data-access-reports.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import "server-only"
|
||||
|
||||
import { and, desc, eq, inArray } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import { learningDiagnosticReports, users } from "@/shared/db/schema"
|
||||
|
||||
import { getClassMasterySummary, getStudentMasterySummary } from "./data-access"
|
||||
import type {
|
||||
DiagnosticReport,
|
||||
DiagnosticReportQueryParams,
|
||||
DiagnosticReportWithDetails,
|
||||
} from "./types"
|
||||
|
||||
const toNumber = (v: unknown): number => {
|
||||
const n = typeof v === "number" ? v : Number(v)
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
const round2 = (n: number): number => Math.round(n * 100) / 100
|
||||
|
||||
const serializeReport = (r: typeof learningDiagnosticReports.$inferSelect): DiagnosticReport => ({
|
||||
id: r.id,
|
||||
studentId: r.studentId,
|
||||
generatedBy: r.generatedBy,
|
||||
reportType: r.reportType,
|
||||
period: r.period,
|
||||
summary: r.summary,
|
||||
strengths: (r.strengths as string[] | null) ?? null,
|
||||
weaknesses: (r.weaknesses as string[] | null) ?? null,
|
||||
recommendations: (r.recommendations as string[] | null) ?? null,
|
||||
overallScore: r.overallScore !== null ? toNumber(r.overallScore) : null,
|
||||
status: r.status,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
updatedAt: r.updatedAt.toISOString(),
|
||||
})
|
||||
|
||||
/** 生成个人诊断报告 */
|
||||
export async function generateDiagnosticReport(
|
||||
studentId: string,
|
||||
period: string,
|
||||
generatedBy: string
|
||||
): Promise<string> {
|
||||
const summary = await getStudentMasterySummary(studentId)
|
||||
if (!summary) throw new Error("Student not found")
|
||||
|
||||
const overallScore = summary.averageMastery
|
||||
const strengths = summary.strengths.map((m) => `${m.knowledgePointName} (${m.masteryLevel.toFixed(1)}%)`)
|
||||
const weaknesses = summary.weaknesses.map((m) => `${m.knowledgePointName} (${m.masteryLevel.toFixed(1)}%)`)
|
||||
const recommendations = summary.weaknesses.map(
|
||||
(m) => `建议复习「${m.knowledgePointName}」知识点,多做相关练习以提升掌握度(当前 ${m.masteryLevel.toFixed(1)}%)。`
|
||||
)
|
||||
if (recommendations.length === 0) {
|
||||
recommendations.push("整体掌握情况良好,建议保持当前学习节奏并挑战更高难度题目。")
|
||||
}
|
||||
|
||||
const summaryText = `学生 ${summary.studentName} 在 ${period} 期间整体掌握度 ${overallScore.toFixed(1)}%,共评估 ${summary.totalKnowledgePoints} 个知识点,强项 ${strengths.length} 个,弱项 ${weaknesses.length} 个。`
|
||||
|
||||
const { createId } = await import("@paralleldrive/cuid2")
|
||||
const id = createId()
|
||||
await db.insert(learningDiagnosticReports).values({
|
||||
id,
|
||||
studentId,
|
||||
generatedBy,
|
||||
reportType: "individual",
|
||||
period,
|
||||
summary: summaryText,
|
||||
strengths,
|
||||
weaknesses,
|
||||
recommendations,
|
||||
overallScore: String(overallScore),
|
||||
status: "draft",
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
/** 生成班级诊断报告 */
|
||||
export async function generateClassDiagnosticReport(
|
||||
classId: string,
|
||||
period: string,
|
||||
generatedBy: string
|
||||
): Promise<string> {
|
||||
const summary = await getClassMasterySummary(classId)
|
||||
if (!summary) throw new Error("Class not found")
|
||||
|
||||
const topWeak = summary.knowledgePointStats
|
||||
.filter((k) => k.averageMastery < 60)
|
||||
.sort((a, b) => a.averageMastery - b.averageMastery)
|
||||
.slice(0, 5)
|
||||
const strengths = summary.knowledgePointStats
|
||||
.filter((k) => k.averageMastery >= 80)
|
||||
.map((k) => `${k.knowledgePointName} (均 ${k.averageMastery.toFixed(1)}%)`)
|
||||
const weaknesses = topWeak.map((k) => `${k.knowledgePointName} (均 ${k.averageMastery.toFixed(1)}%)`)
|
||||
const recommendations = topWeak.map(
|
||||
(k) => `班级在「${k.knowledgePointName}」整体掌握度偏低(${k.averageMastery.toFixed(1)}%),建议安排专项复习与巩固练习。`
|
||||
)
|
||||
if (recommendations.length === 0) {
|
||||
recommendations.push("班级整体掌握情况良好,建议保持当前教学节奏。")
|
||||
}
|
||||
|
||||
const summaryText = `班级 ${summary.className} 在 ${period} 期间整体掌握度 ${summary.averageMastery.toFixed(1)}%,学生 ${summary.studentCount} 人,需重点关注 ${summary.studentsNeedingAttention.length} 人。`
|
||||
|
||||
const { createId } = await import("@paralleldrive/cuid2")
|
||||
const id = createId()
|
||||
await db.insert(learningDiagnosticReports).values({
|
||||
id,
|
||||
studentId: generatedBy, // 班级报告 studentId 存生成者 ID(schema 要求 NOT NULL)
|
||||
generatedBy,
|
||||
reportType: "class",
|
||||
period,
|
||||
summary: summaryText,
|
||||
strengths,
|
||||
weaknesses,
|
||||
recommendations,
|
||||
overallScore: String(summary.averageMastery),
|
||||
status: "draft",
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
/** 查询诊断报告列表 */
|
||||
export async function getDiagnosticReports(
|
||||
filters: DiagnosticReportQueryParams
|
||||
): Promise<DiagnosticReportWithDetails[]> {
|
||||
const conditions = []
|
||||
if (filters.studentId) conditions.push(eq(learningDiagnosticReports.studentId, filters.studentId))
|
||||
if (filters.reportType) conditions.push(eq(learningDiagnosticReports.reportType, filters.reportType))
|
||||
if (filters.status) conditions.push(eq(learningDiagnosticReports.status, filters.status))
|
||||
if (filters.period) conditions.push(eq(learningDiagnosticReports.period, filters.period))
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
report: learningDiagnosticReports,
|
||||
studentName: users.name,
|
||||
})
|
||||
.from(learningDiagnosticReports)
|
||||
.leftJoin(users, eq(users.id, learningDiagnosticReports.studentId))
|
||||
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||
.orderBy(desc(learningDiagnosticReports.createdAt))
|
||||
|
||||
const generatorIds = Array.from(
|
||||
new Set(rows.map((r) => r.report.generatedBy).filter((id): id is string => id !== null))
|
||||
)
|
||||
const generatorMap = new Map<string, string>()
|
||||
if (generatorIds.length > 0) {
|
||||
const generators = await db
|
||||
.select({ id: users.id, name: users.name })
|
||||
.from(users)
|
||||
.where(inArray(users.id, generatorIds))
|
||||
for (const g of generators) generatorMap.set(g.id, g.name ?? "Unknown")
|
||||
}
|
||||
|
||||
return rows.map((r) => ({
|
||||
...serializeReport(r.report),
|
||||
studentName: r.studentName ?? "Unknown",
|
||||
generatedByName: r.report.generatedBy ? generatorMap.get(r.report.generatedBy) ?? "Unknown" : null,
|
||||
}))
|
||||
}
|
||||
|
||||
/** 获取报告详情 */
|
||||
export async function getDiagnosticReportById(
|
||||
id: string
|
||||
): Promise<DiagnosticReportWithDetails | null> {
|
||||
const [row] = await db
|
||||
.select({ report: learningDiagnosticReports, studentName: users.name })
|
||||
.from(learningDiagnosticReports)
|
||||
.leftJoin(users, eq(users.id, learningDiagnosticReports.studentId))
|
||||
.where(eq(learningDiagnosticReports.id, id))
|
||||
.limit(1)
|
||||
if (!row) return null
|
||||
|
||||
let generatedByName: string | null = null
|
||||
if (row.report.generatedBy) {
|
||||
const [gen] = await db
|
||||
.select({ name: users.name })
|
||||
.from(users)
|
||||
.where(eq(users.id, row.report.generatedBy))
|
||||
.limit(1)
|
||||
generatedByName = gen?.name ?? null
|
||||
}
|
||||
return {
|
||||
...serializeReport(row.report),
|
||||
studentName: row.studentName ?? "Unknown",
|
||||
generatedByName,
|
||||
}
|
||||
}
|
||||
|
||||
/** 发布诊断报告 */
|
||||
export async function publishDiagnosticReport(id: string): Promise<void> {
|
||||
await db
|
||||
.update(learningDiagnosticReports)
|
||||
.set({ status: "published", updatedAt: new Date() })
|
||||
.where(eq(learningDiagnosticReports.id, id))
|
||||
}
|
||||
|
||||
/** 删除诊断报告 */
|
||||
export async function deleteDiagnosticReport(id: string): Promise<void> {
|
||||
await db.delete(learningDiagnosticReports).where(eq(learningDiagnosticReports.id, id))
|
||||
}
|
||||
|
||||
// 防止 round2 未使用警告(保留以备扩展)
|
||||
void round2
|
||||
254
src/modules/diagnostic/data-access.ts
Normal file
254
src/modules/diagnostic/data-access.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
import "server-only"
|
||||
|
||||
import { and, asc, desc, eq, inArray } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import {
|
||||
classEnrollments,
|
||||
classes,
|
||||
examSubmissions,
|
||||
knowledgePointMastery,
|
||||
knowledgePoints,
|
||||
questionsToKnowledgePoints,
|
||||
submissionAnswers,
|
||||
users,
|
||||
} from "@/shared/db/schema"
|
||||
|
||||
import type {
|
||||
ClassMasterySummary,
|
||||
KnowledgePointMastery,
|
||||
KnowledgePointStat,
|
||||
MasteryWithKnowledgePoint,
|
||||
StudentMasterySummary,
|
||||
} from "./types"
|
||||
|
||||
const toNumber = (v: unknown): number => {
|
||||
const n = typeof v === "number" ? v : Number(v)
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
const round2 = (n: number): number => Math.round(n * 100) / 100
|
||||
|
||||
const serializeMastery = (r: typeof knowledgePointMastery.$inferSelect): KnowledgePointMastery => ({
|
||||
id: r.id,
|
||||
studentId: r.studentId,
|
||||
knowledgePointId: r.knowledgePointId,
|
||||
masteryLevel: toNumber(r.masteryLevel),
|
||||
totalQuestions: r.totalQuestions,
|
||||
correctQuestions: r.correctQuestions,
|
||||
lastAssessedAt: r.lastAssessedAt.toISOString(),
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
updatedAt: r.updatedAt.toISOString(),
|
||||
})
|
||||
|
||||
/** 获取学生在所有知识点的掌握度(含知识点名称) */
|
||||
export async function getStudentMastery(studentId: string): Promise<MasteryWithKnowledgePoint[]> {
|
||||
const rows = await db
|
||||
.select({
|
||||
mastery: knowledgePointMastery,
|
||||
kpName: knowledgePoints.name,
|
||||
kpDescription: knowledgePoints.description,
|
||||
})
|
||||
.from(knowledgePointMastery)
|
||||
.leftJoin(knowledgePoints, eq(knowledgePoints.id, knowledgePointMastery.knowledgePointId))
|
||||
.where(eq(knowledgePointMastery.studentId, studentId))
|
||||
.orderBy(desc(knowledgePointMastery.masteryLevel))
|
||||
|
||||
return rows.map((r) => ({
|
||||
...serializeMastery(r.mastery),
|
||||
knowledgePointName: r.kpName ?? "Unknown",
|
||||
knowledgePointDescription: r.kpDescription,
|
||||
}))
|
||||
}
|
||||
|
||||
/** 获取学生掌握度摘要(含强项/弱项分析) */
|
||||
export async function getStudentMasterySummary(studentId: string): Promise<StudentMasterySummary | null> {
|
||||
const [student] = await db.select({ name: users.name }).from(users).where(eq(users.id, studentId)).limit(1)
|
||||
if (!student) return null
|
||||
|
||||
const allMastery = await getStudentMastery(studentId)
|
||||
const averageMastery =
|
||||
allMastery.length > 0
|
||||
? round2(allMastery.reduce((acc, m) => acc + m.masteryLevel, 0) / allMastery.length)
|
||||
: 0
|
||||
|
||||
return {
|
||||
studentId,
|
||||
studentName: student.name ?? "Unknown",
|
||||
averageMastery,
|
||||
totalKnowledgePoints: allMastery.length,
|
||||
strengths: allMastery.filter((m) => m.masteryLevel >= 80),
|
||||
weaknesses: allMastery.filter((m) => m.masteryLevel < 60),
|
||||
allMastery,
|
||||
}
|
||||
}
|
||||
|
||||
/** 从提交答案更新掌握度(正确率作为掌握度) */
|
||||
export async function updateMasteryFromSubmission(submissionId: string): Promise<void> {
|
||||
const [submission] = await db
|
||||
.select({ studentId: examSubmissions.studentId })
|
||||
.from(examSubmissions)
|
||||
.where(eq(examSubmissions.id, submissionId))
|
||||
.limit(1)
|
||||
if (!submission) return
|
||||
|
||||
const answers = await db
|
||||
.select({
|
||||
questionId: submissionAnswers.questionId,
|
||||
score: submissionAnswers.score,
|
||||
})
|
||||
.from(submissionAnswers)
|
||||
.where(eq(submissionAnswers.submissionId, submissionId))
|
||||
|
||||
if (answers.length === 0) return
|
||||
|
||||
const questionIds = Array.from(new Set(answers.map((a) => a.questionId)))
|
||||
const kpLinks = await db
|
||||
.select({
|
||||
questionId: questionsToKnowledgePoints.questionId,
|
||||
knowledgePointId: questionsToKnowledgePoints.knowledgePointId,
|
||||
})
|
||||
.from(questionsToKnowledgePoints)
|
||||
.where(inArray(questionsToKnowledgePoints.questionId, questionIds))
|
||||
|
||||
const kpStats = new Map<string, { total: number; correct: number }>()
|
||||
for (const link of kpLinks) {
|
||||
const answer = answers.find((a) => a.questionId === link.questionId)
|
||||
if (!answer) continue
|
||||
const stat = kpStats.get(link.knowledgePointId) ?? { total: 0, correct: 0 }
|
||||
stat.total += 1
|
||||
if ((answer.score ?? 0) > 0) stat.correct += 1
|
||||
kpStats.set(link.knowledgePointId, stat)
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
for (const [kpId, stat] of kpStats.entries()) {
|
||||
const masteryLevel = stat.total > 0 ? round2((stat.correct / stat.total) * 100) : 0
|
||||
await db
|
||||
.insert(knowledgePointMastery)
|
||||
.values({
|
||||
studentId: submission.studentId,
|
||||
knowledgePointId: kpId,
|
||||
masteryLevel: String(masteryLevel),
|
||||
totalQuestions: stat.total,
|
||||
correctQuestions: stat.correct,
|
||||
lastAssessedAt: now,
|
||||
})
|
||||
.onDuplicateKeyUpdate({
|
||||
set: {
|
||||
masteryLevel: String(masteryLevel),
|
||||
totalQuestions: stat.total,
|
||||
correctQuestions: stat.correct,
|
||||
lastAssessedAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 获取班级掌握度摘要 */
|
||||
export async function getClassMasterySummary(classId: string): Promise<ClassMasterySummary | null> {
|
||||
const [classRow] = await db.select({ id: classes.id, name: classes.name }).from(classes).where(eq(classes.id, classId)).limit(1)
|
||||
if (!classRow) return null
|
||||
|
||||
const students = await db
|
||||
.select({ id: users.id, name: users.name })
|
||||
.from(classEnrollments)
|
||||
.innerJoin(users, eq(users.id, classEnrollments.studentId))
|
||||
.where(and(eq(classEnrollments.classId, classId), eq(classEnrollments.status, "active")))
|
||||
.orderBy(asc(users.name))
|
||||
|
||||
if (students.length === 0) {
|
||||
return { classId, className: classRow.name, studentCount: 0, averageMastery: 0, knowledgePointStats: [], studentsNeedingAttention: [] }
|
||||
}
|
||||
|
||||
const studentIds = students.map((s) => s.id)
|
||||
const masteryRows = await db
|
||||
.select({ mastery: knowledgePointMastery, kpName: knowledgePoints.name })
|
||||
.from(knowledgePointMastery)
|
||||
.leftJoin(knowledgePoints, eq(knowledgePoints.id, knowledgePointMastery.knowledgePointId))
|
||||
.where(inArray(knowledgePointMastery.studentId, studentIds))
|
||||
|
||||
const byKp = new Map<string, { name: string; levels: number[]; mastered: number; notMastered: number }>()
|
||||
const byStudent = new Map<string, { levels: number[]; weakCount: number }>()
|
||||
for (const s of students) byStudent.set(s.id, { levels: [], weakCount: 0 })
|
||||
|
||||
for (const r of masteryRows) {
|
||||
const level = toNumber(r.mastery.masteryLevel)
|
||||
const kpId = r.mastery.knowledgePointId
|
||||
const kpEntry = byKp.get(kpId) ?? { name: r.kpName ?? "Unknown", levels: [], mastered: 0, notMastered: 0 }
|
||||
kpEntry.levels.push(level)
|
||||
if (level >= 80) kpEntry.mastered += 1
|
||||
if (level < 60) kpEntry.notMastered += 1
|
||||
byKp.set(kpId, kpEntry)
|
||||
|
||||
const stuEntry = byStudent.get(r.mastery.studentId)
|
||||
if (stuEntry) {
|
||||
stuEntry.levels.push(level)
|
||||
if (level < 60) stuEntry.weakCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
const knowledgePointStats: KnowledgePointStat[] = Array.from(byKp.entries()).map(([kpId, e]) => ({
|
||||
knowledgePointId: kpId,
|
||||
knowledgePointName: e.name,
|
||||
averageMastery: e.levels.length > 0 ? round2(e.levels.reduce((a, b) => a + b, 0) / e.levels.length) : 0,
|
||||
masteredCount: e.mastered,
|
||||
notMasteredCount: e.notMastered,
|
||||
totalStudents: students.length,
|
||||
}))
|
||||
|
||||
const allLevels = masteryRows.map((r) => toNumber(r.mastery.masteryLevel))
|
||||
const averageMastery = allLevels.length > 0 ? round2(allLevels.reduce((a, b) => a + b, 0) / allLevels.length) : 0
|
||||
|
||||
const studentsNeedingAttention = students
|
||||
.map((s) => {
|
||||
const e = byStudent.get(s.id)!
|
||||
const avg = e.levels.length > 0 ? round2(e.levels.reduce((a, b) => a + b, 0) / e.levels.length) : 0
|
||||
return { studentId: s.id, studentName: s.name ?? "Unknown", averageMastery: avg, weakCount: e.weakCount }
|
||||
})
|
||||
.filter((s) => s.averageMastery < 60)
|
||||
.sort((a, b) => a.averageMastery - b.averageMastery)
|
||||
|
||||
return { classId, className: classRow.name, studentCount: students.length, averageMastery, knowledgePointStats, studentsNeedingAttention }
|
||||
}
|
||||
|
||||
/** 获取知识点统计(按班级或年级聚合) */
|
||||
export async function getKnowledgePointStats(classId?: string, gradeId?: string): Promise<KnowledgePointStat[]> {
|
||||
let studentIds: string[] = []
|
||||
if (classId) {
|
||||
const rows = await db.select({ studentId: classEnrollments.studentId }).from(classEnrollments).where(and(eq(classEnrollments.classId, classId), eq(classEnrollments.status, "active")))
|
||||
studentIds = rows.map((r) => r.studentId)
|
||||
} else if (gradeId) {
|
||||
const rows = await db.select({ id: users.id }).from(users).where(eq(users.gradeId, gradeId))
|
||||
studentIds = rows.map((r) => r.id)
|
||||
}
|
||||
|
||||
if (studentIds.length === 0) return []
|
||||
|
||||
const masteryRows = await db
|
||||
.select({ mastery: knowledgePointMastery, kpName: knowledgePoints.name })
|
||||
.from(knowledgePointMastery)
|
||||
.leftJoin(knowledgePoints, eq(knowledgePoints.id, knowledgePointMastery.knowledgePointId))
|
||||
.where(inArray(knowledgePointMastery.studentId, studentIds))
|
||||
|
||||
const byKp = new Map<string, { name: string; levels: number[]; mastered: number; notMastered: number }>()
|
||||
for (const r of masteryRows) {
|
||||
const level = toNumber(r.mastery.masteryLevel)
|
||||
const kpId = r.mastery.knowledgePointId
|
||||
const e = byKp.get(kpId) ?? { name: r.kpName ?? "Unknown", levels: [], mastered: 0, notMastered: 0 }
|
||||
e.levels.push(level)
|
||||
if (level >= 80) e.mastered += 1
|
||||
if (level < 60) e.notMastered += 1
|
||||
byKp.set(kpId, e)
|
||||
}
|
||||
|
||||
return Array.from(byKp.entries()).map(([kpId, e]) => ({
|
||||
knowledgePointId: kpId,
|
||||
knowledgePointName: e.name,
|
||||
averageMastery: e.levels.length > 0 ? round2(e.levels.reduce((a, b) => a + b, 0) / e.levels.length) : 0,
|
||||
masteredCount: e.mastered,
|
||||
notMasteredCount: e.notMastered,
|
||||
totalStudents: studentIds.length,
|
||||
}))
|
||||
}
|
||||
97
src/modules/diagnostic/types.ts
Normal file
97
src/modules/diagnostic/types.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
// Learning Diagnostic Module Types
|
||||
|
||||
export type DiagnosticReportType = "individual" | "class" | "grade"
|
||||
export type DiagnosticReportStatus = "draft" | "published" | "archived"
|
||||
|
||||
/** 知识点掌握度记录 */
|
||||
export interface KnowledgePointMastery {
|
||||
id: string
|
||||
studentId: string
|
||||
knowledgePointId: string
|
||||
masteryLevel: number // 0-100
|
||||
totalQuestions: number
|
||||
correctQuestions: number
|
||||
lastAssessedAt: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/** 含知识点名称的掌握度(join knowledgePoints 后) */
|
||||
export interface MasteryWithKnowledgePoint extends KnowledgePointMastery {
|
||||
knowledgePointName: string
|
||||
knowledgePointDescription: string | null
|
||||
}
|
||||
|
||||
/** 学生掌握度摘要 */
|
||||
export interface StudentMasterySummary {
|
||||
studentId: string
|
||||
studentName: string
|
||||
averageMastery: number
|
||||
totalKnowledgePoints: number
|
||||
strengths: MasteryWithKnowledgePoint[] // 掌握度 >= 80
|
||||
weaknesses: MasteryWithKnowledgePoint[] // 掌握度 < 60
|
||||
allMastery: MasteryWithKnowledgePoint[]
|
||||
}
|
||||
|
||||
/** 诊断报告 */
|
||||
export interface DiagnosticReport {
|
||||
id: string
|
||||
studentId: string
|
||||
generatedBy: string | null
|
||||
reportType: DiagnosticReportType
|
||||
period: string | null
|
||||
summary: string | null
|
||||
strengths: string[] | null
|
||||
weaknesses: string[] | null
|
||||
recommendations: string[] | null
|
||||
overallScore: number | null
|
||||
status: DiagnosticReportStatus
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/** 含学生名的诊断报告(join users 后) */
|
||||
export interface DiagnosticReportWithDetails extends DiagnosticReport {
|
||||
studentName: string
|
||||
generatedByName: string | null
|
||||
}
|
||||
|
||||
/** 班级掌握度摘要 */
|
||||
export interface ClassMasterySummary {
|
||||
classId: string
|
||||
className: string
|
||||
studentCount: number
|
||||
averageMastery: number
|
||||
knowledgePointStats: KnowledgePointStat[]
|
||||
studentsNeedingAttention: Array<{
|
||||
studentId: string
|
||||
studentName: string
|
||||
averageMastery: number
|
||||
weakCount: number
|
||||
}>
|
||||
}
|
||||
|
||||
/** 知识点统计 */
|
||||
export interface KnowledgePointStat {
|
||||
knowledgePointId: string
|
||||
knowledgePointName: string
|
||||
averageMastery: number
|
||||
masteredCount: number // 掌握度 >= 80
|
||||
notMasteredCount: number // 掌握度 < 60
|
||||
totalStudents: number
|
||||
}
|
||||
|
||||
/** 报告查询过滤参数 */
|
||||
export interface DiagnosticReportQueryParams {
|
||||
studentId?: string
|
||||
reportType?: DiagnosticReportType
|
||||
status?: DiagnosticReportStatus
|
||||
period?: string
|
||||
}
|
||||
|
||||
/** 雷达图数据点 */
|
||||
export interface MasteryRadarPoint {
|
||||
knowledgePoint: string
|
||||
student: number // 0-100
|
||||
classAverage?: number // 0-100
|
||||
}
|
||||
Reference in New Issue
Block a user