Compare commits

..
8 Commits
Author SHA1 Message Date
jacobxu666andClaude Haiku 4.5 88c2ee8c52 补试卷题目 JSON 校验(choice options/order words)+ 删周测列表死导入(最终评审)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 17:13:42 +08:00
jacobxu666andClaude Haiku 4.5 3de907164b 删除试卷管理列表页未使用的 countQuestions 死代码(评审发现)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 17:04:27 +08:00
jacobxu666andClaude Haiku 4.5 522ff91525 家长端考试试卷管理:列表/新建/编辑(/parent/exams),题目 JSON 保存校验,孩子端即时生效
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 17:01:00 +08:00
jacobxu666andClaude Haiku 4.5 1b5e95725e 家长端考试记录管理页:/parent/exam-records 编辑分数达标+删除(卷已删兼容)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 16:55:16 +08:00
jacobxu666andClaude Haiku 4.5 abcdd5bed8 家长端每周检测成绩管理页:/parent/weekly-records 编辑分数达标+删除,替换课程管理只读块
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 16:51:50 +08:00
jacobxu666 859fdcbda7 家长端新增成绩与试卷管理 action:周测/考试记录改删+试卷保存删除(归属性校验+JSON校验) 2026-08-19 16:47:06 +08:00
jacobxu666 36ecc71139 docs: 家长端成绩与试卷管理实施计划(4任务:actions/周测管理/考试记录/试卷管理) 2026-08-19 16:45:29 +08:00
jacobxu666andClaude Haiku 4.5 60fa03786a docs: 家长端成绩与试卷管理设计文档(周测/考试记录编辑删除+试卷内容管理)
零新表零迁移;三套管理全走家长端独立页;编辑不联动积分打卡。

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 16:41:07 +08:00
13 changed files with 2081 additions and 37 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,81 @@
# 家长端成绩与试卷管理 - 设计文档
日期:2026-08-19
状态:已批准
## 背景
家长端「课程管理」只有一张只读的最近 10 条周测成绩列表,考试板块(试卷+作答记录)在家长端完全没有入口。
用户要求:每周检测成绩、考试中心对应的数据都可管理(已确认:成绩记录编辑+删除、试卷内容管理一次全做)。
关键现状:
- `weekly_test`:孩子周测自动写入(child+weekKey 唯一),达标联动发积分 + 当日英语打卡。
- `exam_paper`:试卷内容存库(meta + questions quiz JSON);`exam_record`:孩子作答(child+paperId 唯一),达标联动发积分 + 当日数学打卡。
- 家长端已有内容编辑器成熟模式(grammar/words/math:列表页 → 详情编辑页,保存即生效)。
- `quiz-parse` 只提供 `extractQuiz(md)` 与 `QuizQ` 类型,无独立 JSON 校验器 → 校验在保存 action 内做形状校验。
## 需求(已与用户确认)
1. **每周检测成绩管理**:家长可编辑(分数 + 达标状态)、删除记录。
2. **考试成绩记录管理**:同款编辑 + 删除。
3. **考试试卷内容管理**:新增/编辑/删除试卷(元信息表单 + 题目 JSON 文本域,保存时校验)。
4. 编辑成绩/达标**不联动**积分与打卡回滚(用户选定,简单优先)。
5. 题目编辑用 **JSON 文本域 + 保存时校验**(用户选定,非结构化逐题表单)。
## 方案选择
- **方案 A(采用):三套管理全部进家长端独立页,零新表零迁移**
- 成绩记录管理仿 wrongbook/family-manage 模式(server action + 行内编辑);试卷管理仿 grammar/math 编辑器(列表 → 详情编辑)。
- 方案 B(弃):结构化逐题表单编辑题目 → 表单工程量大,两倍工作量。
- 方案 C(弃):成绩管理塞进课程管理 Section 行内 → 交互空间挤、可扩展性差。
## 设计
### 1. 周测成绩管理 `/parent/weekly-records`
- 入口:课程管理 Section 的只读周测列表块删除,替换为「每周检测成绩管理」入口卡片(与课程编辑卡片同风格)。
- 页面(server component):鉴权同其它家长页;查询 `weekly_test` join `users`(本家庭全部孩子),按 takenAt 倒序最近 100 条,按孩子分组展示。
- 每行:孩子名 · 周 key · 分数 · 达标徽标 · 日期;操作:编辑(行内展开分数输入 + 达标开关 + 保存/取消)、删除(按钮二次确认)。
- 分数编辑:整数 0-1000 表单校验;达标独立开关,不自动按 80 分计算(家长手动决定,与"不联动回滚"精神一致)。
- 删除后孩子端 `getWeeklyRecord` 为空 → 可重测,唯一索引重建记录。
### 2. 考试成绩记录管理 `/parent/exam-records`
- 同款独立页。查询 `exam_record` join `users`(孩子)+ `exam_paper`(**left join**,卷被删时 title 显示「已删试卷」)。
- 每行:孩子名 · 试卷标题 · 分数 · 达标 · 日期;编辑(分数+达标)+ 删除(确认)。
- 删除后孩子端 `getExamRecord` 为空 → 可重考。
### 3. 考试试卷管理 `/parent/exams`
- 列表页:按月份分组(复用 exam 页 MONTH_LABEL 分组逻辑,固定 g7/s1/math,与孩子端一致),每组内每卷:标题 · 类型徽标 · 题数;编辑/删除按钮;顶部「+ 新建试卷」。
- 编辑页 `/parent/exams/[paperId]`:元信息表单(标题/考试类型/地区/年份/时长/满分/来源链接/考查说明/月份/序号)+ **题目 JSON 文本域**(初始值 `JSON.stringify(questions, null, 2)`)。
- 保存时校验(server action):`JSON.parse` → 必须是数组 → 每题形状校验(`stem`/`type`/`answer`/`explain` 非空 + type 条件字段,如 fill 的 `answers`、order/match 的 `answer` 数组、solve 的 `reference`)→ 失败返回具体错误信息不保存。
- 文本域下方实时显示"共 N 题"统计(客户端解析,失败显示红色提示)。
- 新建页 `/parent/exams/new`:同表单,paperId 手填(校验格式 `[a-z0-9-]+`、唯一),科目/年级/学期/月份/序号默认值。
- 删除试卷:允许(记录 left join 已容错);孩子端 `/exam` 列表即时消失,已打开的卷页 404。
### 4. parent/actions.ts 新增 6 个 action(全部家长身份 + 家庭归属校验)
| action | 说明 |
| --- | --- |
| `updateWeeklyRecord(id, score, passed)` / `deleteWeeklyRecord(id)` | 周测记录;按 id 查 childUserId → 归属校验 |
| `updateExamRecord(id, score, passed)` / `deleteExamRecord(id)` | 考试记录;同上 |
| `saveExamPaper(formData)` | 新增/更新试卷(带 paperId 唯一性检查 + 题目 JSON 校验) |
| `deleteExamPaper(paperId)` | 删除试卷(仅家长 + 本家庭无需校验——试卷非家庭私有,家长即可) |
- 编辑/删除周测与考试记录后 `revalidatePath("/parent")` + 对应管理页;试卷保存后 `revalidatePath("/parent/exams")` + `revalidatePath("/exam")`(孩子端立即生效)。
### 5. 不改动
- DB schema(三张表已有足够的字段)、`weekly/actions.ts`、`exam/actions.ts`、`lib/weekly.ts`、孩子端任何页面。
- 积分/打卡链路不动。
## 测试清单(手工,项目无自动化测试框架)
1. 课程管理 Section:三张入口卡片(周测管理/考试记录管理/试卷管理)替代原只读周测块。
2. 周测管理:编辑分数/达标 → 显示更新;删除 → 记录消失,孩子端 weekly 页可重测;越权孩子 id 篡改 → 拒绝。
3. 考试记录管理:编辑/删除生效;删除试卷后再看记录 → 标题显示「已删试卷」。
4. 试卷管理:新建试卷(JSON 合法)→ 孩子端 /exam 立即出现;编辑保留;JSON 非法 → 报错不保存;删除 → 孩子端消失;paperId 重复 → 报错。
5. 孩子达标积分/当日打卡在编辑周测/考试记录后不变(不联动,预期行为)。
6. 部署 jump.hn12301.net 后线上复验。
+168 -1
View File
@@ -5,7 +5,7 @@ import { and, eq, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/db";
import { activationCodes, familyInvites, sessions, taskInstances, taskTemplates, users } from "@/db/schema";
import { activationCodes, examPapers, examRecords, familyInvites, sessions, taskInstances, taskTemplates, users, weeklyTest } from "@/db/schema";
import { SUBJECT_VALUES } from "@/db/schema";
import { todayStr } from "@/lib/dates";
import { ensureDay } from "@/lib/tasks";
@@ -258,3 +258,170 @@ export async function removeChild(childId: number): Promise<void> {
revalidatePath("/parent");
revalidatePath("/learn");
}
// ===== 成绩与试卷管理:周测记录(不联动积分/打卡) =====
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 === "choice" && (!Array.isArray(q.options) || q.options.length === 0)) return { error: `${no}(choice)缺少选项(options)` };
if (t === "order" && (!Array.isArray(q.words) || q.words.length === 0)) return { error: `${no}(order)缺少词块(words)` };
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");
}
+17 -14
View File
@@ -68,8 +68,6 @@ export type DevicesData = {
isCurrent: boolean;
}[];
};
export type WeeklyRow = { childName: string; weekKey: string; score: number; passed: boolean };
// xuchao: 家庭管理数据——家庭名 + 家长成员 + 孩子成员
export type FamilyData = {
familyName: string;
@@ -93,14 +91,12 @@ export function ParentDashboard({
overview,
templates,
devices,
weekly,
points,
family,
}: {
overview: OverviewData;
templates: TemplatesData;
devices: DevicesData;
weekly: WeeklyRow[];
points: PointsData;
family: FamilyData;
}) {
@@ -161,17 +157,24 @@ export function ParentDashboard({
<p className="mt-1 text-xs text-muted-foreground">改标题/目标/课文,保存即生效</p>
</div>
</Link>
<div className="rounded-xl border border-slate-100 bg-white p-4 shadow-soft">
<p className="font-bold text-slate-900">📝 每周检测成绩</p>
<div className="mt-2 space-y-1">
{weekly.length === 0 && <p className="text-xs text-muted-foreground">暂无检测记录</p>}
{weekly.map((w, i) => (
<p key={i} className="text-xs text-slate-600">
{w.childName} · {w.weekKey} · {w.score} 分 {w.passed ? "✅" : "❌"}
</p>
))}
<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>
</div>
</Link>
<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>
<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>
</div>
</Section>
+125
View File
@@ -0,0 +1,125 @@
"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>
);
}
+57
View File
@@ -0,0 +1,57 @@
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>
);
}
+47
View File
@@ -0,0 +1,47 @@
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>
);
}
+27
View File
@@ -0,0 +1,27 @@
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>
);
}
+78
View File
@@ -0,0 +1,78 @@
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];
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>
);
}
+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>
);
}
-22
View File
@@ -32,7 +32,6 @@ import {
type OverviewData,
type PointsData,
type TemplatesData,
type WeeklyRow,
} from "./dashboard";
const SH = { timeZone: "Asia/Shanghai" } as const;
@@ -181,26 +180,6 @@ export default async function ParentPage() {
})),
};
// ===== 周测成绩(课程管理) =====
const weeklyRows = await db
.select({
childName: users.displayName,
weekKey: weeklyTest.weekKey,
score: weeklyTest.score,
passed: weeklyTest.passed,
})
.from(weeklyTest)
.innerJoin(users, eq(users.id, weeklyTest.childUserId))
.where(eq(users.familyId, parent.familyId))
.orderBy(desc(weeklyTest.takenAt))
.limit(10);
const weekly: WeeklyRow[] = weeklyRows.map((w) => ({
childName: w.childName,
weekKey: w.weekKey,
score: w.score ?? 0,
passed: w.passed,
}));
// ===== 积分管理(规则 + 每孩子总积分/最近流水) =====
const rules = await listPointRules();
const pointsData: PointsData = { rules, kids: [] };
@@ -243,7 +222,6 @@ export default async function ParentPage() {
overview={overview}
templates={templates}
devices={devices}
weekly={weekly}
points={pointsData}
family={family}
/>
+56
View File
@@ -0,0 +1,56 @@
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>
);
}
@@ -0,0 +1,124 @@
"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 { 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>
);
}