Files
SuperJump/docs/superpowers/plans/2026-08-19-parent-exam-manage.md

1114 lines
44 KiB
Markdown

# 家长端成绩与试卷管理 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 家长端可管理每周检测成绩、考试成绩记录(编辑分数/达标、删除)与考试试卷内容(增改删、题目 JSON 校验)。
**Architecture:** 零新表零迁移。4 个任务:① parent/actions.ts 加 6 个管理 action(身份+家庭归属校验,试卷 JSON 形状校验);② 周测成绩管理页 /parent/weekly-records(替换课程管理只读块为入口卡片,移除 page.tsx weekly 查询);③ 考试成绩记录管理页 /parent/exam-records(左联试卷标题,卷删显示「已删试卷」);④ 考试试卷管理页 /parent/exams(列表/新建/编辑,仿 math 编辑器,JSON 文本域 + 保存校验)。所有页面 child 端行为零改动。
**Tech Stack:** Next.js 15.5 App Router、Drizzle ORM(mysql2)、shadcn ui 组件(Button/Input/Label/Checkbox/Badge)、zod、`useTransition` + `useRouter().refresh()` 行内编辑。
**Spec:** `docs/superpowers/specs/2026-08-19-parent-exam-manage-design.md`
## Global Constraints
- 项目无自动化测试框架,验证 = `npx tsc --noEmit`(每任务)+ `npm run build`(最终任务)。
- 新代码注释遵循项目风格,新函数加一行 `// xuchao:` 注释。
- 所有管理 action:家长身份校验(`!parent || parent.role !== "parent"`),并校验记录/孩子归属 `familyId === parent.familyId`——防越权。
- 编辑成绩/达标**不联动**积分/打卡回滚(用户选定):只改成绩表本身。
- 分数编辑限制:整数 0-1000。
- 删除操作一律 `confirm()` 二次确认(文案含被删对象)。
- 题目 JSON 校验规则:数组、非空、每题必需 `stem`/`type`/`explain`,题型条件字段(choice/judge 需 `answer`;fill 需 `answers` 数组;order 需 `answer` 数组;match 需 `pairs` 数组;solve 需 `reference` + `points > 0`)。
- `exam_paper` 的 `paperId` 有唯一索引 `uq_exam_paper_id`,保存用 `insert().onDuplicateKeyUpdate()`(参照 weekly/actions.ts 同款用法)。
- 课程管理 Section 只读周测块 → 三张入口卡片,风格与「✏️ 编辑英语语法课程」卡片一致(`rounded-xl border ... hover:-translate-y-0.5`)。
---
### Task 1: 家长端 6 个管理 action
**Files:**
- Modify: `src/app/parent/actions.ts`(顶部 schema 导入补 `examPapers/examRecords/weeklyTest`;文件末尾新增 6 个 action + 1 个私有校验函数)
**Interfaces:**
- Consumes: 现有 `getSessionUser`/`db`/`users`/`revalidatePath`/`eq`/`and`;(schema)新增导入 `examPapers`/`examRecords`/`weeklyTest`。
- Produces:
- `updateWeeklyRecord(id: number, score: number, passed: boolean): Promise<string | null>` — 成功返回 null,错误返回文案
- `deleteWeeklyRecord(id: number): Promise<void>`
- `updateExamRecord(id: number, score: number, passed: boolean): Promise<string | null>`
- `deleteExamRecord(id: number): Promise<void>`
- `saveExamPaper(formData: FormData): Promise<{ ok?: boolean; error?: string }>`
- `deleteExamPaper(paperId: string): Promise<void>`
- [ ] **Step 1: schema 导入行补三张表**
`src/app/parent/actions.ts` 顶部 `import { activationCodes, sessions, taskInstances, taskTemplates, users } from "@/db/schema";` 改为:
```ts
import { activationCodes, examPapers, examRecords, sessions, taskInstances, taskTemplates, users, weeklyTest } from "@/db/schema";
```
- [ ] **Step 2: 文件末尾追加三组 action 与校验函数**
```ts
// ===== 成绩与试卷管理:周测记录(不联动积分/打卡) =====
export async function updateWeeklyRecord(id: number, score: number, passed: boolean): Promise<string | null> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return "请先以家长身份登录";
if (!Number.isInteger(score) || score < 0 || score > 1000) return "分数需为 0-1000 的整数";
const [row] = await db
.select({ familyId: users.familyId })
.from(weeklyTest)
.innerJoin(users, eq(users.id, weeklyTest.childUserId))
.where(eq(weeklyTest.id, id))
.limit(1);
if (!row || row.familyId !== parent.familyId) return "记录不存在";
await db.update(weeklyTest).set({ score, passed }).where(eq(weeklyTest.id, id));
revalidatePath("/parent/weekly-records");
revalidatePath("/parent");
return null;
}
export async function deleteWeeklyRecord(id: number): Promise<void> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return;
const [row] = await db
.select({ familyId: users.familyId })
.from(weeklyTest)
.innerJoin(users, eq(users.id, weeklyTest.childUserId))
.where(eq(weeklyTest.id, id))
.limit(1);
if (!row || row.familyId !== parent.familyId) return;
await db.delete(weeklyTest).where(eq(weeklyTest.id, id));
revalidatePath("/parent/weekly-records");
revalidatePath("/parent");
}
// ===== 成绩与试卷管理:考试记录(不联动积分/打卡) =====
export async function updateExamRecord(id: number, score: number, passed: boolean): Promise<string | null> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return "请先以家长身份登录";
if (!Number.isInteger(score) || score < 0 || score > 1000) return "分数需为 0-1000 的整数";
const [row] = await db
.select({ familyId: users.familyId })
.from(examRecords)
.innerJoin(users, eq(users.id, examRecords.childUserId))
.where(eq(examRecords.id, id))
.limit(1);
if (!row || row.familyId !== parent.familyId) return "记录不存在";
await db.update(examRecords).set({ score, passed }).where(eq(examRecords.id, id));
revalidatePath("/parent/exam-records");
revalidatePath("/parent");
return null;
}
export async function deleteExamRecord(id: number): Promise<void> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return;
const [row] = await db
.select({ familyId: users.familyId })
.from(examRecords)
.innerJoin(users, eq(users.id, examRecords.childUserId))
.where(eq(examRecords.id, id))
.limit(1);
if (!row || row.familyId !== parent.familyId) return;
await db.delete(examRecords).where(eq(examRecords.id, id));
revalidatePath("/parent/exam-records");
revalidatePath("/parent");
}
// xuchao: 试卷题目 JSON 形状校验:数组 + 每题必需字段 + 题型条件字段
const EXAM_TYPES = ["choice", "fill", "judge", "order", "match", "solve"];
function validateQuestionsJson(raw: string): { error?: string; count?: number } {
let arr: unknown;
try {
arr = JSON.parse(raw);
} catch {
return { error: "题目 JSON 解析失败,请检查语法" };
}
if (!Array.isArray(arr)) return { error: "题目必须是 JSON 数组" };
if (arr.length === 0) return { error: "试卷至少需要 1 道题" };
for (let i = 0; i < arr.length; i++) {
const q = arr[i] as Record<string, unknown>;
const no = `第 ${i + 1} 题`;
if (!q || typeof q !== "object") return { error: `${no}不是对象` };
if (typeof q.stem !== "string" || !q.stem.trim()) return { error: `${no}缺少题干(stem)` };
if (typeof q.explain !== "string" || !q.explain.trim()) return { error: `${no}缺少解析(explain)` };
const t = q.type;
if (!EXAM_TYPES.includes(t as string)) return { error: `${no}的 type 非法:${String(t)}` };
if ((t === "choice" || t === "judge") && typeof q.answer !== "number") return { error: `${no}(${t})缺少答案(answer 数字)` };
if (t === "fill" && !Array.isArray(q.answers)) return { error: `${no}(fill)缺少参考答案(answers 数组)` };
if (t === "order" && !Array.isArray(q.answer)) return { error: `${no}(order)缺少答案(answer 数组)` };
if (t === "match" && !Array.isArray(q.pairs)) return { error: `${no}(match)缺少配对(pairs 数组)` };
if (t === "solve") {
if (typeof q.reference !== "string" || !q.reference.trim()) return { error: `${no}(solve)缺少参考解答(reference)` };
if (typeof q.points !== "number" || q.points <= 0) return { error: `${no}(solve)缺少满分(points>0)` };
}
}
return { count: arr.length };
}
// xuchao: 保存试卷(paperId 重复则全量更新,孩子端 /exam 立即生效)
export async function saveExamPaper(formData: FormData): Promise<{ ok?: boolean; error?: string }> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return { error: "请先以家长身份登录" };
const f = (k: string) => String(formData.get(k) ?? "").trim();
const paperId = f("paperId");
if (!/^[a-z0-9-]+$/.test(paperId)) return { error: "试卷编号只允许小写字母/数字/中划线,如 g7s1-m09-2" };
const title = f("title");
if (!title) return { error: "请填写试卷标题" };
const month = Number(formData.get("month"));
const seq = Number(formData.get("seq"));
if (!Number.isInteger(month) || month < 0 || month > 12) return { error: "月份需为 0-12 的整数" };
if (!Number.isInteger(seq) || seq < 0) return { error: "展示序号需为不小于 0 的整数" };
const questions = f("questions");
const chk = validateQuestionsJson(questions);
if (chk.error) return { error: chk.error };
await db
.insert(examPapers)
.values({
paperId,
subject: f("subject") || "math",
grade: f("grade") || "g7",
semester: f("semester") || "s1",
month,
examType: f("examType"),
title,
region: f("region") || null,
year: Number(formData.get("year")) || null,
duration: Number(formData.get("duration")) || null,
fullScore: Number(formData.get("fullScore")) || null,
sourceUrl: f("sourceUrl") || null,
summary: f("summary") || null,
questions: JSON.stringify(JSON.parse(questions)),
seq,
})
.onDuplicateKeyUpdate({
set: {
subject: f("subject") || "math",
grade: f("grade") || "g7",
semester: f("semester") || "s1",
month,
examType: f("examType"),
title,
region: f("region") || null,
year: Number(formData.get("year")) || null,
duration: Number(formData.get("duration")) || null,
fullScore: Number(formData.get("fullScore")) || null,
sourceUrl: f("sourceUrl") || null,
summary: f("summary") || null,
questions: JSON.stringify(JSON.parse(questions)),
seq,
},
});
revalidatePath("/parent/exams");
revalidatePath("/exam");
return { ok: true };
}
export async function deleteExamPaper(paperId: string): Promise<void> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return;
await db.delete(examPapers).where(eq(examPapers.paperId, paperId));
revalidatePath("/parent/exams");
revalidatePath("/exam");
}
```
- [ ] **Step 3: 类型检查**
Run: `npx tsc --noEmit`
Expected: 无输出
- [ ] **Step 4: 提交**
```bash
git add src/app/parent/actions.ts
git commit -m "家长端新增成绩与试卷管理 action:周测/考试记录改删+试卷保存删除(归属性校验+JSON校验)"
```
---
### Task 2: 周测成绩管理页
**Files:**
- Create: `src/app/parent/weekly-records/page.tsx`(server)
- Create: `src/app/parent/weekly-records/weekly-list.tsx`(client,行内编辑)
- Modify: `src/app/parent/dashboard.tsx`(移除 `WeeklyRow` 类型与 `weekly` prop 及只读周测块,替换为「每周检测成绩管理」入口卡片)
- Modify: `src/app/parent/page.tsx`(删除 weeklyRows 查询、weekly 组装、`WeeklyRow` 类型导入与传参)
**Interfaces:**
- Consumes: Task 1 的 `updateWeeklyRecord`/`deleteWeeklyRecord`(签名见 Task 1)。
- Produces: `/parent/weekly-records` 路由。
- [ ] **Step 1: 创建 `src/app/parent/weekly-records/page.tsx`**
```tsx
import Link from "next/link";
import { redirect } from "next/navigation";
import { desc, eq } from "drizzle-orm";
import { BackgroundBlobs } from "@/components/background-blobs";
import { db } from "@/db";
import { users, weeklyTest } from "@/db/schema";
import { getSessionUser } from "@/lib/auth";
import { WeeklyList } from "./weekly-list";
// xuchao: 周测成绩管理——编辑分数/达标、删除误生成记录(不联动积分打卡)
export default async function WeeklyRecordsPage() {
const parent = await getSessionUser();
if (!parent) redirect("/login");
if (parent.role !== "parent") redirect("/kid");
const rows = await db
.select({
id: weeklyTest.id,
childName: users.displayName,
weekKey: weeklyTest.weekKey,
score: weeklyTest.score,
passed: weeklyTest.passed,
takenAt: weeklyTest.takenAt,
})
.from(weeklyTest)
.innerJoin(users, eq(users.id, weeklyTest.childUserId))
.where(eq(users.familyId, parent.familyId))
.orderBy(desc(weeklyTest.takenAt))
.limit(100);
return (
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-10">
<BackgroundBlobs />
<header className="flex items-center justify-between">
<Link href="/parent" className="text-sm font-medium text-indigo-600">
← 返回家长中心
</Link>
<h1 className="text-xl font-extrabold text-slate-900">每周检测成绩管理</h1>
<span className="text-xs text-muted-foreground">最近 {rows.length} 条</span>
</header>
<p className="rounded-lg border-l-4 border-indigo-400 bg-indigo-50 px-3 py-2 text-sm text-indigo-800">
修改分数/达标状态或删除记录不会影响已发的积分与当日打卡。
</p>
<WeeklyList
rows={rows.map((r) => ({
id: r.id,
childName: r.childName,
weekKey: r.weekKey,
score: r.score ?? 0,
passed: r.passed,
takenAt: r.takenAt.toLocaleDateString("zh-CN"),
}))}
/>
</main>
);
}
```
- [ ] **Step 2: 创建 `src/app/parent/weekly-records/weekly-list.tsx`**
```tsx
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Check, Pencil, RotateCcw, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { deleteWeeklyRecord, updateWeeklyRecord } from "../actions";
export type WeeklyRowItem = {
id: number;
childName: string;
weekKey: string;
score: number;
passed: boolean;
takenAt: string;
};
// xuchao: 周测成绩行内编辑(分数+达标开关)、删除;保存后刷新服务端列表
export function WeeklyList({ rows }: { rows: WeeklyRowItem[] }) {
const router = useRouter();
const [editingId, setEditingId] = useState<number | null>(null);
const [score, setScore] = useState("");
const [passed, setPassed] = useState(false);
const [msg, setMsg] = useState("");
const [pending, startTransition] = useTransition();
const startEdit = (r: WeeklyRowItem) => {
setEditingId(r.id);
setScore(String(r.score));
setPassed(r.passed);
setMsg("");
};
const save = () => {
if (editingId == null) return;
const s = Number(score);
const err = (t: string) => setMsg(t);
startTransition(async () => {
const r = await updateWeeklyRecord(editingId, s, passed);
if (r) err(r);
else {
setEditingId(null);
router.refresh();
}
});
};
const remove = (id: number, label: string) => {
if (!confirm(`确定删除「${label}」的这条周测记录?孩子可重新检测。`)) return;
startTransition(() => {
deleteWeeklyRecord(id).then(() => router.refresh());
});
};
return (
<div className="space-y-2.5">
{rows.length === 0 && (
<div className="rounded-2xl border border-slate-100 bg-white p-8 text-center shadow-soft">
<p className="text-sm text-muted-foreground">暂无周测记录</p>
</div>
)}
{rows.map((r) => (
<div key={r.id} className="rounded-xl border border-slate-100 bg-white p-3 shadow-soft">
{editingId === r.id ? (
<div className="space-y-2.5">
<p className="text-sm font-medium text-slate-800">
{r.childName} · {r.weekKey}
</p>
<div className="flex items-center gap-3">
<div className="flex items-center gap-1.5 text-sm text-slate-600">
分数
<Input
className="h-8 w-20"
type="number"
min={0}
max={1000}
value={score}
onChange={(e) => setScore(e.target.value)}
/>
</div>
<label className="flex items-center gap-1.5 text-sm text-slate-600">
<Checkbox checked={passed} onCheckedChange={(v) => setPassed(v === true)} />
达标
</label>
{msg && <span className="text-xs font-medium text-destructive">{msg}</span>}
</div>
<div className="flex gap-2">
<Button size="sm" disabled={pending} onClick={save}>
<Check className="size-4" /> 保存
</Button>
<Button size="sm" variant="outline" disabled={pending} onClick={() => setEditingId(null)}>
<X className="size-4" /> 取消
</Button>
</div>
</div>
) : (
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-slate-800">{r.childName}</span>
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-muted-foreground">{r.weekKey}</span>
<span className={cn("text-sm font-bold", r.passed ? "text-emerald-600" : "text-rose-600")}>
{r.score} 分 {r.passed ? "✅" : "❌"}
</span>
<span className="ml-auto text-xs text-muted-foreground">{r.takenAt}</span>
<button type="button" aria-label="编辑" className="text-muted-foreground hover:text-indigo-600" onClick={() => startEdit(r)}>
<Pencil className="size-4" />
</button>
<button
type="button"
aria-label="删除"
className="text-muted-foreground hover:text-destructive"
onClick={() => remove(r.id, `${r.childName} ${r.weekKey}`)}
>
<Trash2 className="size-4" />
</button>
</div>
)}
</div>
))}
</div>
);
}
```
- [ ] **Step 3: dashboard.tsx 移除只读周测块与 weekly prop**
a) 删除类型 `export type WeeklyRow = {...};` 定义。
b) `ParentDashboard` 签名:参数删 `weekly`(三个位置:解构、props 类型注释、调用处)。
c) 课程管理 grid 中「📝 每周检测成绩」只读 `<div>` 块整体替换为:
```tsx
<Link href="/parent/weekly-records" className="block">
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
<p className="font-bold text-slate-900">📝 每周检测成绩管理</p>
<p className="mt-1 text-xs text-muted-foreground">改分数/达标,删除误生成记录</p>
</div>
</Link>
```
- [ ] **Step 4: page.tsx 删除 weekly 查询与传参**
a) `WeeklyRow` 从 dashboard 类型导入中移除;`weekly` prop 从 `ParentDashboard` 调用中移除。
b) 删除「周测成绩(课程管理)」块:weeklyRows 查询(约 182-200 行)、`const weekly: WeeklyRow[] = ...` 组装、以及 `WeeklyRow` 类型导入与 `<ParentDashboard ... weekly={weekly} />` 传参。
⚠️ 注意:`weeklyTest` 的 schema import **必须保留**——page.tsx 顶部 overview 日历的 wRows 查询(约 74 行)仍在使用它。只删「周测成绩(课程管理)」块。
- [ ] **Step 5: 类型检查**
Run: `npx tsc --noEmit`
Expected: 无输出
- [ ] **Step 6: 提交**
```bash
git add src/app/parent/weekly-records src/app/parent/dashboard.tsx src/app/parent/page.tsx
git commit -m "家长端每周检测成绩管理页:/parent/weekly-records 编辑分数达标+删除,替换课程管理只读块"
```
---
### Task 3: 考试成绩记录管理页
**Files:**
- Create: `src/app/parent/exam-records/page.tsx`(server)
- Create: `src/app/parent/exam-records/exam-list.tsx`(client,行内编辑,结构同 weekly-list)
- Modify: `src/app/parent/dashboard.tsx`(课程管理 grid 加「考试记录管理」入口卡片)
**Interfaces:**
- Consumes: Task 1 的 `updateExamRecord`/`deleteExamRecord`。
- Produces: `/parent/exam-records` 路由。
- [ ] **Step 1: 创建 `src/app/parent/exam-records/page.tsx`**
```tsx
import Link from "next/link";
import { redirect } from "next/navigation";
import { desc, eq } from "drizzle-orm";
import { BackgroundBlobs } from "@/components/background-blobs";
import { db } from "@/db";
import { examPapers, examRecords, users } from "@/db/schema";
import { getSessionUser } from "@/lib/auth";
import { ExamList } from "./exam-list";
// xuchao: 考试成绩记录管理——编辑分数/达标、删除记录(卷已删时标题显示占位)
export default async function ExamRecordsPage() {
const parent = await getSessionUser();
if (!parent) redirect("/login");
if (parent.role !== "parent") redirect("/kid");
const rows = await db
.select({
id: examRecords.id,
childName: users.displayName,
paperTitle: examPapers.title,
score: examRecords.score,
passed: examRecords.passed,
takenAt: examRecords.takenAt,
})
.from(examRecords)
.innerJoin(users, eq(users.id, examRecords.childUserId))
.leftJoin(examPapers, eq(examPapers.paperId, examRecords.paperId))
.where(eq(users.familyId, parent.familyId))
.orderBy(desc(examRecords.takenAt))
.limit(100);
return (
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-10">
<BackgroundBlobs />
<header className="flex items-center justify-between">
<Link href="/parent" className="text-sm font-medium text-indigo-600">
← 返回家长中心
</Link>
<h1 className="text-xl font-extrabold text-slate-900">考试记录管理</h1>
<span className="text-xs text-muted-foreground">最近 {rows.length} 条</span>
</header>
<p className="rounded-lg border-l-4 border-indigo-400 bg-indigo-50 px-3 py-2 text-sm text-indigo-800">
修改分数/达标状态或删除记录不会影响已发的积分与当日打卡;删除后孩子可重新考试。
</p>
<ExamList
rows={rows.map((r) => ({
id: r.id,
childName: r.childName,
paperTitle: r.paperTitle ?? "已删试卷",
score: r.score ?? 0,
passed: r.passed,
takenAt: r.takenAt.toLocaleDateString("zh-CN"),
}))}
/>
</main>
);
}
```
- [ ] **Step 2: 创建 `src/app/parent/exam-records/exam-list.tsx`**
```tsx
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Check, Pencil, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { deleteExamRecord, updateExamRecord } from "../actions";
export type ExamRowItem = {
id: number;
childName: string;
paperTitle: string;
score: number;
passed: boolean;
takenAt: string;
};
// xuchao: 考试记录行内编辑(分数+达标开关)、删除;保存后刷新服务端列表
export function ExamList({ rows }: { rows: ExamRowItem[] }) {
const router = useRouter();
const [editingId, setEditingId] = useState<number | null>(null);
const [score, setScore] = useState("");
const [passed, setPassed] = useState(false);
const [msg, setMsg] = useState("");
const [pending, startTransition] = useTransition();
const startEdit = (r: ExamRowItem) => {
setEditingId(r.id);
setScore(String(r.score));
setPassed(r.passed);
setMsg("");
};
const save = () => {
if (editingId == null) return;
const s = Number(score);
startTransition(async () => {
const r = await updateExamRecord(editingId, s, passed);
if (r) setMsg(r);
else {
setEditingId(null);
router.refresh();
}
});
};
const remove = (id: number, label: string) => {
if (!confirm(`确定删除「${label}」这条考试记录?孩子可重新考试。`)) return;
startTransition(() => {
deleteExamRecord(id).then(() => router.refresh());
});
};
return (
<div className="space-y-2.5">
{rows.length === 0 && (
<div className="rounded-2xl border border-slate-100 bg-white p-8 text-center shadow-soft">
<p className="text-sm text-muted-foreground">暂无考试记录</p>
</div>
)}
{rows.map((r) => (
<div key={r.id} className="rounded-xl border border-slate-100 bg-white p-3 shadow-soft">
{editingId === r.id ? (
<div className="space-y-2.5">
<p className="text-sm font-medium text-slate-800">
{r.childName} · {r.paperTitle}
</p>
<div className="flex items-center gap-3">
<div className="flex items-center gap-1.5 text-sm text-slate-600">
分数
<Input
className="h-8 w-20"
type="number"
min={0}
max={1000}
value={score}
onChange={(e) => setScore(e.target.value)}
/>
</div>
<label className="flex items-center gap-1.5 text-sm text-slate-600">
<Checkbox checked={passed} onCheckedChange={(v) => setPassed(v === true)} />
达标
</label>
{msg && <span className="text-xs font-medium text-destructive">{msg}</span>}
</div>
<div className="flex gap-2">
<Button size="sm" disabled={pending} onClick={save}>
<Check className="size-4" /> 保存
</Button>
<Button size="sm" variant="outline" disabled={pending} onClick={() => setEditingId(null)}>
<X className="size-4" /> 取消
</Button>
</div>
</div>
) : (
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-slate-800">{r.childName}</span>
<span className="max-w-[45%] truncate rounded-full bg-slate-100 px-2 py-0.5 text-xs text-muted-foreground">
{r.paperTitle}
</span>
<span className={cn("text-sm font-bold", r.passed ? "text-emerald-600" : "text-rose-600")}>
{r.score} 分 {r.passed ? "✅" : "❌"}
</span>
<span className="ml-auto text-xs text-muted-foreground">{r.takenAt}</span>
<button type="button" aria-label="编辑" className="text-muted-foreground hover:text-indigo-600" onClick={() => startEdit(r)}>
<Pencil className="size-4" />
</button>
<button
type="button"
aria-label="删除"
className="text-muted-foreground hover:text-destructive"
onClick={() => remove(r.id, `${r.childName} ${r.paperTitle}`)}
>
<Trash2 className="size-4" />
</button>
</div>
)}
</div>
))}
</div>
);
}
```
- [ ] **Step 3: dashboard.tsx 加「考试记录管理」入口卡片**
课程管理 grid 中,「📝 每周检测成绩管理」卡片之后插入:
```tsx
<Link href="/parent/exam-records" className="block">
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
<p className="font-bold text-slate-900">📄 考试记录管理</p>
<p className="mt-1 text-xs text-muted-foreground">改考试成绩/达标,删除误生成记录</p>
</div>
</Link>
```
- [ ] **Step 4: 类型检查**
Run: `npx tsc --noEmit`
Expected: 无输出
- [ ] **Step 5: 提交**
```bash
git add src/app/parent/exam-records src/app/parent/dashboard.tsx
git commit -m "家长端考试记录管理页:/parent/exam-records 编辑分数达标+删除(卷已删兼容)"
```
---
### Task 4: 考试试卷管理页(列表/新建/编辑)
**Files:**
- Create: `src/app/parent/exams/page.tsx`(server,月份分组列表)
- Create: `src/app/parent/exams/paper-form.tsx`(client,元信息表单 + 题目 JSON 文本域 + 保存/删除)
- Create: `src/app/parent/exams/new/page.tsx`(server,空表单)
- Create: `src/app/parent/exams/[paperId]/page.tsx`(server,编辑表单)
- Modify: `src/app/parent/dashboard.tsx`(课程管理 grid 加「考试试卷管理」入口卡片)
**Interfaces:**
- Consumes: Task 1 的 `saveExamPaper`/`deleteExamPaper`;`lib/exam.ts` 的 `getPaper`、`EXAM_TYPE_LABEL`、`listPapers`。
- Produces: `/parent/exams`、`/parent/exams/new`、`/parent/exams/[paperId]` 路由。
- [ ] **Step 1: 创建 `src/app/parent/exams/page.tsx`**
```tsx
import Link from "next/link";
import { Plus } from "lucide-react";
import { redirect } from "next/navigation";
import { BackgroundBlobs } from "@/components/background-blobs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { getSessionUser } from "@/lib/auth";
import { EXAM_TYPE_LABEL, listPapers } from "@/lib/exam";
// xuchao: 试卷管理列表——与孩子端考试中心同分组(月份),点击进入编辑
const MONTH_LABEL: Record<number, string> = {
0: "入学 · 分班考",
9: "9 月 · 有理数",
10: "10 月 · 整式的加减",
11: "11 月 · 一元一次方程",
12: "12 月 · 几何图形初步",
1: "1 月 · 期末全册",
};
const MONTH_ORDER = [0, 9, 10, 11, 12, 1];
function countQuestions(qs: string): number {
try {
const arr = JSON.parse(qs) as unknown[];
return Array.isArray(arr) ? arr.length : 0;
} catch {
return 0;
}
}
export default async function ExamsAdmin() {
const parent = await getSessionUser();
if (!parent) redirect("/login");
if (parent.role !== "parent") redirect("/kid");
const papers = await listPapers("g7", "s1");
return (
<main className="relative mx-auto max-w-2xl space-y-5 p-4 pb-10">
<BackgroundBlobs />
<header className="flex items-center justify-between">
<Link href="/parent" className="text-sm font-medium text-indigo-600">
← 返回家长中心
</Link>
<h1 className="text-xl font-extrabold text-slate-900">考试试卷管理</h1>
<Link href="/parent/exams/new">
<Button size="sm">
<Plus className="size-4" /> 新建试卷
</Button>
</Link>
</header>
<p className="rounded-lg border-l-4 border-indigo-400 bg-indigo-50 px-3 py-2 text-sm text-indigo-800">
点击试卷可编辑元信息与题目,保存后孩子端考试中心立即生效。
</p>
{papers.length === 0 && (
<div className="rounded-2xl border border-slate-100 bg-white p-8 text-center shadow-soft">
<p className="text-sm text-muted-foreground">还没有试卷,点右上角新建</p>
</div>
)}
{MONTH_ORDER.map((m) => {
const group = papers.filter((p) => p.month === m);
if (group.length === 0) return null;
return (
<section key={m} className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
<h2 className="mb-2 text-sm font-extrabold text-slate-900">{MONTH_LABEL[m]}</h2>
<div className="space-y-1.5">
{group.map((p) => (
<Link
key={p.paperId}
href={`/parent/exams/${p.paperId}`}
className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700 transition-colors hover:border-indigo-300"
>
<span className="truncate font-medium text-slate-800">{p.title}</span>
<Badge className="shrink-0 bg-indigo-100 text-indigo-700 hover:bg-indigo-100">
{EXAM_TYPE_LABEL[p.examType] ?? p.examType}
</Badge>
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{p.seq} 号卷</span>
</Link>
))}
</div>
</section>
);
})}
</main>
);
}
```
- [ ] **Step 2: 创建 `src/app/parent/exams/paper-form.tsx`**
```tsx
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { CheckCircle2, Save, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { EXAM_TYPE_LABEL } from "@/lib/exam";
import { deleteExamPaper, saveExamPaper } from "../actions";
export type PaperMeta = {
paperId: string;
title: string;
examType: string;
region: string | null;
year: number | null;
duration: number | null;
fullScore: number | null;
month: number;
seq: number;
sourceUrl: string | null;
summary: string | null;
questions: string;
};
// xuchao: 试卷编辑器——元信息表单 + 题目 JSON 文本域;保存走服务端完整校验
export function PaperForm({ paper, isNew }: { paper: PaperMeta | null; isNew: boolean }) {
const router = useRouter();
const [f, setF] = useState({
paperId: paper?.paperId ?? "",
title: paper?.title ?? "",
examType: paper?.examType ?? "monthly",
region: paper?.region ?? "",
year: paper?.year != null ? String(paper.year) : "",
duration: paper?.duration != null ? String(paper.duration) : "",
fullScore: paper?.fullScore != null ? String(paper.fullScore) : "100",
month: String(paper?.month ?? 9),
seq: String(paper?.seq ?? 1),
sourceUrl: paper?.sourceUrl ?? "",
summary: paper?.summary ?? "",
questions: paper ? JSON.stringify(JSON.parse(paper.questions), null, 2) : "[]",
});
const [msg, setMsg] = useState<{ ok?: boolean; text: string } | null>(null);
const [pending, startTransition] = useTransition();
// xuchao: 客户端轻量预览:JSON 可解析则显示题数,失败显示错误(完整校验在服务端)
const preview = (() => {
try {
const arr = JSON.parse(f.questions) as unknown[];
if (!Array.isArray(arr)) return { ok: false, text: "题目必须是 JSON 数组" };
return { ok: true, text: `共 ${arr.length} 道题` };
} catch (e) {
return { ok: false, text: `JSON 语法错误:${(e as Error).message}` };
}
})();
const save = () => {
setMsg(null);
const fd = new FormData();
(Object.keys(f) as (keyof typeof f)[]).forEach((k) => fd.set(k, f[k]));
startTransition(() => {
saveExamPaper(fd).then((r) => {
if (r.error) setMsg({ text: r.error });
else setMsg({ ok: true, text: "已保存,孩子端立即生效" });
});
});
};
const remove = () => {
if (!paper || !confirm(`确定删除试卷「${paper.title}」?孩子的历史作答记录会保留。`)) return;
startTransition(() => {
deleteExamPaper(paper.paperId).then(() => router.push("/parent/exams"));
});
};
const n = (key: keyof typeof f) => ({
value: f[key],
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
setF((prev) => ({ ...prev, [key]: e.target.value })),
});
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label>试卷编号(唯一,如 g7s1-m09-2)</Label>
<Input disabled={!isNew} placeholder="g7s1-m09-2" {...n("paperId")} />
</div>
<div className="space-y-1">
<Label>试卷标题</Label>
<Input placeholder="2025-2026 学年第一学期 9 月月考" {...n("title")} />
</div>
<div className="space-y-1">
<Label>考试类型</Label>
<select
value={f.examType}
onChange={(e) => setF((prev) => ({ ...prev, examType: e.target.value }))}
className="h-10 w-full rounded-lg border border-slate-200 bg-white px-3 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
>
{Object.entries(EXAM_TYPE_LABEL).map(([k, v]) => (
<option key={k} value={k}>
{v}
</option>
))}
</select>
</div>
<div className="space-y-1">
<Label>月份(0=入学考,1-12)</Label>
<select
value={f.month}
onChange={(e) => setF((prev) => ({ ...prev, month: e.target.value }))}
className="h-10 w-full rounded-lg border border-slate-200 bg-white px-3 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
>
{[0, 9, 10, 11, 12, 1].map((m) => (
<option key={m} value={m}>
{m === 0 ? "入学 · 分班考" : `${m} 月`}
</option>
))}
</select>
</div>
<div className="space-y-1">
<Label>地区(如:湖南长沙)</Label>
<Input placeholder="湖南长沙" {...n("region")} />
</div>
<div className="space-y-1">
<Label>年份</Label>
<Input type="number" placeholder="2025" {...n("year")} />
</div>
<div className="space-y-1">
<Label>考试时长(分钟)</Label>
<Input type="number" placeholder="120" {...n("duration")} />
</div>
<div className="space-y-1">
<Label>卷面满分</Label>
<Input type="number" placeholder="100" {...n("fullScore")} />
</div>
<div className="space-y-1">
<Label>展示序号(组内顺序)</Label>
<Input type="number" placeholder="1" {...n("seq")} />
</div>
<div className="space-y-1">
<Label>来源链接</Label>
<Input placeholder="https://…" {...n("sourceUrl")} />
</div>
</div>
<div className="space-y-1">
<Label>考查说明</Label>
<Input placeholder="考查范围,如:有理数、整式的加减" {...n("summary")} />
</div>
<div className="space-y-1">
<div className="flex items-center justify-between">
<Label>题目(quiz JSON 数组)</Label>
<span className={preview.ok ? "text-xs text-emerald-600" : "text-xs text-destructive"}>{preview.text}</span>
</div>
<textarea
value={f.questions}
onChange={n("questions").onChange}
rows={16}
className="w-full rounded-lg border border-slate-200 bg-white p-3 font-mono text-xs leading-relaxed focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
/>
</div>
{msg && <p className={msg.ok ? "text-sm font-medium text-emerald-600" : "text-sm font-medium text-destructive"}>{msg.text}</p>}
<div className="flex items-center gap-2">
<Button disabled={pending} onClick={save}>
<Save className="size-4" /> {pending ? "保存中…" : "保存"}
</Button>
{!isNew && (
<Button variant="outline" disabled={pending} onClick={remove}>
<Trash2 className="size-4 text-destructive" /> 删除试卷
</Button>
)}
{msg?.ok && <CheckCircle2 className="size-4 text-emerald-600" />}
</div>
</div>
);
}
```
- [ ] **Step 3: 创建 `src/app/parent/exams/new/page.tsx`**
```tsx
import Link from "next/link";
import { redirect } from "next/navigation";
import { BackgroundBlobs } from "@/components/background-blobs";
import { getSessionUser } from "@/lib/auth";
import { PaperForm } from "../paper-form";
// xuchao: 新建试卷页(paperId 唯一;科目/年级/学期固定 math/g7/s1,孩子端立即出现)
export default async function NewExamPage() {
const parent = await getSessionUser();
if (!parent) redirect("/login");
if (parent.role !== "parent") redirect("/kid");
return (
<main className="relative mx-auto max-w-3xl space-y-5 p-4 pb-10">
<BackgroundBlobs />
<header className="flex items-center justify-between">
<Link href="/parent/exams" className="text-sm font-medium text-indigo-600">
← 试卷列表
</Link>
<h1 className="text-xl font-extrabold text-slate-900">新建试卷</h1>
</header>
<div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-soft">
<PaperForm paper={null} isNew />
</div>
</main>
);
}
```
- [ ] **Step 4: 创建 `src/app/parent/exams/[paperId]/page.tsx`**
```tsx
import Link from "next/link";
import { redirect } from "next/navigation";
import { BackgroundBlobs } from "@/components/background-blobs";
import { getSessionUser } from "@/lib/auth";
import { getPaper } from "@/lib/exam";
import { PaperForm } from "../paper-form";
// xuchao: 编辑试卷页——元信息 + 题目 JSON,保存即刷新孩子端 /exam
export default async function EditExamPage({ params }: { params: Promise<{ paperId: string }> }) {
const parent = await getSessionUser();
if (!parent) redirect("/login");
if (parent.role !== "parent") redirect("/kid");
const paper = await getPaper((await params).paperId);
if (!paper) redirect("/parent/exams");
return (
<main className="relative mx-auto max-w-3xl space-y-5 p-4 pb-10">
<BackgroundBlobs />
<header className="flex items-center justify-between">
<Link href="/parent/exams" className="text-sm font-medium text-indigo-600">
← 试卷列表
</Link>
<h1 className="text-xl font-extrabold text-slate-900">{paper.title}</h1>
</header>
<div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-soft">
<PaperForm
isNew={false}
paper={{
paperId: paper.paperId,
title: paper.title,
examType: paper.examType,
region: paper.region,
year: paper.year,
duration: paper.duration,
fullScore: paper.fullScore,
month: paper.month,
seq: paper.seq,
sourceUrl: paper.sourceUrl,
summary: paper.summary,
questions: paper.questions,
}}
/>
</div>
</main>
);
}
```
- [ ] **Step 5: dashboard.tsx 加「考试试卷管理」入口卡片**
课程管理 grid 中「📄 考试记录管理」卡片之后插入:
```tsx
<Link href="/parent/exams" className="block">
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft transition-transform duration-200 hover:-translate-y-0.5">
<p className="font-bold text-slate-900">🗂️ 考试试卷管理</p>
<p className="mt-1 text-xs text-muted-foreground">新增/编辑/删除试卷,孩子端立即生效</p>
</div>
</Link>
```
- [ ] **Step 6: 类型检查 + 构建**
Run: `npx tsc --noEmit`
Expected: 无输出
Run: `npm run build`
Expected: 构建成功;`/parent/exams`、`/parent/exams/new`、`/parent/exams/[paperId]`、`/parent/weekly-records`、`/parent/exam-records` 均在路由表
- [ ] **Step 7: 提交**
```bash
git add src/app/parent/exams src/app/parent/dashboard.tsx
git commit -m "家长端考试试卷管理:列表/新建/编辑(/parent/exams),题目 JSON 保存校验,孩子端即时生效"
```
---
## 手工测试清单(部署 jump.hn12301.net 后)
1. 课程管理:三张入口卡片(周测管理/考试记录管理/试卷管理)替代原只读周测块。
2. 周测管理:编辑分数/达标 → 保存后行内显示更新;删除 → 记录消失;孩子端 weekly 可重测。
3. 考试记录管理:编辑/删除生效;先删一张卷再看记录 → 标题显示「已删试卷」。
4. 试卷管理:新建合法 JSON 试卷 → 孩子端 /exam 立即出现;paperId 重复 → 报错;JSON 非法 → 对应错误文案不保存;删除 → 孩子端消失。
5. 编辑周测/考试记录后,孩子达标积分与当日打卡不变化(预期,不联动)。
6. 孩子账号访问任一管理页 → 重定向 /kid;未登录 → /login。