Compare commits

..
29 Commits
Author SHA1 Message Date
jacobxu666andClaude Haiku 4.5 c706f485cc 试卷题目配图(几何体):编辑器上传区+孩子端渲染+文件名校验+public挂卷持久化
test / test (push) Successful in 37s
uploadPaperFigure 存 public/exam/<卷>/<uuid>.ext;编辑器预览/移除;
quiz-block 渲染 q.figure;compose 挂 exam-figures 卷防重建丢失。

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 16:08:27 +08:00
jacobxu666andClaude Haiku 4.5 890e7ef3ac 编辑卡片类型徽标不随题干换行(shrink-0+min-w-0);新增题目按钮去掉双加号(图标+文字)
test / test (push) Failing after 43s
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 15:59:20 +08:00
jacobxu666andClaude Haiku 4.5 95994b14d0 试卷编辑页三处布局优化:头部标题独立成行可换行、网格显式单列+元素自适应、题目编辑表单渲染在被编辑题下方
test / test (push) Failing after 6m52s
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 15:24:10 +08:00
jacobxu666 131ee41ac8 docs: 设计文档与 C1 裁定对齐(新建应用题固定 answer 模式,存量 rubric 只读)
test / test (push) Failing after 6m37s
2026-08-20 14:58:17 +08:00
jacobxu666andClaude Haiku 4.5 5ce33f3edf 编辑器存量 rubric 徽标/题型切换清理/分值输入修复(最终复核 R1-R3)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 14:57:40 +08:00
jacobxu666andClaude Haiku 4.5 5e4904742a 编辑器新建应用题仅 answer 模式+数据完整性修复(最终评审:rubric 0分守卫/答案下标/points/ossKey 前缀/测试修正)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 14:49:21 +08:00
jacobxu666 fe68ed7512 新增 Gitea Actions 测试 workflow:push 即跑 vitest 全量 2026-08-20 14:23:09 +08:00
jacobxu666andClaude Haiku 4.5 063420595d 移除多余测试依赖 @vitejs/plugin-react,改用内置 OXC JSX 配置(评审约束违反修复)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 14:20:53 +08:00
jacobxu666andClaude Haiku 4.5 0749ba2c38 家长端结构化题目编辑器:题型联动表单替代 JSON 文本域,应用题支持 judgeMode 切换
- 新增 question-list.tsx:结构化题目卡片列表(选择题/判断题/填空题/应用题)
- 新增 question-list.test.tsx:4 个 RTL 组件测试覆盖渲染/新增/编辑/校验
- paper-form.tsx:JSON textarea 替换为 QuestionList,保存时序列化 QuizQ[]
- vitest.config.ts:加 @vitejs/plugin-react 支持 JSX 组件测试
- test-setup.ts:注册 afterEach cleanup 避免跨测试 DOM 污染

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 14:16:13 +08:00
jacobxu666andClaude Haiku 4.5 255c9a244c 孩子端应用题 answer 模式:拍照+填最终答案,交卷归一化匹配秒判(rubric 流程不变)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 14:07:12 +08:00
jacobxu666andClaude Haiku 4.5 e896b2be51 题目校验抽取为可单测 lib;扩展 solve judgeMode(answer/rubric)分支校验
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 13:59:51 +08:00
jacobxu666andClaude Haiku 4.5 bb8bb25096 搭建 Vitest 测试框架;新增答案等价判定 lib(answer-match),QuizQ 支持 judgeMode
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 13:55:16 +08:00
jacobxu666 637c6032d4 docs: 结构化编辑器+答案判分实施计划(5任务含Vitest框架/组件测试/CI) 2026-08-20 13:49:01 +08:00
jacobxu666 611b493c84 docs: 设计文档补充自动化测试框架节(Vitest+jsdom+CI 测试 workflow) 2026-08-20 13:45:10 +08:00
jacobxu666andClaude Haiku 4.5 8de35e85c2 docs: 结构化题目编辑器+应用题答案判分模式设计文档
题型联动表单替代 JSON 文本域(首发 judge/choice/fill/solve);
应用题新增 judgeMode=answer(最终答案数组+归一化匹配秒判),rubric AI 判分共存。

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-20 13:38:46 +08:00
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
jacobxu666 348dad28fe docs: 新文件补末尾换行(评审 Minor) 2026-08-19 15:35:41 +08:00
jacobxu666 145ba1b7d1 家长端新增家庭管理:成员列表+生成邀请码,第二位家长凭码注册加入 2026-08-19 15:24:38 +08:00
jacobxu666 df41f7713d 新增家长注册页 /register:凭家庭邀请码注册加入并自动登录 2026-08-19 15:20:49 +08:00
jacobxu666andClaude Haiku 4.5 da7f7a6a19 新增 family_invite 家庭邀请码表(schema+0009迁移)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 15:17:38 +08:00
jacobxu666 8c9d8ece1a docs: 家庭管理实施计划(3任务:迁移/注册页/家庭管理卡片) 2026-08-19 14:36:42 +08:00
jacobxu666andClaude Haiku 4.5 4ac4e2091a docs: 家庭管理设计文档(邀请码注册第二位家长)
新表 family_invite+注册页 /register+家长端家庭管理卡片;
新家长与现有家长权限一致,本次不做成员移除。

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-08-19 11:55:13 +08:00
39 changed files with 7341 additions and 641 deletions
+12
View File
@@ -0,0 +1,12 @@
# xuchao: 自动化测试——push 即跑,守护题型校验/答案判定/编辑器组件
name: test
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run test
+6
View File
@@ -5,6 +5,8 @@ services:
container_name: superjump
restart: unless-stopped
env_file: .env
volumes:
- exam-figures:/app/public/exam
networks: [proxy, data]
labels:
- traefik.enable=true
@@ -21,3 +23,7 @@ networks:
data:
name: data
external: true
# 试卷配图持久化:容器内 public/exam 写卷挂载,重建不丢
volumes:
exam-figures:
@@ -0,0 +1,469 @@
# 家庭管理(邀请第二位家长)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:** 家长端可生成家庭邀请码,第二位家长凭码在 `/register` 注册加入家庭,登录后看到全部孩子数据(权限与现有家长一致)。
**Architecture:** 新增 `family_invite` 表(仿 `activation_code`:6 位码、一次性、15 分钟);新增 `/register` 家长注册页(server action 校验码→建 user→自动登录);家长端功能 tab 新增「家庭管理」Section(成员列表 + 生成邀请码按钮)。`users.familyId` 已按家庭隔离数据,第二位家长同 familyId 即自动可见全部数据,无需权限改造。
**Tech Stack:** Next.js 15.5 App Router、TypeScript、Drizzle ORM(mysql2)、bcryptjs、Tailwind/ui 组件(shadcn 风格)、zod。
**Spec:** `docs/superpowers/specs/2026-08-19-family-manage-design.md`
## Global Constraints
- 项目无自动化测试框架,验证靠 `npx tsc --noEmit` + `npm run build`(每任务末尾跑 tsc,最终任务跑 build)+ 手工清单。
- 新代码注释遵循项目风格,新函数加一行 `// xuchao:` 注释(用户全局规范)。
- 验证码/邀请码一律只存 sha256 哈希(`crypto.createHash("sha256").update(code).digest("hex")`),明文只在生成后一次性返回给调用方。
- 迁移文件格式:文件头 `-- xuchao:` 注释 + `CREATE TABLE IF NOT EXISTS` + 幂等,语句间 `--> statement-breakpoint` 分隔(参照 `drizzle/0008_points.sql`)。
- 邀请码规则固定:6 位数字、15 分钟过期、一次性(未用且未过期才算有效)。
- 手机号唯一(`uq_user_phone`),注册时先查占用,报「该手机号已注册」。
---
### Task 1:family_invite 表(schema + 迁移 0009)
**Files:**
- Modify: `src/db/schema.ts`(在 `activationCodes` 表定义之后追加)
- Create: `drizzle/0009_family-invite.sql`
**Interfaces:**
- Produces: `familyInvites` 表的 drizzle 对象(列:`id`/`familyId`/`codeHash`/`createdBy`/`createdAt`/`expiresAt`/`usedAt`),供 Task 2/3 的 server action 使用。
- [ ] **Step 1: schema.ts 追加 family_invite 表**
在 `src/db/schema.ts` 中 `activationCodes` 表定义(`// ===== 设备激活码` 那一节)结束之后、`// ===== 周模板` 注释之前插入:
```ts
// ===== 家庭邀请码(家长生成,其他家长凭码注册加入;一次性,15 分钟)=====
export const familyInvites = mysqlTable("family_invite", {
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
familyId: bigint("family_id", { mode: "number" })
.notNull()
.references(() => families.id, { onDelete: "cascade" }),
codeHash: varchar("code_hash", { length: 64 }).notNull(),
createdBy: bigint("created_by", { mode: "number" })
.notNull()
.references(() => users.id),
createdAt: datetime("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
expiresAt: datetime("expires_at").notNull(),
usedAt: datetime("used_at"),
});
```
- [ ] **Step 2: 创建迁移文件 `drizzle/0009_family-invite.sql`**
```sql
-- xuchao: 家庭邀请码——家长生成一次性邀请码,其他家长凭码注册加入家庭。幂等。
CREATE TABLE IF NOT EXISTS `family_invite` (
`id` bigint AUTO_INCREMENT NOT NULL,
`family_id` bigint NOT NULL,
`code_hash` varchar(64) NOT NULL,
`created_by` bigint NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`expires_at` datetime NOT NULL,
`used_at` datetime,
CONSTRAINT `family_invite_id` PRIMARY KEY(`id`)
);
```
- [ ] **Step 3: 类型检查**
Run: `npx tsc --noEmit`
Expected: 无输出(退出码 0)
- [ ] **Step 4: 提交**
```bash
git add src/db/schema.ts drizzle/0009_family-invite.sql
git commit -m "新增 family_invite 家庭邀请码表(schema+0009迁移)"
```
---
### Task 2:`/register` 注册页 + 登录页入口
**Files:**
- Create: `src/app/register/actions.ts`
- Create: `src/app/register/page.tsx`
- Modify: `src/app/login/page.tsx`(登录按钮下的提示区加链接)
**Interfaces:**
- Consumes: Task 1 的 `familyInvites`、现有 `users`/`createSession`、`bcryptjs`。
- Produces: `registerWithInvite(prev: RegisterState, formData: FormData): Promise<RegisterState>`(RegisterState = `{ error?: string } | null`)。
- [ ] **Step 1: 创建 `src/app/register/actions.ts`**
```ts
"use server";
import crypto from "node:crypto";
import bcrypt from "bcryptjs";
import { and, eq, gt, isNull } from "drizzle-orm";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/db";
import { familyInvites, users } from "@/db/schema";
import { createSession } from "@/lib/auth";
function hashCode(code: string) {
return crypto.createHash("sha256").update(code).digest("hex");
}
const registerSchema = z.object({
displayName: z.string().trim().min(1, "请输入称呼").max(20, "称呼最多 20 字"),
phone: z.string().regex(/^1\d{10}$/, "请输入 11 位手机号"),
password: z.string().min(6, "密码至少 6 位"),
code: z.string().regex(/^\d{6}$/, "邀请码是 6 位数字"),
});
export type RegisterState = { error?: string } | null;
// xuchao: 家长凭邀请码注册:校验码→查重手机号→事务(码标记已用+建家长)→自动登录跳家长中心
export async function registerWithInvite(
_prev: RegisterState,
formData: FormData,
): Promise<RegisterState> {
const parsed = registerSchema.safeParse({
displayName: formData.get("displayName"),
phone: formData.get("phone"),
password: formData.get("password"),
code: formData.get("code"),
});
if (!parsed.success) return { error: parsed.error.issues[0].message };
const { displayName, phone, password, code } = parsed.data;
const [invite] = await db
.select({ id: familyInvites.id, familyId: familyInvites.familyId })
.from(familyInvites)
.where(
and(
eq(familyInvites.codeHash, hashCode(code)),
isNull(familyInvites.usedAt),
gt(familyInvites.expiresAt, new Date()),
),
)
.limit(1);
if (!invite) return { error: "邀请码无效或已过期,请让家长重新生成" };
const [dup] = await db.select({ id: users.id }).from(users).where(eq(users.phone, phone)).limit(1);
if (dup) return { error: "该手机号已注册" };
const passwordHash = await bcrypt.hash(password, 10);
const newUserId = await db.transaction(async (tx) => {
await tx.update(familyInvites).set({ usedAt: new Date() }).where(eq(familyInvites.id, invite.id));
const [created] = await tx
.insert(users)
.values({ familyId: invite.familyId, role: "parent", displayName, phone, passwordHash })
.$returningId();
return created.id;
});
await createSession(newUserId, "家长设备", 30);
redirect("/parent");
}
```
- [ ] **Step 2: 创建 `src/app/register/page.tsx`**
```tsx
"use client";
import { useActionState } from "react";
import Link from "next/link";
import { UserPlus } from "lucide-react";
import { BackgroundBlobs } from "@/components/background-blobs";
import { registerWithInvite } from "./actions";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export default function RegisterPage() {
const [state, formAction, pending] = useActionState(registerWithInvite, null);
return (
<main className="relative flex min-h-dvh items-center justify-center p-4">
<BackgroundBlobs />
<Card className="w-full max-w-sm border-slate-100 shadow-soft transition-shadow duration-200 hover:shadow-lift">
<CardHeader className="items-center gap-3 text-center">
<div className="flex size-14 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-btn">
<UserPlus className="size-8 text-white" />
</div>
<h1 className="text-2xl font-extrabold tracking-tight">加入家庭</h1>
<p className="text-sm text-muted-foreground">需要家里已有成员的邀请码</p>
</CardHeader>
<CardContent>
<form action={formAction} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="displayName">称呼</Label>
<Input id="displayName" name="displayName" placeholder="如:妈妈" required />
</div>
<div className="space-y-2">
<Label htmlFor="phone">手机号</Label>
<Input
id="phone"
name="phone"
type="tel"
inputMode="numeric"
autoComplete="username"
placeholder="11 位手机号"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">密码</Label>
<Input
id="password"
name="password"
type="password"
autoComplete="new-password"
placeholder="至少 6 位"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="code">邀请码</Label>
<Input
id="code"
name="code"
inputMode="numeric"
maxLength={6}
placeholder="6 位数字"
className="font-mono tracking-widest"
required
/>
</div>
{state?.error && <p className="text-sm font-medium text-destructive">{state.error}</p>}
<Button type="submit" className="w-full" size="lg" disabled={pending}>
{pending ? "注册中…" : "注册并加入家庭"}
</Button>
<p className="text-center text-sm text-muted-foreground">
已有账号?{" "}
<Link href="/login" className="font-semibold text-indigo-600 underline-offset-4 hover:underline">
去登录
</Link>
</p>
</form>
</CardContent>
</Card>
</main>
);
}
```
- [ ] **Step 3: 登录页加注册入口**
`src/app/login/page.tsx` 中「去输入激活码」那个 `<p>` 之后、`</form>` 之前插入:
```tsx
<p className="text-center text-sm text-muted-foreground">
家里另一位家长想加入?{" "}
<Link
href="/register"
className="font-semibold text-indigo-600 underline-offset-4 hover:underline"
>
用邀请码加入家庭
</Link>
</p>
```
- [ ] **Step 4: 类型检查**
Run: `npx tsc --noEmit`
Expected: 无输出(退出码 0)
- [ ] **Step 5: 提交**
```bash
git add src/app/register src/app/login/page.tsx
git commit -m "新增家长注册页 /register:凭家庭邀请码注册加入并自动登录"
```
---
### Task 3:家长端「家庭管理」Section
**Files:**
- Modify: `src/app/parent/actions.ts`(schema 导入行加 `familyInvites`;文件内新增 `generateFamilyInvite` action)
- Create: `src/app/parent/family-manage.tsx`
- Modify: `src/app/parent/dashboard.tsx`(新增 `FamilyData` 类型 + props + Section)
- Modify: `src/app/parent/page.tsx`(查询家庭名与家长列表,组装 `family` 传入 Dashboard)
**Interfaces:**
- Consumes: Task 1 的 `familyInvites`;现有 `getSessionUser`/`db`/`families`/`users`。
- Produces: `generateFamilyInvite(): Promise<{ code?: string; error?: string }>`;`FamilyManage({ familyName, parents, kids })` 组件;`FamilyData` 类型。
- [ ] **Step 1: parent/actions.ts 加 `generateFamilyInvite`**
先改 schema 导入行(文件顶部 `import { activationCodes, sessions, taskInstances, taskTemplates, users } from "@/db/schema";` → 追加 `familyInvites`);再在 `createActivationCode` action 之后追加:
```ts
// xuchao: 生成家庭邀请码(6 位,15 分钟一次性),对方凭码在 /register 注册加入
export async function generateFamilyInvite(): Promise<{ code?: string; error?: string }> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return { error: "请先以家长身份登录" };
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
await db.insert(familyInvites).values({
familyId: parent.familyId,
codeHash: hashCode(code),
createdBy: parent.id,
expiresAt: new Date(Date.now() + 15 * 60_000),
});
return { code };
}
```
- [ ] **Step 2: 创建 `src/app/parent/family-manage.tsx`**
```tsx
"use client";
import { useState, useTransition } from "react";
import { UserPlus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { generateFamilyInvite } from "./actions";
// xuchao: 家庭管理——展示成员列表,生成一次性邀请码让其他家长注册加入
export function FamilyManage({
familyName,
parents,
kids,
}: {
familyName: string;
parents: { id: number; name: string }[];
kids: { id: number; name: string }[];
}) {
const [invite, setInvite] = useState<{ code?: string; error?: string } | null>(null);
const [pending, startTransition] = useTransition();
const gen = () => {
setInvite(null);
startTransition(async () => {
setInvite(await generateFamilyInvite());
});
};
return (
<div className="space-y-3">
<p className="text-sm text-slate-700">
<span className="font-semibold">{familyName}</span> · {parents.length} 位家长 · {kids.length} 个孩子
</p>
<div className="space-y-1.5">
{parents.map((p) => (
<div key={p.id} className="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm">
<span className="font-medium text-slate-800">{p.name}</span>
<span className="rounded-full bg-indigo-100 px-2 py-0.5 text-xs font-medium text-indigo-700">家长</span>
</div>
))}
{kids.map((k) => (
<div key={k.id} className="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm">
<span className="font-medium text-slate-800">{k.name}</span>
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500">孩子</span>
</div>
))}
</div>
<div className="flex flex-wrap items-center gap-3">
<Button size="sm" variant="secondary" disabled={pending} onClick={gen}>
<UserPlus className="size-4" /> {pending ? "生成中…" : "生成邀请码"}
</Button>
{invite?.error && <p className="text-sm font-medium text-destructive">{invite.error}</p>}
{invite?.code && (
<p className="text-sm text-slate-700">
邀请码{" "}
<span className="font-mono text-lg font-bold tracking-widest text-indigo-600">{invite.code}</span>
<span className="ml-1 text-xs text-muted-foreground">15 分钟有效,一次性</span>
</p>
)}
</div>
</div>
);
}
```
- [ ] **Step 3: dashboard.tsx 加 `FamilyData` 类型、props 与 Section**
a) `WeeklyRow` 类型定义之后追加:
```ts
// xuchao: 家庭管理数据——家庭名 + 家长成员 + 孩子成员
export type FamilyData = {
familyName: string;
parents: { id: number; name: string }[];
kids: { id: number; name: string }[];
};
```
b) 导入区加 `import { FamilyManage } from "./family-manage";`(与 `ChildManage` 导入相邻)。
c) `ParentDashboard` 函数签名 props 加 `family: FamilyData;`,`({ overview, templates, devices, weekly, points, family }: { ...; family: FamilyData; })`。
d) 「孩子管理」Section 之前插入:
```tsx
<Section title="家庭管理" desc="添加家庭其他家长,一起查看孩子的学习情况">
<FamilyManage
familyName={family.familyName}
parents={family.parents}
kids={family.kids}
/>
</Section>
```
- [ ] **Step 4: page.tsx 查询并传入 family 数据**
a) schema 导入行(第 4-16 行 `import { sessions, ... } from "@/db/schema";`)追加 `families`。
b) Dashboard 类型导入(第 27-34 行)追加 `FamilyData`。
c) 会话/周测查询之后、`return` 之前插入:
```ts
// ===== 家庭管理(家庭名 + 全部成员) =====
const [familyRow] = await db
.select({ name: families.name })
.from(families)
.where(eq(families.id, parent.familyId))
.limit(1);
const parentRows = await db
.select({ id: users.id, displayName: users.displayName })
.from(users)
.where(and(eq(users.familyId, parent.familyId), eq(users.role, "parent")))
.orderBy(asc(users.id));
const family: FamilyData = {
familyName: familyRow?.name ?? "我的家庭",
parents: parentRows.map((p) => ({ id: p.id, name: p.displayName })),
kids: kids.map((k) => ({ id: k.id, name: k.name })),
};
```
d) `return` 里 `<ParentDashboard ... />` 追加 `family={family}` prop。
- [ ] **Step 5: 类型检查 + 构建**
Run: `npx tsc --noEmit`
Expected: 无输出
Run: `npm run build`
Expected: 构建成功,`/register`、`/parent` 均出现在路由表
- [ ] **Step 6: 提交**
```bash
git add src/app/parent
git commit -m "家长端新增家庭管理:成员列表+生成邀请码,第二位家长凭码注册加入"
```
---
## 手工测试清单(部署 jump.hn12301.net 前在本地 MySQL 可用时/或部署后执行)
1. 家长端功能 tab → 「家庭管理」:显示家庭名、家长/孩子成员与计数。
2. 点「生成邀请码」→ 显示 6 位码与「15 分钟有效,一次性」。
3. 浏览器开 `/register`:输称呼+新手机号+密码+邀请码 → 注册成功自动进 `/parent`,看到全部孩子与数据。
4. 第二家长登录(新手机号+密码)→ 能编辑课程/看积分,设备管理里出现两个家长会话。
5. 同一邀请码二次注册 → 「邀请码无效或已过期」;过期(15 分钟)同样报错。
6. 已注册手机号再注册 → 「该手机号已注册」;错误邀请码 → 「邀请码无效或已过期」。
7. 登录页出现「用邀请码加入家庭」链接,可达 `/register`;孩子设备激活流程不受影响。
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,90 @@
# 家庭管理:邀请第二位家长加入 - 设计文档
日期:2026-08-19
状态:已批准
## 背景
家长端目前只有 seed 脚本创建的首位家长(手机号+密码登录),家庭内无法自助添加其他家长(如配偶)。
用户希望:能添加家庭其他家长,第二位家长也能查看孩子的学习情况。
关键现状:
- `users.familyId` 已支持一家庭多家长;`/parent` 所有查询按 familyId 隔离,
**第二位家长只要拿到同一 familyId 即自动看到全部孩子数据,无需权限改造**。
- 首位家长账号由 `scripts/seed.ts` 创建,生产无注册页。
- 孩子加入:家长生成 6 位激活码(`activation_code` 表,一次性+15分钟) → 孩子设备输入 → 2 年设备会话。
- `families` 表已有 `name` 字段(seed 写入),尚未展示。
## 需求(已与用户确认)
1. 家长端「家庭管理」可生成邀请码,第二位家长凭码注册加入家庭。
2. 新加入家长权限与现有家长完全一样(概览/课程/积分/设备/孩子管理全可见)。
3. 本次不做成员移除(用户选定)。
4. 邀请码:6 位数字、一次性、15 分钟有效(与孩子激活码一致)。
## 方案选择
- **方案 A(采用):独立邀请码表 `family_invite` + 新注册页 `/register`**
- 仿 `activation_code` 既有模式,注册页表单(称呼+手机号+密码+邀请码),对方自设密码。
- 方案 B(弃):家长代建账号直接填手机号+初始密码 → 对方无法自选密码,需线下传递。
- 方案 C(弃):复用 `activation_code` 表 → 该表按 childUserId 绑定,语义冲突。
## 设计
### 1. 数据模型(schema.ts + 迁移 0009_family-invite.sql)
```ts
export const familyInvites = mysqlTable("family_invite", {
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
familyId: bigint("family_id", { mode: "number" })
.notNull()
.references(() => families.id, { onDelete: "cascade" }),
codeHash: varchar("code_hash", { length: 64 }).notNull(),
createdBy: bigint("created_by", { mode: "number" })
.notNull()
.references(() => users.id),
createdAt: datetime("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
expiresAt: datetime("expires_at").notNull(),
usedAt: datetime("used_at"),
});
```
### 2. 注册页:`src/app/register/page.tsx` + `actions.ts`(仿 join,server action + useActionState)
- 表单:称呼、手机号(11 位)、密码(≥6 位)、邀请码(6 位数字)。
- `registerWithInvite(prev, formData)` 逻辑:
1. zod 校验表单;邀请码 sha256 查询 `family_invite`(未用且未过期),失败统一报「邀请码无效或已过期,请让家长重新生成」;
2. 校验手机号未被占用(`users.phone` 唯一),占用报「该手机号已注册」;
3. 事务:标记邀请码已用 → 插入 `user(role=parent, familyId=邀请码家庭, phone, passwordHash)` → `createSession(30 天)` → `redirect("/parent")`。
- 密码 bcrypt 哈希(与 login 一致)。
### 3. 登录页入口
- `src/app/login/page.tsx` 底部「去输入激活码」旁加「没有账号?用邀请码加入家庭」链接 → `/register`。
### 4. 家长端「家庭管理」卡片
- `src/components` 或 `src/app/parent/family-manage.tsx`(client 组件,仿 child-manage):
- 展示:家庭名 + 成员列表(家长显示称呼+「家长」徽标,孩子显示名字+「孩子」徽标);
- 「生成邀请码」按钮 → 调 `createFamilyInvite` action → 内联显示 6 位码 +「15 分钟有效,一次性」;
- 允许同时存在多个未用邀请码,不做互斥。
- dashboard.tsx「功能」tab 中与孩子管理并列插入该卡片;`/parent/page.tsx` 查询家庭成员数据传入:
- `parents`: `users.role=parent AND familyId=parent.familyId`
- `kids`: 已有查询复用
- `familyName`: `families` 表按 familyId 查询
- action `createFamilyInvite`(parent/actions.ts):取会话家长 → 生成 6 位随机数字码(与 createActivationCode 同法,15 分钟过期) → 存 hash → 返回码明文给调用方展示。
### 5. 不改动
- 孩子激活流程、`login` 逻辑、`activation_code` 表、`devices-tab`。
## 测试清单(手工,项目无自动化测试框架)
1. 家长端功能 tab → 家庭管理卡片:显示家庭名与全部成员。
2. 生成邀请码 → 显示 6 位码;15 分钟后(或码用过后)注册报「邀请码无效或已过期」。
3. `/register` 成功注册 → 自动登录进入 `/parent`,看到全部孩子与数据(概览/错题/周测)。
4. 第二家长登录后:设备管理能看到两家长会话;课程/积分改动互相可见。
5. 手机号已注册(任意家庭) → 报「该手机号已注册」。
6. 孩子设备激活流程不受影响;登录页新链接可达 `/register`。
7. 部署 jump.hn12301.net 后线上复验。
@@ -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 后线上复验。
@@ -0,0 +1,103 @@
# 结构化题目编辑器 + 应用题答案判分模式 - 设计文档
日期:2026-08-20
状态:已批准
## 背景
`/parent/exams/[paperId]` 编辑页目前用**裸 JSON 文本域**录入题目,家长需手写 quiz JSON 数组(曾明确拒绝结构化表单,现转向)。同时用户对应用题判分提出新模式:孩子拍照上传解题过程 + 填写最终答案来判定对错(替代/补充现有 AI 逐评分点判分)。
现状事实(grilling 确认):
- 现有 86 道种子题 = choice 48 + fill 30 + solve 8,**judge/order/match 零数据**。
- solve 题现状:孩子拍照 → 百炼 Qwen-VL 按 rubric 评分点逐点判分(ai-grade.ts,无 key 演示回退),照片与逐点判定进错题本。
- 孩子端 QuizBlock 已支持全部 6 题型答题 + 对错反馈;fill 题的参考答案本身是**数组**(answers)。
- 现有 svaeEqxamPaper 的 validateQuestionsJson 已做形状校验。
## 需求(已与用户确认)
1. **结构化编辑器**:试卷题目改为逐题表单(题型联动字段),不再手写 JSON。题目卡片流:新增/编辑/删除/上移/下移。
2. **首发四种题型**:判断题/选择题/填空题/应用题(judge/order/match 暂不做,有数据时后置)。
3. **应用题新增判定模式** `judgeMode: "answer"`:家长只填**最终答案数组**(复用 fill 的 answers 语义)+ 分值;孩子拍照解题过程 + 填最终答案,**归一化匹配秒级判对错**,不调 AI。
4. **共存**:现有 rubric 模式(AI 逐点评分)保留,存量 8 道题零改动(`judgeMode` 缺省 = rubric)。
5. 孩子端此模式下:拍照必填(进错题本),最终答案判对错;对 = 满分,错 = 0 分(不做部分给分,可解释)。
## 方案选择
- **方案 A(采用):结构化表单产出仍是 QuizQ JSON,存储/孩子端渲染零schema改动**
- 编辑 UI 从 JSON textarea 换成题型联动表单;服务端校验扩展 judgeMode 分支;判分在现有 child 提交链路内按 judgeMode 分流。
- 方案 B(弃):引入独立"题目表"(questions 拆表)→ 迁移 86 题、错题本/组卷/判分全部重写,收益为零。
- 方案 C(弃):AI 判最终答案(取代归一化)→ 有延迟、依赖 key、判定无法对孩子解释;归一化数组对家庭场景足够。
## 设计
### 1. QuizQ 扩展(src/lib/quiz-parse.ts)
```ts
// solve 新增可选字段(缺省即 rubric 老模式,向后兼容):
judgeMode?: "rubric" | "answer";
// judgeMode==="answer" 时复用:
answers?: string[]; // 最终答案数组(与 fill 同字段语义,等价答法都填)
// points 两种模式下都必须(分值);reference 为展示用参考解答
```
### 2. 归一化判定 lib(新建 src/lib/answer-match.ts)
```ts
// xuchao: 答案等价判定——数值类归一化(分数/小数/百分数互转),文本类去空格/全角/大小写
export function normalizeAnswer(s: string): string;
export function answersMatch(expected: string[], given: string): boolean; // 任一期望答案等价即中
```
- 纯数字语义(`1/2`→`0.5`、`50%`→`0.5`、`0.50`→`0.5`,去尾零)互转比较。
- 含字母/单位词(如 `10个`、`across`)按文本归一(去空白、全角→半角、小写)严格比较;等价形式靠家长在答案数组里补填。
- **fill 现有判分不动**(grammar.ts `gradeOne`:trim+小写精确匹配)——归一化仅用于 judgeMode==="answer" 的应用题,避免改变既有周测/记录判分行为。
### 3. 孩子端判分流(exam/actions.ts takeExam + QuizBlock)
- `takeExam` 中 solve 题分流:
- `judgeMode==="answer"`:`answersMatch(q.answers, 孩子填的答案)` → score=points(对)/0(错);判定与照片写 `solveSnap`(`hits:[{ point:"最终答案", score, hit, reason }]`),照片 OSS 照常上传。
- 缺省/`rubric`:走现有 ai-grade 逐点评分,零改动。
- QuizBlock solve 分支:answer 模式下拍照必填 + 显示最终答案 Input;rubric 模式现状不变。
- 错题本:**零改动**(solveSnap 结构兼容;answerText 已对 solve 显示拍照与得分)。
### 4. 家长端结构化编辑器(/parent/exams/[paperId] 重构)
- PaperForm 拆为:试卷 MetaForm(现有字段,不动)+ `QuestionList`(题目卡片区)。
- QuestionList:
- 每题卡片:题型徽标 + 题干摘要 + 操作(编辑/上移/下移/删除)。
- 「+ 新增题目」按钮;题型下拉(judge/choice/fill/solve 四项)。
- QuestionForm 按 type 联动:
- **judge**:题干 + 解析 + 对/错单选
- **choice**:题干 + 选项列表(增/删/编辑,单选正确答案)+ 解析
- **fill**:题干 + 参考答案数组(增/删/编辑)+ 解析
- **solve**:题干 + 分值 + **新建题固定「仅最终答案(秒判)」模式**(最终答案数组 + 参考解答可选);存量 rubric 题只读徽标「AI 逐评分点判分(存量题,保留原评分点)」+ 参考解答(必填语义),不提供评分点编辑(2026-08-20 用户裁定:新题仅 answer,无判分模式开关)
- 非法时客户端给出对应提示(与服务端同文案);保存仍走现有 `saveExamPaper`(JSON 序列化 QuizQ 数组)。
- 服务端 validateQuestionsJson 扩展:
- solve:rubric 模式沿用现行(reference + points 必填);answer 模式要求 `answers` 非空数组 + points 必填,reference 可选;answer 模式不得带 rubric。
- 其余题型校验不变。
### 5. 不改动
- DB schema(quiz JSON 存储不变)、ai-grade.ts、错题本 WrongRow、积分/达标规则、周测组卷。
- 孩子端之外:seed、overview、记录管理全不动。
### 6. 自动化测试框架(用户追加要求:没有就搭建)
- 框架:**Vitest**(TS 原生、零配置成本),+ jsdom + @testing-library/react 用于组件测试(QuestionForm/QuestionList 题型联动)。
- 关键可测逻辑**沉淀为纯函数**进 lib,不做 DB/网络依赖:
- 新增 `src/lib/answer-match.ts`(归一化/等价,已设计于 §2)
- 现 `validateQuestionsJson`(parent/actions.ts 私有)→ 迁到新 `src/lib/question-validation.ts` 导出,`saveExamPaper` 引用之(行为不变)
- 测试覆盖:answer-match 全分支(数值/文本/单位/边界);question-validation 全题型 + judgeMode 新分支(accept/reject 用例);QuestionForm 题型联动渲染与非法输入提示。
- 脚本:`"test": "vitest run"`;vitest.config.ts 配 `@` alias。
- CI:Gitea Actions 新增 `.gitea/workflows/test.yaml`,push 即跑 `npm ci && npm run test`(runner 为 node:24-slim,已可用)。
## 测试清单(手工 + 自动化)
- 自动化:上述 Vitest 用例全绿;`npm run test` 通过。
- 手工:编辑页 JSON 文本域消失,题目卡片流可新增/编辑/删除/上下移/保存。
- 手工:四种题型表单字段联动正确;应用题的 rubric/answer 开关切换字段正确。
- 手工:新建 answer 应用题(答案 0.5 与 1/2 都填):孩子端拍照 + 填 `1/2` → 判对满分;填 `2/3` → 判错 0 分,错题本含照片与判定。
- 手工:存量 rubric 题:孩子照旧拍照 AI 逐点评分,进错题本逐点判定。
- 手工:服务端校验:answer 模式缺 answers / rubric 模式缺 reference → 对应报错不保存。
- 部署 jump.hn12301.net 后线上复验。
+11
View File
@@ -0,0 +1,11 @@
-- xuchao: 家庭邀请码——家长生成一次性邀请码,其他家长凭码注册加入家庭。幂等。
CREATE TABLE IF NOT EXISTS `family_invite` (
`id` bigint AUTO_INCREMENT NOT NULL,
`family_id` bigint NOT NULL,
`code_hash` varchar(64) NOT NULL,
`created_by` bigint NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`expires_at` datetime NOT NULL,
`used_at` datetime,
CONSTRAINT `family_invite_id` PRIMARY KEY(`id`)
);
+7
View File
@@ -64,6 +64,13 @@
"when": 1786233600000,
"tag": "0008_points",
"breakpoints": true
},
{
"idx": 9,
"version": "5",
"when": 1786320000000,
"tag": "0009_family-invite",
"breakpoints": true
}
]
}
+2515 -599
View File
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -11,7 +11,8 @@
"db:push": "drizzle-kit push",
"db:seed": "tsx scripts/seed.ts",
"db:seed-math": "tsx scripts/seed-math.ts",
"db:seed-exam": "tsx scripts/seed-exam.ts"
"db:seed-exam": "tsx scripts/seed-exam.ts",
"test": "vitest run"
},
"dependencies": {
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
@@ -34,13 +35,18 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.11",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.5",
"@types/node": "^24.0.0",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"dotenv": "^17.2.0",
"drizzle-kit": "^0.31.4",
"jsdom": "^30.0.1",
"tailwindcss": "^4.1.11",
"tsx": "^4.20.3",
"typescript": "^5.8.3"
"typescript": "^5.8.3",
"vitest": "^4.1.11"
}
}
+25
View File
@@ -4,6 +4,8 @@
import { revalidatePath } from "next/cache";
import { getSessionUser } from "@/lib/auth";
import { gradeOne, gradeAnswers, type AnswerValue } from "@/lib/grammar";
import { solveAnswerHit } from "@/lib/answer-match";
import type { SolveAnswerPayload } from "@/lib/quiz-parse";
import { getPaper, gradeCountToday, latestSolveLogs, paperQuestions, recordExam } from "@/lib/exam";
import { recordWrong } from "@/lib/wrongbook";
import { gradeSolvePhoto, type GradeVerdict } from "@/lib/ai-grade";
@@ -135,6 +137,29 @@ export async function takeExam(paperId: string, answers: (AnswerValue | null)[])
const pts = q.points ?? 1;
pointSum += pts;
if (q.type === "solve") {
if (q.judgeMode === "answer") {
// xuchao: answer 模式——最终答案归一化匹配秒判,不调 AI 不写审计日志
const payload = answers[i] as SolveAnswerPayload | null | undefined;
const given = payload?.answer?.trim() ?? "";
const hit = solveAnswerHit(q, given);
const earned = hit ? pts : 0;
detail.push(hit);
if (hit) correct++;
earnedSum += earned;
const hits: GradeVerdict["hits"] = [
{ point: "最终答案", score: earned, hit, reason: hit ? "与最终答案一致" : `期望:${(q.answers ?? []).join(" / ")},实际:${given || "未作答"}` },
];
// xuchao: ossKey 前缀校验——防止客户端伪造路径
const prefix = `exam-solve/${user.id}/${paperId}/`;
const rawKey = payload?.ossKey ?? "";
const safeKey = rawKey.startsWith(prefix) && rawKey.endsWith(".jpg") ? rawKey : "";
solves.push({ qIndex: i, ossKey: safeKey, status: hit ? "ok" : "wrong", earned, points: pts, hits, comment: "" });
storedAnswers.push({ type: "solve", qIndex: i, ossKey: safeKey, earned, points: pts });
if (!hit) {
void recordWrong(user.id, "exam", paperId, paper.title, q, null, { ossKey: safeKey, earned, hits });
}
return;
}
const log = logs.get(i);
const okLog = log && log.status === "ok" ? log : null;
const earned = okLog ? Math.min(okLog.earned, pts) : 0;
+65 -4
View File
@@ -5,7 +5,7 @@ import Link from "next/link";
import { Camera, Check, Loader2, RotateCcw, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { QuizQ } from "@/lib/quiz-parse";
import type { QuizQ, SolveAnswerPayload } from "@/lib/quiz-parse";
import type { AnswerValue } from "@/lib/grammar";
import type { GradeVerdict } from "@/lib/ai-grade";
import { getSolveUploadUrl, gradeSolve } from "@/app/exam/actions";
@@ -18,7 +18,9 @@ type SolveState =
| { phase: "idle" }
| { phase: "preview"; blob: Blob; dataUrl: string }
| { phase: "grading"; dataUrl: string }
| { phase: "graded"; dataUrl: string; photoUrl: string; verdict: GradeVerdict };
| { phase: "graded"; dataUrl: string; photoUrl: string; verdict: GradeVerdict }
// xuchao: answer 模式照片传完即停,填最终答案待交卷秒判
| { phase: "uploaded"; dataUrl: string; ossKey: string; answer: string };
type CellValue = AV | SolveState;
@@ -56,6 +58,10 @@ export function QuizBlock({
const isAnswered = (q: QuizQ, a: CellValue): boolean => {
if (q.type === "solve") {
if (q.judgeMode === "answer")
return (
!!a && typeof a === "object" && "phase" in a && a.phase === "uploaded" && (a.answer?.trim() ?? "") !== ""
);
return !!a && typeof a === "object" && "phase" in a && a.phase === "graded" && a.verdict.status === "ok";
}
if (q.type === "fill") return typeof a === "string" && a.trim() !== "";
@@ -68,8 +74,15 @@ export function QuizBlock({
const submit = () => {
setError("");
startTransition(async () => {
// xuchao: 解答题得分以服务端判分日志为准,客户端只传 null 占位
const payload = answers.map((a, i) => (questions[i].type === "solve" ? null : (a as AnswerValue)));
// xuchao: rubric 解答题以服务端判分日志为准传 null;answer 模式传最终答案+照片 key
const payload = answers.map((a, i) => {
const q = questions[i];
if (q.type !== "solve") return a as AnswerValue;
if (q.judgeMode === "answer" && a && typeof a === "object" && "phase" in a && a.phase === "uploaded") {
return { answer: a.answer ?? "", ossKey: a.ossKey } as SolveAnswerPayload;
}
return null;
});
const r = submitter
? await submitter(payload as AnswerValue[])
: await submitQuiz(pointId, payload as AnswerValue[]);
@@ -93,6 +106,13 @@ export function QuizBlock({
{q.type === "solve" && <span className="ml-2 rounded bg-amber-100 px-1.5 py-0.5 text-xs font-semibold text-amber-700">{q.points} 分 · 拍照作答</span>}
</p>
{q.figure && (
<>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`/exam/${pointId}/${q.figure}`} alt="题目配图" className="mt-2 max-h-56 rounded-lg border border-slate-200 object-contain" />
</>
)}
{q.type === "fill" && (
<input
type="text"
@@ -142,6 +162,7 @@ export function QuizBlock({
<SolveInput
paperId={pointId}
qIndex={qi}
judgeMode={q.judgeMode ?? "rubric"}
value={a as SolveState | null}
disabled={!!result}
onChange={(v) => set(qi, v)}
@@ -221,12 +242,14 @@ export function QuizBlock({
function SolveInput({
paperId,
qIndex,
judgeMode,
value,
disabled,
onChange,
}: {
paperId: string;
qIndex: number;
judgeMode: "rubric" | "answer";
value: SolveState | null;
disabled: boolean;
onChange: (v: SolveState) => void;
@@ -235,6 +258,7 @@ function SolveInput({
const [busy, setBusy] = useState("");
const [err, setErr] = useState("");
const st = value ?? { phase: "idle" as const };
const isAnswerMode = judgeMode === "answer";
// xuchao: 压缩到 ≤2MB(先缩到 2000px 内,再降质量)
const compress = (file: File) =>
@@ -306,6 +330,11 @@ function SolveInput({
const resp = await fetch("/api/dev-photo", { method: "POST", body: fd });
if (!resp.ok) throw new Error("照片上传失败,请重试");
}
if (isAnswerMode) {
// xuchao: answer 模式不调 AI,照片存档后等待最终答案提交秒判
onChange({ phase: "uploaded", dataUrl, ossKey: up.key, answer: "" });
return;
}
setBusy("AI 判分中…");
let r = await gradeSolve(paperId, qIndex, up.key);
// xuchao: 调用失败自动重试一次
@@ -347,6 +376,38 @@ function SolveInput({
);
}
if (st.phase === "uploaded") {
return (
<div className="mt-2 space-y-2">
<input
ref={fileRef}
type="file"
accept="image/*"
capture="environment"
className="hidden"
onChange={(e) => {
void onPick(e.target.files?.[0]);
e.target.value = "";
}}
/>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={st.dataUrl} alt="解题照片(已上传)" className="max-h-40 rounded-lg border border-slate-200 object-contain" />
<p className="text-xs text-emerald-600">✅ 解题过程已上传</p>
<input
type="text"
value={st.answer}
disabled={disabled}
onChange={(e) => onChange({ ...st, answer: e.target.value })}
placeholder="填写最终答案,如:1/2 或 0.5"
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200"
/>
<button type="button" onClick={() => fileRef.current?.click()} disabled={disabled} className="text-xs text-indigo-600">
重新拍照
</button>
</div>
);
}
const dataUrl = st.phase === "preview" || st.phase === "grading" || st.phase === "graded" ? st.dataUrl : "";
return (
<div className="mt-2 space-y-2">
+9
View File
@@ -65,6 +65,15 @@ export default function LoginPage() {
去输入激活码
</Link>
</p>
<p className="text-center text-sm text-muted-foreground">
家里另一位家长想加入?{" "}
<Link
href="/register"
className="font-semibold text-indigo-600 underline-offset-4 hover:underline"
>
用邀请码加入家庭
</Link>
</p>
</form>
</CardContent>
</Card>
+174 -1
View File
@@ -1,16 +1,19 @@
"use server";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/db";
import { activationCodes, 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";
import { getSessionUser } from "@/lib/auth";
import { DEFAULT_RULE_POINTS, upsertPointRule } from "@/lib/points";
import { validateQuestions } from "@/lib/question-validation";
function hashCode(code: string) {
return crypto.createHash("sha256").update(code).digest("hex");
@@ -51,6 +54,21 @@ export async function createActivationCode(
return { code, childName: child.displayName };
}
// xuchao: 生成家庭邀请码(6 位,15 分钟一次性),对方凭码在 /register 注册加入
export async function generateFamilyInvite(): Promise<{ code?: string; error?: string }> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return { error: "请先以家长身份登录" };
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
await db.insert(familyInvites).values({
familyId: parent.familyId,
codeHash: hashCode(code),
createdBy: parent.id,
expiresAt: new Date(Date.now() + 15 * 60_000),
});
return { code };
}
// 家长补卡 / 撤销补卡:仅限过去的日期,补卡记录永久带标记
export async function makeupTask(instanceId: number, done: boolean) {
const parent = await getSessionUser();
@@ -243,3 +261,158 @@ 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: 保存试卷(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 = validateQuestions(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");
}
// xuchao: 上传试卷题目配图(几何体等)——存 public/exam/<paperId>/<uuid>.<ext>,返回文件名写回 q.figure
// 生产容器 public/exam 挂卷持久化(compose volumes: exam-figures),重建不丢
export async function uploadPaperFigure(
paperId: string,
file: File,
): Promise<{ filename?: string; error?: string }> {
const parent = await getSessionUser();
if (!parent || parent.role !== "parent") return { error: "请先以家长身份登录" };
if (!/^[a-z0-9-]+$/.test(paperId)) return { error: "试卷编号不合法" };
if (!file.type.startsWith("image/")) return { error: "只能上传图片文件" };
const ext = file.name.toLowerCase().split(".").pop();
if (!["png", "jpg", "jpeg", "webp"].includes(ext ?? "")) return { error: "只支持 png/jpg/webp 图片" };
if (file.size > 8 * 1024 * 1024) return { error: "图片不能超过 8MB" };
const buf = Buffer.from(await file.arrayBuffer());
const filename = `${crypto.randomUUID()}.${ext}`;
const dir = path.join(process.cwd(), "public", "exam", paperId);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, filename), buf);
return { filename };
}
+34 -13
View File
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ChildManage } from "./child-manage";
import { DevicesTab } from "./devices-tab";
import { FamilyManage } from "./family-manage";
import { OverviewTab } from "./overview-tab";
import { PointsManage } from "./points-manage";
import { TemplatesTab } from "./templates-tab";
@@ -67,7 +68,12 @@ export type DevicesData = {
isCurrent: boolean;
}[];
};
export type WeeklyRow = { childName: string; weekKey: string; score: number; passed: boolean };
// xuchao: 家庭管理数据——家庭名 + 家长成员 + 孩子成员
export type FamilyData = {
familyName: string;
parents: { id: number; name: string }[];
kids: { id: number; name: string }[];
};
const tabCls = "data-[state=active]:bg-white data-[state=active]:text-indigo-600 data-[state=active]:shadow-soft";
@@ -85,14 +91,14 @@ export function ParentDashboard({
overview,
templates,
devices,
weekly,
points,
family,
}: {
overview: OverviewData;
templates: TemplatesData;
devices: DevicesData;
weekly: WeeklyRow[];
points: PointsData;
family: FamilyData;
}) {
return (
<main className="relative mx-auto max-w-3xl space-y-5 p-4 pb-10">
@@ -151,20 +157,35 @@ 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>
<Section title="家庭管理" desc="添加家庭其他家长,一起查看孩子的学习情况">
<FamilyManage
familyName={family.familyName}
parents={family.parents}
kids={family.kids}
/>
</Section>
<Section title="孩子管理" desc="增加或删除孩子,删除会连同其记录一起删除">
<ChildManage kids={overview.kids.map((k) => ({ id: k.id, name: k.name }))} />
</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="space-y-2">
<Link href="/parent/exams" className="text-sm font-medium text-indigo-600">
← 试卷列表
</Link>
<h1 className="text-xl font-extrabold break-words 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="space-y-2">
<Link href="/parent/exams" className="text-sm font-medium text-indigo-600">
← 试卷列表
</Link>
<h1 className="text-xl font-extrabold break-words 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>
);
}
+182
View File
@@ -0,0 +1,182 @@
"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 type { QuizQ } from "@/lib/quiz-parse";
import { deleteExamPaper, saveExamPaper } from "../actions";
import { QuestionList } from "./question-list";
// 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: 试卷编辑器——元信息表单 + 结构化题目编辑器;保存走服务端完整校验
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 ?? "",
});
// xuchao: 题目用结构化数组管理,保存时序列化为 JSON(与旧 JSON 形状一致)
const [questions, setQuestions] = useState<QuizQ[]>(() => {
try {
return paper ? (JSON.parse(paper.questions) as QuizQ[]) : [];
} catch {
return [];
}
});
const [msg, setMsg] = useState<{ ok?: boolean; text: string } | null>(null);
const [pending, startTransition] = useTransition();
const save = () => {
setMsg(null);
const fd = new FormData();
(Object.keys(f) as (keyof typeof f)[]).forEach((k) => fd.set(k, f[k]));
fd.set("questions", JSON.stringify(questions));
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 grid-cols-1 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">
<Label>题目(结构化编辑)</Label>
<QuestionList
value={questions}
onChange={(qs) => setQuestions(qs)}
paperId={paper?.paperId ?? f.paperId}
/>
</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 flex-wrap 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>
);
}
+117
View File
@@ -0,0 +1,117 @@
// @vitest-environment jsdom
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { QuestionList } from "./question-list";
import type { QuizQ } from "@/lib/quiz-parse";
const choiceQ = { type: "choice" as const, stem: "1+1=?", options: ["1", "2"], answer: 1, explain: "e" };
beforeEach(() => {
vi.spyOn(window, "confirm").mockReturnValue(true);
});
describe("QuestionList 结构化编辑", () => {
it("渲染题目卡片(题型徽标+题干)并可删除", () => {
let saved: QuizQ[] = [{ ...choiceQ }];
render(<QuestionList value={saved} onChange={(v) => (saved = v)} paperId="g7s1-m09-1" />);
expect(screen.getByText("选择题")).toBeInTheDocument();
expect(screen.getByText("1+1=?")).toBeInTheDocument();
fireEvent.click(screen.getByLabelText("删除第 1 题"));
expect(saved.length).toBe(0);
});
it("新增选择题:填题干/选项/点选答案/解析后保存进列表", async () => {
const user = userEvent.setup();
let saved: QuizQ[] = [];
render(<QuestionList value={[]} onChange={(v) => (saved = v)} paperId="g7s1-m09-1" />);
await user.click(screen.getByText("新增题目"));
await user.selectOptions(screen.getByLabelText("题型"), "choice");
await user.type(screen.getByLabelText("题干"), "2+2=?");
await user.click(screen.getByText("+ 添加选项"));
await user.type(screen.getByPlaceholderText("选项1"), "3");
await user.click(screen.getByText("+ 添加选项"));
await user.type(screen.getByPlaceholderText("选项2"), "4");
fireEvent.click(screen.getByLabelText("选 4 为正确答案"));
await user.type(screen.getByLabelText("解析"), "e1");
await user.click(screen.getByText("完成"));
expect((saved[0] as Record<string, unknown>).stem).toBe("2+2=?");
expect((saved[0] as Record<string, unknown>).answer).toBe(1);
expect((saved[0] as Record<string, unknown>).explain).toBe("e1");
});
it("新建应用题仅 answer 模式(无判分模式 select)", async () => {
const user = userEvent.setup();
render(<QuestionList value={[]} onChange={() => {}} paperId="g7s1-m09-1" />);
await user.click(screen.getByText("新增题目"));
await user.selectOptions(screen.getByLabelText("题型"), "solve");
expect(screen.queryByLabelText("判分模式")).not.toBeInTheDocument();
expect(screen.getByText("仅最终答案(秒判)")).toBeInTheDocument();
});
it("编辑存量 rubric 题显示只读徽标", () => {
render(
<QuestionList
value={[{ type: "solve", stem: "解方程", points: 10, judgeMode: "rubric" as const, reference: "x=2", rubric: [{ point: "过程", score: 6 }], explain: "e" }]}
onChange={() => {}}
paperId="g7s1-m09-1"
/>,
);
fireEvent.click(screen.getByLabelText("编辑第 1 题"));
expect(screen.queryByLabelText("判分模式")).not.toBeInTheDocument();
expect(screen.getByText("AI 逐评分点判分(存量题,保留原评分点)")).toBeInTheDocument();
});
it("编辑存量无 judgeMode 字段的题显示 AI 判分徽标与必填参考解答语义", () => {
render(
<QuestionList
value={[{ type: "solve", stem: "解方程", points: 10, reference: "x=2", rubric: [{ point: "过程", score: 6 }], explain: "e" }]}
onChange={() => {}}
paperId="g7s1-m09-1"
/>,
);
fireEvent.click(screen.getByLabelText("编辑第 1 题"));
expect(screen.getByText("AI 逐评分点判分(存量题,保留原评分点)")).toBeInTheDocument();
expect(screen.getByText("参考解答(完整解题过程,展示给孩子)")).toBeInTheDocument();
});
it("题干为空保存时报错,不写入列表", async () => {
const user = userEvent.setup();
let saved: QuizQ[] = [];
render(<QuestionList value={[]} onChange={(v) => (saved = v)} paperId="g7s1-m09-1" />);
await user.click(screen.getByText("新增题目"));
await user.click(screen.getByText("完成"));
expect(saved.length).toBe(0);
expect(screen.getByText(/缺少题干/)).toBeInTheDocument();
});
it("删除选项后 answer 下标正确回落", async () => {
const user = userEvent.setup();
let saved: QuizQ[] = [{ type: "choice" as const, stem: "q", options: ["a", "b", "c"], answer: 2, explain: "e" }];
render(<QuestionList value={saved} onChange={(v) => (saved = v)} paperId="g7s1-m09-1" />);
fireEvent.click(screen.getByLabelText("编辑第 1 题"));
// xuchao: buttons = [上移,下移,编辑,删除, 取消, 添加选项, 删a, 删b, 删c, 完成] → 删b = [7]
const buttons = screen.getAllByRole("button");
fireEvent.click(buttons[7]);
// xuchao: 点"完成"保存,onChange 被调用
await user.click(screen.getByText("完成"));
const d = saved[0] as Record<string, unknown>;
expect(d.answer).toBe(1);
});
it("已有配图显示预览并可移除", () => {
let saved: QuizQ[] = [{ ...choiceQ, figure: "tri.png" as const }];
render(<QuestionList value={saved} onChange={(v) => (saved = v)} paperId="g7s1-m09-1" />);
fireEvent.click(screen.getByLabelText("编辑第 1 题"));
expect(screen.getByAltText("题目配图")).toHaveAttribute("src", "/exam/g7s1-m09-1/tri.png");
fireEvent.click(screen.getByText("移除配图"));
fireEvent.click(screen.getByText("完成"));
expect((saved[0] as Record<string, unknown>).figure).toBeUndefined();
});
it("无配图时显示上传配图按钮", () => {
render(<QuestionList value={[{ ...choiceQ }]} onChange={() => {}} paperId="g7s1-m09-1" />);
fireEvent.click(screen.getByLabelText("编辑第 1 题"));
expect(screen.getByText("上传配图")).toBeInTheDocument();
});
});
+300
View File
@@ -0,0 +1,300 @@
"use client";
import { Fragment, useRef, useState, useTransition } from "react";
import { ArrowDown, ArrowUp, ImagePlus, Pencil, Plus, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { QuizQ } from "@/lib/quiz-parse";
import { uploadPaperFigure } from "../actions";
const TYPE_LABEL: Record<string, string> = {
judge: "判断题",
choice: "选择题",
fill: "填空题",
solve: "应用题",
};
const TYPE_ORDER = ["judge", "choice", "fill", "solve"];
// xuchao: 结构化题目编辑器——题型联动表单;产出 QuizQ JSON(与服务端校验同文案)
export function QuestionList({
value,
onChange,
paperId,
}: {
value: QuizQ[];
onChange: (qs: QuizQ[]) => void;
paperId: string;
}) {
const [editIndex, setEditIndex] = useState<number | null>(null);
const [draft, setDraft] = useState<QuizQ | null>(null);
const [error, setError] = useState("");
const [figError, setFigError] = useState("");
const [pendingFig, startFig] = useTransition();
const figureRef = useRef<HTMLInputElement>(null);
// xuchao: 配图上传(几何体等)——成功后把文件名写入题目 draft.figure
const uploadFigure = (file: File | undefined) => {
if (!file || pendingFig) return;
setFigError("");
startFig(async () => {
const r = await uploadPaperFigure(paperId, file);
if (r.error) setFigError(r.error);
else update({ figure: r.filename });
});
};
const startNew = () => {
setError("");
setDraft({ type: "choice", stem: "", options: [""], answer: 0, explain: "" });
setEditIndex(null);
};
const startEdit = (i: number) => {
setError("");
setDraft(JSON.parse(JSON.stringify(value[i])) as QuizQ);
setEditIndex(i);
};
const update = (patch: Partial<QuizQ>) => setDraft((d) => ({ ...(d as QuizQ), ...patch }));
const commit = () => {
const d = draft as QuizQ;
const no = `第 ${editIndex != null ? editIndex + 1 : value.length + 1} 题`;
if (!d.stem.trim()) return setError(`${no}缺少题干(stem)`);
if (!d.explain.trim()) return setError(`${no}缺少解析(explain)`);
if (d.type === "choice" && !d.options?.some((o) => o.trim())) return setError(`${no}缺少选项(options)`);
if (d.type === "fill" && (d.answers ?? []).every((a) => !a.trim())) return setError(`${no}缺少参考答案(answers 数组)`);
if (d.type === "solve") {
if (d.judgeMode === "answer") {
if ((d.answers ?? []).every((a) => !a.trim())) return setError(`${no}缺少最终答案(answers 数组)`);
} else if (!d.reference?.trim()) {
return setError(`${no}缺少参考解答(reference)`);
}
if (!(d.points && d.points > 0)) return setError(`${no}缺少满分(points>0)`);
}
setError("");
const q = { ...d, stem: d.stem.trim(), explain: d.explain.trim() };
const next = editIndex == null ? [...value, q] : value.map((x, i) => (i === editIndex ? q : x));
onChange(next);
setDraft(null);
};
const remove = (i: number) => {
if (confirm("确定删除这道题?")) onChange(value.filter((_, idx) => idx !== i));
};
const move = (i: number, dir: -1 | 1) => {
const j = i + dir;
if (j < 0 || j >= value.length) return;
const next = [...value];
[next[i], next[j]] = [next[j], next[i]];
onChange(next);
};
// xuchao: 编辑表单——编辑存量题渲染在该题卡片下方,新增时渲染在列表末尾
const draftForm = draft ? (
<div className="rounded-xl border border-indigo-200 bg-white p-3">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<label className="text-sm font-medium text-slate-700">
题型
<select
value={draft.type}
aria-label="题型"
onChange={(e) => {
const t = e.target.value as QuizQ["type"];
update({ type: t, options: undefined, answers: undefined, reference: undefined, rubric: undefined, judgeMode: undefined, points: undefined, ...(t === "solve" ? { judgeMode: "answer", points: 10 } : {}) });
}}
className="ml-2 h-8 rounded-lg border border-slate-200 bg-white px-2 text-sm"
>
{TYPE_ORDER.map((t) => (
<option key={t} value={t}>
{TYPE_LABEL[t]}
</option>
))}
</select>
</label>
<Button size="sm" variant="ghost" onClick={() => setDraft(null)}>
<X className="size-4" /> 取消
</Button>
</div>
<div className="space-y-2">
<div className="space-y-1">
<Label>题干</Label>
<Input aria-label="题干" value={draft.stem} onChange={(e) => update({ stem: e.target.value })} />
</div>
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label>题目配图(几何体等,可选)</Label>
{draft.figure && (
<Button size="sm" variant="ghost" className="h-7" onClick={() => update({ figure: undefined })}>
<X className="size-4" /> 移除配图
</Button>
)}
</div>
{draft.figure ? (
<>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={`/exam/${paperId}/${draft.figure}`} alt="题目配图" className="max-h-48 rounded-lg border border-slate-200 object-contain" />
{figError && <p className="text-xs font-medium text-destructive">{figError}</p>}
</>
) : (
<div>
<input
ref={figureRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
uploadFigure(e.target.files?.[0]);
e.target.value = "";
}}
/>
<Button type="button" size="sm" variant="outline" className="h-8" disabled={pendingFig} onClick={() => figureRef.current?.click()}>
<ImagePlus className="size-4" /> {pendingFig ? "上传中…" : "上传配图"}
</Button>
{figError && <p className="mt-1 text-xs font-medium text-destructive">{figError}</p>}
</div>
)}
</div>
{draft.type === "choice" && (
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label>选项(点选正确答案)</Label>
<Button size="sm" variant="outline" className="h-7" onClick={() => update({ options: [...(draft.options ?? []), ""] })}>
+ 添加选项
</Button>
</div>
{(draft.options ?? []).map((o, oi) => (
<div key={oi} className="flex items-center gap-2">
<input
type="radio"
name="opt"
checked={draft.answer === oi}
onChange={() => update({ answer: oi })}
aria-label={`选 ${o || `选项${oi + 1}`} 为正确答案`}
/>
<Input placeholder={`选项${oi + 1}`} value={o} onChange={(e) => update({ options: (draft.options ?? []).map((x, xi) => (xi === oi ? e.target.value : x)) })} />
<Button size="sm" variant="ghost" className="h-7 px-2" onClick={() => {
const newOpts = (draft.options ?? []).filter((_, xi) => xi !== oi);
const patch: Partial<QuizQ> = { options: newOpts };
if (draft.answer === oi) patch.answer = 0;
else if (typeof draft.answer === "number" && draft.answer > oi) patch.answer = draft.answer - 1;
update(patch);
}}>
<X className="size-4" />
</Button>
</div>
))}
</div>
)}
{draft.type === "judge" && (
<div className="space-y-1">
<Label>答案</Label>
<div className="flex gap-3 text-sm">
{[0, 1].map((v) => (
<label key={v} className="flex items-center gap-1">
<input type="radio" checked={draft.answer === v} onChange={() => update({ answer: v })} />
{v === 0 ? "对" : "错"}
</label>
))}
</div>
</div>
)}
{(draft.type === "fill" || (draft.type === "solve" && draft.judgeMode === "answer")) && (
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label>{draft.type === "fill" ? "参考答案(等价答法可填多个)" : "最终答案(等价答法可填多个)"}</Label>
<Button size="sm" variant="outline" className="h-7" onClick={() => update({ answers: [...(draft.answers ?? []), ""] })}>
+ 添加答案
</Button>
</div>
{(draft.answers ?? []).map((a, ai) => (
<div key={ai} className="flex items-center gap-2">
<Input value={a} onChange={(e) => update({ answers: (draft.answers ?? []).map((x, xi) => (xi === ai ? e.target.value : x)) })} />
<Button size="sm" variant="ghost" className="h-7 px-2" onClick={() => update({ answers: (draft.answers ?? []).filter((_, xi) => xi !== ai) })}>
<X className="size-4" />
</Button>
</div>
))}
</div>
)}
{draft.type === "solve" && (
<div className="space-y-2">
<div className="space-y-1">
<Label>分值</Label>
<Input
aria-label="分值"
type="number"
min={1}
placeholder="10"
value={draft.points ?? ""}
onChange={(e) => update({ points: Number(e.target.value) || undefined })}
/>
</div>
<div className="rounded-md bg-slate-50 px-3 py-2 text-xs text-slate-600">
{draft.judgeMode === "answer" ? "仅最终答案(秒判)" : "AI 逐评分点判分(存量题,保留原评分点)"}
</div>
<div className="space-y-1">
<Label>{draft.judgeMode === "answer" ? "参考解答(可选,给孩子看)" : "参考解答(完整解题过程,展示给孩子)"}</Label>
<Input aria-label="参考解答" value={draft.reference ?? ""} onChange={(e) => update({ reference: e.target.value })} />
</div>
</div>
)}
<div className="space-y-1">
<Label>解析</Label>
<Input aria-label="解析" value={draft.explain} onChange={(e) => update({ explain: e.target.value })} />
</div>
{error && <p className="text-sm font-medium text-destructive">{error}</p>}
<Button size="sm" onClick={commit}>
完成
</Button>
</div>
</div>
) : null;
return (
<div className="space-y-3">
{value.map((q, i) => {
const def = q as QuizQ;
return (
<Fragment key={i}>
<div className="rounded-xl border border-slate-100 bg-slate-50/60 p-3">
<div className="flex items-center gap-2">
<span className="shrink-0 rounded-full bg-indigo-100 px-2 py-0.5 text-xs font-medium text-indigo-700">{TYPE_LABEL[def.type]}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-slate-800">{def.stem}</span>
<span className="ml-auto flex shrink-0 items-center gap-1">
<button type="button" aria-label={`上移第 ${i + 1} 题`} className="text-muted-foreground hover:text-indigo-600" onClick={() => move(i, -1)}>
<ArrowUp className="size-4" />
</button>
<button type="button" aria-label={`下移第 ${i + 1} 题`} className="text-muted-foreground hover:text-indigo-600" onClick={() => move(i, 1)}>
<ArrowDown className="size-4" />
</button>
<button type="button" aria-label={`编辑第 ${i + 1} 题`} className="text-muted-foreground hover:text-indigo-600" onClick={() => startEdit(i)}>
<Pencil className="size-4" />
</button>
<button type="button" aria-label={`删除第 ${i + 1} 题`} className="text-muted-foreground hover:text-destructive" onClick={() => remove(i)}>
<Trash2 className="size-4" />
</button>
</span>
</div>
</div>
{draft && editIndex === i && draftForm}
</Fragment>
);
})}
{draft && editIndex == null && draftForm}
{!draft && (
<Button variant="outline" onClick={startNew}>
<Plus className="size-4" /> 新增题目
</Button>
)}
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
"use client";
import { useState, useTransition } from "react";
import { UserPlus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { generateFamilyInvite } from "./actions";
// xuchao: 家庭管理——展示成员列表,生成一次性邀请码让其他家长注册加入
export function FamilyManage({
familyName,
parents,
kids,
}: {
familyName: string;
parents: { id: number; name: string }[];
kids: { id: number; name: string }[];
}) {
const [invite, setInvite] = useState<{ code?: string; error?: string } | null>(null);
const [pending, startTransition] = useTransition();
const gen = () => {
setInvite(null);
startTransition(async () => {
setInvite(await generateFamilyInvite());
});
};
return (
<div className="space-y-3">
<p className="text-sm text-slate-700">
<span className="font-semibold">{familyName}</span> · {parents.length} 位家长 · {kids.length} 个孩子
</p>
<div className="space-y-1.5">
{parents.map((p) => (
<div key={p.id} className="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm">
<span className="font-medium text-slate-800">{p.name}</span>
<span className="rounded-full bg-indigo-100 px-2 py-0.5 text-xs font-medium text-indigo-700">家长</span>
</div>
))}
{kids.map((k) => (
<div key={k.id} className="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm">
<span className="font-medium text-slate-800">{k.name}</span>
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500">孩子</span>
</div>
))}
</div>
<div className="flex flex-wrap items-center gap-3">
<Button size="sm" variant="secondary" disabled={pending} onClick={gen}>
<UserPlus className="size-4" /> {pending ? "生成中…" : "生成邀请码"}
</Button>
{invite?.error && <p className="text-sm font-medium text-destructive">{invite.error}</p>}
{invite?.code && (
<p className="text-sm text-slate-700">
邀请码{" "}
<span className="font-mono text-lg font-bold tracking-widest text-indigo-600">{invite.code}</span>
<span className="ml-1 text-xs text-muted-foreground">15 分钟有效,一次性</span>
</p>
)}
</div>
</div>
);
}
+20 -22
View File
@@ -13,6 +13,7 @@ import {
weeklyTest,
wrongBook,
wordRecording,
families,
} from "@/db/schema";
import { SESSION_COOKIE, getSessionUser } from "@/lib/auth";
import { addDays, dowOf, todayStr } from "@/lib/dates";
@@ -27,10 +28,10 @@ import { viewUrl } from "@/lib/oss";
import {
ParentDashboard,
type DevicesData,
type FamilyData,
type OverviewData,
type PointsData,
type TemplatesData,
type WeeklyRow,
} from "./dashboard";
const SH = { timeZone: "Asia/Shanghai" } as const;
@@ -179,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: [] };
@@ -219,13 +200,30 @@ export default async function ParentPage() {
});
}
// ===== 家庭管理(家庭名 + 全部成员) =====
const [familyRow] = await db
.select({ name: families.name })
.from(families)
.where(eq(families.id, parent.familyId))
.limit(1);
const parentRows = await db
.select({ id: users.id, displayName: users.displayName })
.from(users)
.where(and(eq(users.familyId, parent.familyId), eq(users.role, "parent")))
.orderBy(asc(users.id));
const family: FamilyData = {
familyName: familyRow?.name ?? "我的家庭",
parents: parentRows.map((p) => ({ id: p.id, name: p.displayName })),
kids: kids.map((k) => ({ id: k.id, name: k.name })),
};
return (
<ParentDashboard
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>
);
}
+68
View File
@@ -0,0 +1,68 @@
"use server";
import crypto from "node:crypto";
import bcrypt from "bcryptjs";
import { and, eq, gt, isNull } from "drizzle-orm";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/db";
import { familyInvites, users } from "@/db/schema";
import { createSession } from "@/lib/auth";
function hashCode(code: string) {
return crypto.createHash("sha256").update(code).digest("hex");
}
const registerSchema = z.object({
displayName: z.string().trim().min(1, "请输入称呼").max(20, "称呼最多 20 字"),
phone: z.string().regex(/^1\d{10}$/, "请输入 11 位手机号"),
password: z.string().min(6, "密码至少 6 位"),
code: z.string().regex(/^\d{6}$/, "邀请码是 6 位数字"),
});
export type RegisterState = { error?: string } | null;
// xuchao: 家长凭邀请码注册:校验码→查重手机号→事务(码标记已用+建家长)→自动登录跳家长中心
export async function registerWithInvite(
_prev: RegisterState,
formData: FormData,
): Promise<RegisterState> {
const parsed = registerSchema.safeParse({
displayName: formData.get("displayName"),
phone: formData.get("phone"),
password: formData.get("password"),
code: formData.get("code"),
});
if (!parsed.success) return { error: parsed.error.issues[0].message };
const { displayName, phone, password, code } = parsed.data;
const [invite] = await db
.select({ id: familyInvites.id, familyId: familyInvites.familyId })
.from(familyInvites)
.where(
and(
eq(familyInvites.codeHash, hashCode(code)),
isNull(familyInvites.usedAt),
gt(familyInvites.expiresAt, new Date()),
),
)
.limit(1);
if (!invite) return { error: "邀请码无效或已过期,请让家长重新生成" };
const [dup] = await db.select({ id: users.id }).from(users).where(eq(users.phone, phone)).limit(1);
if (dup) return { error: "该手机号已注册" };
const passwordHash = await bcrypt.hash(password, 10);
const newUserId = await db.transaction(async (tx) => {
await tx.update(familyInvites).set({ usedAt: new Date() }).where(eq(familyInvites.id, invite.id));
const [created] = await tx
.insert(users)
.values({ familyId: invite.familyId, role: "parent", displayName, phone, passwordHash })
.$returningId();
return created.id;
});
await createSession(newUserId, "家长设备", 30);
redirect("/parent");
}
+83
View File
@@ -0,0 +1,83 @@
"use client";
import { useActionState } from "react";
import Link from "next/link";
import { UserPlus } from "lucide-react";
import { BackgroundBlobs } from "@/components/background-blobs";
import { registerWithInvite } from "./actions";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export default function RegisterPage() {
const [state, formAction, pending] = useActionState(registerWithInvite, null);
return (
<main className="relative flex min-h-dvh items-center justify-center p-4">
<BackgroundBlobs />
<Card className="w-full max-w-sm border-slate-100 shadow-soft transition-shadow duration-200 hover:shadow-lift">
<CardHeader className="items-center gap-3 text-center">
<div className="flex size-14 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-btn">
<UserPlus className="size-8 text-white" />
</div>
<h1 className="text-2xl font-extrabold tracking-tight">加入家庭</h1>
<p className="text-sm text-muted-foreground">需要家里已有成员的邀请码</p>
</CardHeader>
<CardContent>
<form action={formAction} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="displayName">称呼</Label>
<Input id="displayName" name="displayName" placeholder="如:妈妈" required />
</div>
<div className="space-y-2">
<Label htmlFor="phone">手机号</Label>
<Input
id="phone"
name="phone"
type="tel"
inputMode="numeric"
autoComplete="username"
placeholder="11 位手机号"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">密码</Label>
<Input
id="password"
name="password"
type="password"
autoComplete="new-password"
placeholder="至少 6 位"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="code">邀请码</Label>
<Input
id="code"
name="code"
inputMode="numeric"
maxLength={6}
placeholder="6 位数字"
className="font-mono tracking-widest"
required
/>
</div>
{state?.error && <p className="text-sm font-medium text-destructive">{state.error}</p>}
<Button type="submit" className="w-full" size="lg" disabled={pending}>
{pending ? "注册中…" : "注册并加入家庭"}
</Button>
<p className="text-center text-sm text-muted-foreground">
已有账号?{" "}
<Link href="/login" className="font-semibold text-indigo-600 underline-offset-4 hover:underline">
去登录
</Link>
</p>
</form>
</CardContent>
</Card>
</main>
);
}
+15
View File
@@ -78,6 +78,21 @@ export const activationCodes = mysqlTable("activation_code", {
usedAt: datetime("used_at"),
});
// ===== 家庭邀请码(家长生成,其他家长凭码注册加入;一次性,15 分钟)=====
export const familyInvites = mysqlTable("family_invite", {
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
familyId: bigint("family_id", { mode: "number" })
.notNull()
.references(() => families.id, { onDelete: "cascade" }),
codeHash: varchar("code_hash", { length: 64 }).notNull(),
createdBy: bigint("created_by", { mode: "number" })
.notNull()
.references(() => users.id),
createdAt: datetime("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
expiresAt: datetime("expires_at").notNull(),
usedAt: datetime("used_at"),
});
// ===== 周模板(每个孩子 × 每周几 × 每条任务)=====
export const taskTemplates = mysqlTable(
"task_template",
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { answersMatch, normalizeAnswer, solveAnswerHit } from "./answer-match";
describe("normalizeAnswer", () => {
it("分数转小数", () => {
expect(normalizeAnswer("1/2")).toBe("0.5");
expect(normalizeAnswer("2/4")).toBe("0.5");
});
it("百分数转小数", () => {
expect(normalizeAnswer("50%")).toBe("0.5");
});
it("小数去尾零", () => {
expect(normalizeAnswer("0.50")).toBe("0.5");
});
it("整数原样", () => {
expect(normalizeAnswer("10")).toBe("10");
});
it("文本去空白/全角/大小写", () => {
expect(normalizeAnswer("ABC")).toBe("abc");
expect(normalizeAnswer("10 个")).toBe("10个");
});
});
describe("answersMatch", () => {
it("等值命中:1/2 ≡ 0.5", () => {
expect(answersMatch(["0.5", "1/2"], "1/2")).toBe(true);
expect(answersMatch(["0.5"], "0.50")).toBe(true);
});
it("百分数命中", () => {
expect(answersMatch(["0.5"], "50%")).toBe(true);
});
it("文本大小写/全角不敏感", () => {
expect(answersMatch(["across"], "ACROSS")).toBe(true);
});
it("单位严格:10个 ≠ 10", () => {
expect(answersMatch(["10个"], "10")).toBe(false);
expect(answersMatch(["10", "10个"], "10个")).toBe(true);
});
it("空白答案不判对", () => {
expect(answersMatch(["0.5"], " ")).toBe(false);
});
it("空期望数组不判对", () => {
expect(answersMatch([], "0.5")).toBe(false);
});
});
describe("solveAnswerHit", () => {
const q = { answers: ["2", "x=2"] };
it("命中最终答案", () => {
expect(solveAnswerHit({ answers: ["2"] }, "2")).toBe(true);
expect(solveAnswerHit(q, " x = 2 ")).toBe(true);
});
it("未命中", () => {
expect(solveAnswerHit(q, "3")).toBe(false);
expect(solveAnswerHit({ answers: [] }, "2")).toBe(false);
});
});
+33
View File
@@ -0,0 +1,33 @@
// xuchao: 答案等价判定——数值归一(分数/小数/百分数互转),文本归一(去空白/全角/小写)
import type { QuizQ } from "@/lib/quiz-parse";
const toHalf = (s: string) =>
s.replace(/[!-~]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0)).replace(/ /g, " ");
function stripWs(s: string): string {
return toHalf(s).replace(/\s+/g, "").toLowerCase();
}
export function normalizeAnswer(s: string): string {
const t = stripWs(s);
const frac = t.match(/^(-?\d+)\/(-?\d+)$/);
if (frac && Number(frac[2]) !== 0) {
const v = Number(frac[1]) / Number(frac[2]);
if (Number.isFinite(v)) return String(v);
}
const pct = t.match(/^(-?\d+(?:\.\d+)?)%$/);
if (pct) return String(Number(pct[1]) / 100);
if (/^-?\d+\.\d+$/.test(t)) return String(Number(t));
return t;
}
// xuchao: 任一期望答案等值命中即判对;空白答案一律不判对
export function answersMatch(expected: string[], given: string): boolean {
const g = normalizeAnswer(given);
if (!g) return false;
return expected.some((x) => normalizeAnswer(x) === g);
}
// xuchao: 应用题 answer 模式判定——最终答案等值即判对
export function solveAnswerHit(q: Pick<QuizQ, "answers">, given: string): boolean {
return answersMatch(q.answers ?? [], given);
}
+89
View File
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { validateQuestions } from "./question-validation";
const base = {
type: "choice",
stem: "x?",
options: ["a", "b"],
answer: 0,
explain: "e",
};
describe("validateQuestions 基础", () => {
it("解析失败报错", () => {
expect(validateQuestions("{bad").error).toContain("解析失败");
});
it("非数组报错", () => {
expect(validateQuestions("{}").error).toContain("必须是 JSON 数组");
});
it("空数组报错", () => {
expect(validateQuestions("[]").error).toContain("至少需要 1 道题");
});
it("合法 choice 通过并返回题数", () => {
const r = validateQuestions(JSON.stringify([base]));
expect(r.error).toBeUndefined();
expect(r.count).toBe(1);
});
it("choice 缺 options 报错", () => {
const { stem, answer, explain } = base;
expect(validateQuestions(JSON.stringify([{ type: "choice", stem, answer, explain }])).error).toContain("缺少选项");
});
it("fill 缺 answers 报错", () => {
expect(
validateQuestions(JSON.stringify([{ type: "fill", stem: "f?", explain: "e" }])).error,
).toContain("缺少参考答案");
});
it("figure 合法/非法文件名", () => {
expect(validateQuestions(JSON.stringify([{ ...base, figure: "tri.png" }])).error).toBeUndefined();
expect(validateQuestions(JSON.stringify([{ ...base, figure: "a b.png" }])).error).toContain("配图文件名不合法");
expect(validateQuestions(JSON.stringify([{ ...base, figure: " " }])).error).toContain("配图文件名不合法");
});
});
describe("validateQuestions solve / judgeMode", () => {
const solveRubric = {
type: "solve",
stem: "解方程",
points: 10,
reference: "x=2",
rubric: [{ point: "过程", score: 6 }, { point: "答案", score: 4 }],
explain: "e",
};
it("合法 rubric solve(缺省 judgeMode)通过", () => {
expect(validateQuestions(JSON.stringify([solveRubric])).error).toBeUndefined();
});
it("rubric 模式缺 reference 报错", () => {
const { reference: _ref, ...rest } = solveRubric;
expect(validateQuestions(JSON.stringify([rest])).error).toContain("缺少参考解答");
});
it("rubric 模式缺 rubric 评分点报错", () => {
const { rubric: _rub, ...rest } = solveRubric;
expect(validateQuestions(JSON.stringify([rest])).error).toContain("缺少评分点");
});
it("answer 模式缺 answers 报错,不要求 reference", () => {
const q = { ...solveRubric, judgeMode: "answer", answers: [], rubric: undefined };
delete q.rubric;
expect(validateQuestions(JSON.stringify([q])).error).toContain("缺少最终答案");
const ok = { ...solveRubric, judgeMode: "answer", answers: ["2"], rubric: undefined, reference: undefined };
delete ok.rubric;
delete ok.reference;
expect(validateQuestions(JSON.stringify([ok])).error).toBeUndefined();
});
it("answer 模式带 rubric 报错", () => {
const q = { ...solveRubric, judgeMode: "answer", answers: ["2"], rubric: [solveRubric.rubric[0]] };
expect(validateQuestions(JSON.stringify([q])).error).toContain("不应携带 rubric");
});
it("judgeMode 非法值报错", () => {
const q = { ...solveRubric, judgeMode: "auto" };
expect(validateQuestions(JSON.stringify([q])).error).toContain("judgeMode 非法");
});
it("存量 86 题形状全通过(48 choice/30 fill/8 solve 代表用例)", () => {
const fill = { type: "fill", stem: "f?", answers: ["a", "b"], explain: "e" };
const arr: unknown[] = Array.from({ length: 48 }, () => base);
arr.push(...Array.from({ length: 30 }, () => fill));
arr.push(...Array.from({ length: 8 }, () => solveRubric));
const r = validateQuestions(JSON.stringify(arr));
expect(r.error).toBeUndefined();
expect(r.count).toBe(86);
});
});
+52
View File
@@ -0,0 +1,52 @@
// xuchao: 试卷题目 JSON 形状校验(服务端保存前唯一写入门禁),纯函数便于单测
export const EXAM_TYPES = ["choice", "fill", "judge", "order", "match", "solve"] as const;
const SOLVE_JUDGE_MODES = ["rubric", "answer"] as const;
export type ValidationResult = { error?: string; count?: number };
export function validateQuestions(raw: string): ValidationResult {
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 as (typeof EXAM_TYPES)[number];
if (!EXAM_TYPES.includes(t)) return { error: `${no}的 type 非法:${String(q.type)}` };
if (typeof q.figure === "string" && (q.figure.trim() === "" || !/^[\w.-]+$/.test(q.figure))) {
return { error: `${no}配图文件名不合法(figure)` };
}
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 === "choice" && (typeof q.answer !== "number" || q.answer < 0 || q.answer >= (q.options as unknown[]).length)) return { error: `${no}(choice)答案下标越界` };
if (t === "fill" && !Array.isArray(q.answers)) return { error: `${no}(fill)缺少参考答案(answers 数组)` };
if (t === "order") {
if (!Array.isArray(q.answer)) return { error: `${no}(order)缺少答案(answer 数组)` };
if (!Array.isArray(q.words) || q.words.length === 0) return { error: `${no}(order)缺少词块(words)` };
}
if (t === "match" && !Array.isArray(q.pairs)) return { error: `${no}(match)缺少配对(pairs 数组)` };
if (t === "solve") {
if (typeof q.points !== "number" || q.points <= 0) return { error: `${no}(solve)缺少满分(points>0)` };
const mode = q.judgeMode;
if (mode !== undefined && !SOLVE_JUDGE_MODES.includes(mode as (typeof SOLVE_JUDGE_MODES)[number])) {
return { error: `${no}(solve)judgeMode 非法:${String(mode)}` };
}
if (mode === "answer") {
if (!Array.isArray(q.answers) || q.answers.length === 0) return { error: `${no}(solve·answer 模式)缺少最终答案(answers 数组)` };
if (Array.isArray(q.rubric) && q.rubric.length > 0) return { error: `${no}(solve·answer 模式)不应携带 rubric 评分点` };
} else {
if (typeof q.reference !== "string" || !q.reference.trim()) return { error: `${no}(solve)缺少参考解答(reference)` };
if (!Array.isArray(q.rubric) || q.rubric.length === 0) return { error: `${no}(solve·rubric 模式)缺少评分点(rubric)` };
}
}
}
return { count: arr.length };
}
+6
View File
@@ -13,6 +13,9 @@ export type QuizQ = {
points?: number; // solve:本题满分
reference?: string; // solve:完整参考解答
rubric?: { point: string; score: number }[]; // solve:评分点,合计 = points
// xuchao: 应用题判定模式——rubric=AI 逐评分点(缺省,存量兼容);answer=最终答案数组匹配秒判
judgeMode?: "rubric" | "answer";
// judgeMode==="answer" 时复用上面 answers 数组(等价答法都填)
// xuchao: 错题本里的解答题作答快照(照片 + 逐点判定),交卷入错题本时写入
solveSnap?: { ossKey: string; earned: number; hits: { point: string; score: number; hit: boolean; reason: string }[] };
explain: string;
@@ -33,3 +36,6 @@ export function extractQuiz(md: string): QuizQ[] {
}
return out;
}
// xuchao: 应用题 answer 模式的提交载荷(最终答案 + 照片 key,供秒判与错题本快照)
export type SolveAnswerPayload = { answer: string; ossKey: string };
+6
View File
@@ -0,0 +1,6 @@
import "@testing-library/jest-dom/vitest";
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
// xuchao: 组件测试后自动清理 DOM,避免跨测试污染
afterEach(() => cleanup());
+13
View File
@@ -0,0 +1,13 @@
import path from "node:path";
import { defineConfig } from "vitest/config";
// xuchao: Vitest 配置——@ 别名对齐 tsconfig;组件测试文件用 // @vitest-environment jsdom 标注
export default defineConfig({
resolve: { alias: { "@": path.resolve(__dirname, "src") } },
oxc: { jsx: { runtime: "automatic" } },
test: {
environment: "node",
include: ["src/**/*.test.{ts,tsx}"],
setupFiles: ["src/test-setup.ts"],
},
});