家长端考试试卷管理:列表/新建/编辑(/parent/exams),题目 JSON 保存校验,孩子端即时生效

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
jacobxu666
2026-08-19 17:01:00 +08:00
co-authored by Claude Haiku 4.5
parent 1b5e95725e
commit 522ff91525
5 changed files with 354 additions and 0 deletions
+187
View File
@@ -0,0 +1,187 @@
"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 { deleteExamPaper, saveExamPaper } from "../actions";
// xuchao: 与 lib/exam.ts 的 EXAM_TYPE_LABEL 保持同步(客户端不能直接引用服务端模块)
const EXAM_TYPE_LABEL: Record<string, string> = {
entrance: "入学考",
monthly: "月考",
unit: "单元卷",
midterm: "期中",
final: "期末",
};
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>
);
}