refactor: RBAC权限系统重构 + UI组件拆分 + 测试修复 + 架构文档
Some checks failed
CI / build-deploy (push) Has been cancelled
Some checks failed
CI / build-deploy (push) Has been cancelled
- RBAC: 新增30个权限点、DataScope行级权限、requirePermission守卫,所有57+ Server Action接入权限校验 - UI拆分: exam-form(1623行→11文件)、textbook-reader(744行→7文件),均降至300行以内 - 测试: 新增5个单元测试文件(19用例),修复4个集成测试文件(38用例全部通过) - 架构文档: 新增架构影响地图(004/005)、标准功能清单(006)、差距审计报告(007) - 项目规则: 架构图优先规则,改码必同步图 - 安全: rehype-sanitize净化、AES加密API Key、权限路由守卫 - 无障碍: skip-link、aria-label、prefers-reduced-motion - 性能: next/font优化、next/image、代码分割
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { ActionState } from "@/shared/types/action-state"
|
||||
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import { z } from "zod"
|
||||
import { createId } from "@paralleldrive/cuid2"
|
||||
import { db } from "@/shared/db"
|
||||
@@ -253,53 +255,61 @@ export async function createExamAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const rawQuestions = formData.get("questionsJson") as string | null
|
||||
|
||||
const parsed = ExamCreateSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
scheduledAt: getStringValue(formData, "scheduledAt") ?? null,
|
||||
questions: rawQuestions ? JSON.parse(rawQuestions) : [],
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, { useFirstMessage: false })
|
||||
}
|
||||
|
||||
const input = parsed.data
|
||||
const context = await prepareExamCreateContext({
|
||||
subject: input.subject,
|
||||
grade: input.grade,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
scheduledAt: input.scheduledAt,
|
||||
})
|
||||
const description = context.buildDescription()
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
await persistExamDraft({
|
||||
examId: context.examId,
|
||||
title: input.title,
|
||||
creatorId: user?.id ?? "user_teacher_math",
|
||||
subjectId: input.subject,
|
||||
gradeId: input.grade,
|
||||
scheduledAt: context.scheduled,
|
||||
description,
|
||||
const ctx = await requirePermission(Permissions.EXAM_CREATE)
|
||||
|
||||
const rawQuestions = formData.get("questionsJson") as string | null
|
||||
|
||||
const parsed = ExamCreateSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
scheduledAt: getStringValue(formData, "scheduledAt") ?? null,
|
||||
questions: rawQuestions ? JSON.parse(rawQuestions) : [],
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, { useFirstMessage: false })
|
||||
}
|
||||
|
||||
const input = parsed.data
|
||||
const context = await prepareExamCreateContext({
|
||||
subject: input.subject,
|
||||
grade: input.grade,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
scheduledAt: input.scheduledAt,
|
||||
})
|
||||
const description = context.buildDescription()
|
||||
|
||||
try {
|
||||
await persistExamDraft({
|
||||
examId: context.examId,
|
||||
title: input.title,
|
||||
creatorId: ctx.userId,
|
||||
subjectId: input.subject,
|
||||
gradeId: input.grade,
|
||||
scheduledAt: context.scheduled,
|
||||
description,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to create exam:", error)
|
||||
return failState<string>("Database error: Failed to create exam")
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(context.examId, "Exam created successfully.")
|
||||
} catch (error) {
|
||||
console.error("Failed to create exam:", error)
|
||||
return failState<string>("Database error: Failed to create exam")
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<string>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(context.examId, "Exam created successfully.")
|
||||
}
|
||||
|
||||
const AiExamCreateSchema = ExamCreateSchema.extend({
|
||||
@@ -324,167 +334,193 @@ export async function createAiExamAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const rawQuestions = formData.get("questionsJson") as string | null
|
||||
const rawAiQuestions = formData.get("aiQuestionsJson") as string | null
|
||||
const rawStructure = formData.get("structureJson") as string | null
|
||||
const aiSourceTextRaw = formData.get("aiSourceText")
|
||||
const aiQuestionCountRaw = formData.get("aiQuestionCount")
|
||||
const aiProviderIdRaw = formData.get("aiProviderId")
|
||||
|
||||
const parsed = AiExamCreateSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
scheduledAt: getStringValue(formData, "scheduledAt") ?? null,
|
||||
questions: rawQuestions ? JSON.parse(rawQuestions) : [],
|
||||
aiSourceText: typeof aiSourceTextRaw === "string" ? aiSourceTextRaw.trim() : undefined,
|
||||
aiQuestionCount: typeof aiQuestionCountRaw === "string" && aiQuestionCountRaw.trim().length > 0
|
||||
? aiQuestionCountRaw
|
||||
: undefined,
|
||||
aiProviderId: typeof aiProviderIdRaw === "string" && aiProviderIdRaw.trim().length > 0
|
||||
? aiProviderIdRaw
|
||||
: undefined,
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error)
|
||||
}
|
||||
|
||||
const input = parsed.data
|
||||
if (!rawAiQuestions && !input.aiSourceText) {
|
||||
return failState<string>("Please analyze and preview before creating")
|
||||
}
|
||||
const context = await prepareExamCreateContext({
|
||||
subject: input.subject,
|
||||
grade: input.grade,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
scheduledAt: input.scheduledAt,
|
||||
})
|
||||
|
||||
const user = await getCurrentUser()
|
||||
const aiDraftResult = await loadAiDraftQuestionsAndStructure({
|
||||
rawAiQuestions,
|
||||
rawStructure,
|
||||
title: input.title,
|
||||
subject: context.subjectName,
|
||||
grade: context.gradeName,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
aiSourceText: input.aiSourceText,
|
||||
aiQuestionCount: input.aiQuestionCount,
|
||||
aiProviderId: input.aiProviderId,
|
||||
})
|
||||
if (!aiDraftResult.ok) {
|
||||
return failState<string>(aiDraftResult.message)
|
||||
}
|
||||
const { generated, structure } = aiDraftResult
|
||||
|
||||
const questionCount = generated.length
|
||||
const description = context.buildDescription({ questionCount })
|
||||
|
||||
try {
|
||||
await persistAiGeneratedExamDraft({
|
||||
examId: context.examId,
|
||||
title: input.title,
|
||||
creatorId: user?.id ?? "user_teacher_math",
|
||||
subjectId: input.subject,
|
||||
gradeId: input.grade,
|
||||
scheduledAt: context.scheduled,
|
||||
description,
|
||||
structure,
|
||||
generated,
|
||||
const ctx = await requirePermission(Permissions.EXAM_AI_GENERATE)
|
||||
|
||||
const rawQuestions = formData.get("questionsJson") as string | null
|
||||
const rawAiQuestions = formData.get("aiQuestionsJson") as string | null
|
||||
const rawStructure = formData.get("structureJson") as string | null
|
||||
const aiSourceTextRaw = formData.get("aiSourceText")
|
||||
const aiQuestionCountRaw = formData.get("aiQuestionCount")
|
||||
const aiProviderIdRaw = formData.get("aiProviderId")
|
||||
|
||||
const parsed = AiExamCreateSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
scheduledAt: getStringValue(formData, "scheduledAt") ?? null,
|
||||
questions: rawQuestions ? JSON.parse(rawQuestions) : [],
|
||||
aiSourceText: typeof aiSourceTextRaw === "string" ? aiSourceTextRaw.trim() : undefined,
|
||||
aiQuestionCount: typeof aiQuestionCountRaw === "string" && aiQuestionCountRaw.trim().length > 0
|
||||
? aiQuestionCountRaw
|
||||
: undefined,
|
||||
aiProviderId: typeof aiProviderIdRaw === "string" && aiProviderIdRaw.trim().length > 0
|
||||
? aiProviderIdRaw
|
||||
: undefined,
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error)
|
||||
}
|
||||
|
||||
const input = parsed.data
|
||||
if (!rawAiQuestions && !input.aiSourceText) {
|
||||
return failState<string>("Please analyze and preview before creating")
|
||||
}
|
||||
const context = await prepareExamCreateContext({
|
||||
subject: input.subject,
|
||||
grade: input.grade,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
scheduledAt: input.scheduledAt,
|
||||
})
|
||||
|
||||
const aiDraftResult = await loadAiDraftQuestionsAndStructure({
|
||||
rawAiQuestions,
|
||||
rawStructure,
|
||||
title: input.title,
|
||||
subject: context.subjectName,
|
||||
grade: context.gradeName,
|
||||
difficulty: input.difficulty,
|
||||
totalScore: input.totalScore,
|
||||
durationMin: input.durationMin,
|
||||
aiSourceText: input.aiSourceText,
|
||||
aiQuestionCount: input.aiQuestionCount,
|
||||
aiProviderId: input.aiProviderId,
|
||||
})
|
||||
if (!aiDraftResult.ok) {
|
||||
return failState<string>(aiDraftResult.message)
|
||||
}
|
||||
const { generated, structure } = aiDraftResult
|
||||
|
||||
const questionCount = generated.length
|
||||
const description = context.buildDescription({ questionCount })
|
||||
|
||||
try {
|
||||
await persistAiGeneratedExamDraft({
|
||||
examId: context.examId,
|
||||
title: input.title,
|
||||
creatorId: ctx.userId,
|
||||
subjectId: input.subject,
|
||||
gradeId: input.grade,
|
||||
scheduledAt: context.scheduled,
|
||||
description,
|
||||
structure,
|
||||
generated,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to create exam:", error)
|
||||
return failState<string>("Database error: Failed to create exam")
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(context.examId, "Exam created successfully.")
|
||||
} catch (error) {
|
||||
console.error("Failed to create exam:", error)
|
||||
return failState<string>("Database error: Failed to create exam")
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<string>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(context.examId, "Exam created successfully.")
|
||||
}
|
||||
|
||||
export async function previewAiExamAction(
|
||||
prevState: ActionState<AiPreviewData> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<AiPreviewData>> {
|
||||
const aiSourceTextRaw = formData.get("aiSourceText")
|
||||
const aiQuestionCountRaw = formData.get("aiQuestionCount")
|
||||
const aiProviderIdRaw = formData.get("aiProviderId")
|
||||
try {
|
||||
await requirePermission(Permissions.EXAM_AI_GENERATE)
|
||||
|
||||
const sourceText = typeof aiSourceTextRaw === "string" ? aiSourceTextRaw.trim() : ""
|
||||
if (!sourceText) {
|
||||
return failState<AiPreviewData>("Please paste the full exam text first", {
|
||||
aiSourceText: ["Please paste the full exam text first"],
|
||||
const aiSourceTextRaw = formData.get("aiSourceText")
|
||||
const aiQuestionCountRaw = formData.get("aiQuestionCount")
|
||||
const aiProviderIdRaw = formData.get("aiProviderId")
|
||||
|
||||
const sourceText = typeof aiSourceTextRaw === "string" ? aiSourceTextRaw.trim() : ""
|
||||
if (!sourceText) {
|
||||
return failState<AiPreviewData>("Please paste the full exam text first", {
|
||||
aiSourceText: ["Please paste the full exam text first"],
|
||||
})
|
||||
}
|
||||
|
||||
const parsed = AiExamPreviewSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
aiSourceText: sourceText,
|
||||
aiQuestionCount: typeof aiQuestionCountRaw === "string" && aiQuestionCountRaw.trim().length > 0
|
||||
? aiQuestionCountRaw
|
||||
: undefined,
|
||||
aiProviderId: typeof aiProviderIdRaw === "string" && aiProviderIdRaw.trim().length > 0
|
||||
? aiProviderIdRaw
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const parsed = AiExamPreviewSchema.safeParse({
|
||||
title: getStringValue(formData, "title"),
|
||||
subject: getStringValue(formData, "subject"),
|
||||
grade: getStringValue(formData, "grade"),
|
||||
difficulty: getStringValue(formData, "difficulty"),
|
||||
totalScore: getStringValue(formData, "totalScore"),
|
||||
durationMin: getStringValue(formData, "durationMin"),
|
||||
aiSourceText: sourceText,
|
||||
aiQuestionCount: typeof aiQuestionCountRaw === "string" && aiQuestionCountRaw.trim().length > 0
|
||||
? aiQuestionCountRaw
|
||||
: undefined,
|
||||
aiProviderId: typeof aiProviderIdRaw === "string" && aiProviderIdRaw.trim().length > 0
|
||||
? aiProviderIdRaw
|
||||
: undefined,
|
||||
})
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<AiPreviewData>(parsed.error)
|
||||
}
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<AiPreviewData>(parsed.error)
|
||||
const input = parsed.data
|
||||
const previewRequest = await prepareAiPreviewRequest(input)
|
||||
const aiDraft = await generateAiPreviewData(previewRequest)
|
||||
if (!aiDraft.ok) {
|
||||
return failState<AiPreviewData>(aiDraft.message)
|
||||
}
|
||||
return successState({ ...aiDraft.data, rawOutput: aiDraft.rawOutput })
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<AiPreviewData>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
const input = parsed.data
|
||||
const previewRequest = await prepareAiPreviewRequest(input)
|
||||
const aiDraft = await generateAiPreviewData(previewRequest)
|
||||
if (!aiDraft.ok) {
|
||||
return failState<AiPreviewData>(aiDraft.message)
|
||||
}
|
||||
return successState({ ...aiDraft.data, rawOutput: aiDraft.rawOutput })
|
||||
}
|
||||
|
||||
export async function regenerateAiQuestionAction(
|
||||
prevState: ActionState<AiRewriteQuestionData> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<AiRewriteQuestionData>> {
|
||||
const parsedInput = parseRegenerateAiQuestionInput(formData)
|
||||
if (!parsedInput.ok) {
|
||||
return parsedInput.state
|
||||
}
|
||||
const { instruction, aiProviderId, sourceText, originalQuestion } = parsedInput
|
||||
|
||||
const originalDifficulty = originalQuestion.difficulty ?? 3
|
||||
const originalScore = originalQuestion.score ?? 0
|
||||
|
||||
try {
|
||||
const result = await regenerateAiQuestionByInstruction({
|
||||
instruction,
|
||||
originalQuestion,
|
||||
sourceText,
|
||||
aiProviderId,
|
||||
})
|
||||
if (!result.ok) {
|
||||
return failState<AiRewriteQuestionData>(result.message)
|
||||
await requirePermission(Permissions.EXAM_AI_GENERATE)
|
||||
|
||||
const parsedInput = parseRegenerateAiQuestionInput(formData)
|
||||
if (!parsedInput.ok) {
|
||||
return parsedInput.state
|
||||
}
|
||||
return successState({
|
||||
type: result.data.type,
|
||||
difficulty: result.data.difficulty ?? originalDifficulty,
|
||||
score: result.data.score ?? originalScore,
|
||||
content: result.data.content,
|
||||
})
|
||||
} catch {
|
||||
return failState<AiRewriteQuestionData>("AI question format invalid")
|
||||
const { instruction, aiProviderId, sourceText, originalQuestion } = parsedInput
|
||||
|
||||
const originalDifficulty = originalQuestion.difficulty ?? 3
|
||||
const originalScore = originalQuestion.score ?? 0
|
||||
|
||||
try {
|
||||
const result = await regenerateAiQuestionByInstruction({
|
||||
instruction,
|
||||
originalQuestion,
|
||||
sourceText,
|
||||
aiProviderId,
|
||||
})
|
||||
if (!result.ok) {
|
||||
return failState<AiRewriteQuestionData>(result.message)
|
||||
}
|
||||
return successState({
|
||||
type: result.data.type,
|
||||
difficulty: result.data.difficulty ?? originalDifficulty,
|
||||
score: result.data.score ?? originalScore,
|
||||
content: result.data.content,
|
||||
})
|
||||
} catch {
|
||||
return failState<AiRewriteQuestionData>("AI question format invalid")
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<AiRewriteQuestionData>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,58 +542,78 @@ export async function updateExamAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const rawQuestions = formData.get("questionsJson")
|
||||
const rawStructure = formData.get("structureJson")
|
||||
const hasQuestions = typeof rawQuestions === "string"
|
||||
const hasStructure = typeof rawStructure === "string"
|
||||
|
||||
const parsed = ExamUpdateSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
questions: hasQuestions ? JSON.parse(rawQuestions) : undefined,
|
||||
structure: hasStructure ? JSON.parse(rawStructure) : undefined,
|
||||
status: formData.get("status") ?? undefined,
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid update data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId, questions, structure, status } = parsed.data
|
||||
|
||||
try {
|
||||
if (questions) {
|
||||
await db.delete(examQuestions).where(eq(examQuestions.examId, examId))
|
||||
if (questions.length > 0) {
|
||||
await db.insert(examQuestions).values(
|
||||
questions.map((q, idx) => ({
|
||||
examId,
|
||||
questionId: q.id,
|
||||
score: q.score ?? 0,
|
||||
order: idx,
|
||||
}))
|
||||
)
|
||||
const ctx = await requirePermission(Permissions.EXAM_UPDATE)
|
||||
|
||||
const rawQuestions = formData.get("questionsJson")
|
||||
const rawStructure = formData.get("structureJson")
|
||||
const hasQuestions = typeof rawQuestions === "string"
|
||||
const hasStructure = typeof rawStructure === "string"
|
||||
|
||||
const parsed = ExamUpdateSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
questions: hasQuestions ? JSON.parse(rawQuestions) : undefined,
|
||||
structure: hasStructure ? JSON.parse(rawStructure) : undefined,
|
||||
status: formData.get("status") ?? undefined,
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid update data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId, questions, structure, status } = parsed.data
|
||||
|
||||
// Ownership check: non-admin users can only update their own exams
|
||||
if (ctx.dataScope.type !== "all") {
|
||||
const exam = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
columns: { creatorId: true },
|
||||
})
|
||||
if (!exam || exam.creatorId !== ctx.userId) {
|
||||
return failState<string>("You can only update exams you created")
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare update object
|
||||
const updateData: Partial<typeof exams.$inferInsert> = {}
|
||||
if (status) updateData.status = status
|
||||
if (structure !== undefined) updateData.structure = structure
|
||||
|
||||
if (Object.keys(updateData).length > 0) {
|
||||
await db.update(exams).set(updateData).where(eq(exams.id, examId))
|
||||
|
||||
try {
|
||||
if (questions) {
|
||||
await db.delete(examQuestions).where(eq(examQuestions.examId, examId))
|
||||
if (questions.length > 0) {
|
||||
await db.insert(examQuestions).values(
|
||||
questions.map((q, idx) => ({
|
||||
examId,
|
||||
questionId: q.id,
|
||||
score: q.score ?? 0,
|
||||
order: idx,
|
||||
}))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare update object
|
||||
const updateData: Partial<typeof exams.$inferInsert> = {}
|
||||
if (status) updateData.status = status
|
||||
if (structure !== undefined) updateData.structure = structure
|
||||
|
||||
if (Object.keys(updateData).length > 0) {
|
||||
await db.update(exams).set(updateData).where(eq(exams.id, examId))
|
||||
}
|
||||
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to update exam")
|
||||
}
|
||||
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to update exam")
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(examId, "Exam updated")
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<string>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(examId, "Exam updated")
|
||||
}
|
||||
|
||||
const ExamDeleteSchema = z.object({
|
||||
@@ -568,28 +624,48 @@ export async function deleteExamAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const parsed = ExamDeleteSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid delete data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId } = parsed.data
|
||||
|
||||
try {
|
||||
await db.delete(exams).where(eq(exams.id, examId))
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to delete exam")
|
||||
const ctx = await requirePermission(Permissions.EXAM_DELETE)
|
||||
|
||||
const parsed = ExamDeleteSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid delete data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId } = parsed.data
|
||||
|
||||
// Ownership check: non-admin users can only delete their own exams
|
||||
if (ctx.dataScope.type !== "all") {
|
||||
const exam = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
columns: { creatorId: true },
|
||||
})
|
||||
if (!exam || exam.creatorId !== ctx.userId) {
|
||||
return failState<string>("You can only delete exams you created")
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await db.delete(exams).where(eq(exams.id, examId))
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to delete exam")
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(examId, "Exam deleted")
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<string>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(examId, "Exam deleted")
|
||||
}
|
||||
|
||||
const ExamDuplicateSchema = z.object({
|
||||
@@ -600,124 +676,157 @@ export async function duplicateExamAction(
|
||||
prevState: ActionState<string> | null,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
const parsed = ExamDuplicateSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid duplicate data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId } = parsed.data
|
||||
|
||||
const source = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
with: {
|
||||
questions: {
|
||||
orderBy: (examQuestions, { asc }) => [asc(examQuestions.order)],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!source) {
|
||||
return failState<string>("Exam not found")
|
||||
}
|
||||
|
||||
const newExamId = createId()
|
||||
const user = await getCurrentUser()
|
||||
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(exams).values({
|
||||
id: newExamId,
|
||||
title: `${source.title} (Copy)`,
|
||||
description: omitScheduledAtFromDescription(source.description),
|
||||
creatorId: user?.id ?? "user_teacher_math",
|
||||
startTime: null,
|
||||
endTime: null,
|
||||
status: "draft",
|
||||
structure: source.structure,
|
||||
})
|
||||
const ctx = await requirePermission(Permissions.EXAM_DUPLICATE)
|
||||
|
||||
if (source.questions.length > 0) {
|
||||
await tx.insert(examQuestions).values(
|
||||
source.questions.map((q) => ({
|
||||
examId: newExamId,
|
||||
questionId: q.questionId,
|
||||
score: q.score ?? 0,
|
||||
order: q.order ?? 0,
|
||||
}))
|
||||
)
|
||||
}
|
||||
const parsed = ExamDuplicateSchema.safeParse({
|
||||
examId: formData.get("examId"),
|
||||
})
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to duplicate exam")
|
||||
|
||||
if (!parsed.success) {
|
||||
return invalidFormState<string>(parsed.error, {
|
||||
fallbackMessage: "Invalid duplicate data",
|
||||
useFirstMessage: false,
|
||||
})
|
||||
}
|
||||
|
||||
const { examId } = parsed.data
|
||||
|
||||
const source = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
with: {
|
||||
questions: {
|
||||
orderBy: (examQuestions, { asc }) => [asc(examQuestions.order)],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!source) {
|
||||
return failState<string>("Exam not found")
|
||||
}
|
||||
|
||||
const newExamId = createId()
|
||||
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(exams).values({
|
||||
id: newExamId,
|
||||
title: `${source.title} (Copy)`,
|
||||
description: omitScheduledAtFromDescription(source.description),
|
||||
creatorId: ctx.userId,
|
||||
startTime: null,
|
||||
endTime: null,
|
||||
status: "draft",
|
||||
structure: source.structure,
|
||||
})
|
||||
|
||||
if (source.questions.length > 0) {
|
||||
await tx.insert(examQuestions).values(
|
||||
source.questions.map((q) => ({
|
||||
examId: newExamId,
|
||||
questionId: q.questionId,
|
||||
score: q.score ?? 0,
|
||||
order: q.order ?? 0,
|
||||
}))
|
||||
)
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
return failState<string>("Database error: Failed to duplicate exam")
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(newExamId, "Exam duplicated")
|
||||
} catch (error) {
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<string>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
revalidatePath("/teacher/exams/all")
|
||||
|
||||
return successState(newExamId, "Exam duplicated")
|
||||
}
|
||||
|
||||
export async function getExamPreviewAction(
|
||||
examId: string
|
||||
): Promise<ActionState<{ structure: unknown; questions: Array<{ id: string }> }>> {
|
||||
try {
|
||||
const exam = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
with: {
|
||||
questions: {
|
||||
orderBy: (examQuestions, { asc }) => [asc(examQuestions.order)],
|
||||
with: {
|
||||
question: true
|
||||
await requirePermission(Permissions.EXAM_READ)
|
||||
|
||||
try {
|
||||
const exam = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, examId),
|
||||
with: {
|
||||
questions: {
|
||||
orderBy: (examQuestions, { asc }) => [asc(examQuestions.order)],
|
||||
with: {
|
||||
question: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
if (!exam) {
|
||||
return failState<{ structure: unknown; questions: Array<{ id: string }> }>("Exam not found")
|
||||
if (!exam) {
|
||||
return failState<{ structure: unknown; questions: Array<{ id: string }> }>("Exam not found")
|
||||
}
|
||||
const questions = exam.questions.map((eq) => eq.question)
|
||||
return successState({
|
||||
structure: exam.structure,
|
||||
questions,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return failState<{ structure: unknown; questions: Array<{ id: string }> }>("Failed to load exam preview")
|
||||
}
|
||||
const questions = exam.questions.map((eq) => eq.question)
|
||||
return successState({
|
||||
structure: exam.structure,
|
||||
questions,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return failState<{ structure: unknown; questions: Array<{ id: string }> }>("Failed to load exam preview")
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<{ structure: unknown; questions: Array<{ id: string }> }>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSubjectsAction(): Promise<ActionState<{ id: string; name: string }[]>> {
|
||||
try {
|
||||
const allSubjects = await db.query.subjects.findMany({
|
||||
orderBy: (subjects, { asc }) => [asc(subjects.order), asc(subjects.name)],
|
||||
})
|
||||
await requirePermission(Permissions.EXAM_READ)
|
||||
|
||||
return successState(allSubjects.map((s) => ({ id: s.id, name: s.name })))
|
||||
try {
|
||||
const allSubjects = await db.query.subjects.findMany({
|
||||
orderBy: (subjects, { asc }) => [asc(subjects.order), asc(subjects.name)],
|
||||
})
|
||||
|
||||
return successState(allSubjects.map((s) => ({ id: s.id, name: s.name })))
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch subjects:", error)
|
||||
return failState<{ id: string; name: string }[]>("Failed to load subjects")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch subjects:", error)
|
||||
return failState<{ id: string; name: string }[]>("Failed to load subjects")
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<{ id: string; name: string }[]>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGradesAction(): Promise<ActionState<{ id: string; name: string }[]>> {
|
||||
try {
|
||||
const allGrades = await db.query.grades.findMany({
|
||||
orderBy: (grades, { asc }) => [asc(grades.order), asc(grades.name)],
|
||||
})
|
||||
await requirePermission(Permissions.EXAM_READ)
|
||||
|
||||
return successState(allGrades.map((g) => ({ id: g.id, name: g.name })))
|
||||
try {
|
||||
const allGrades = await db.query.grades.findMany({
|
||||
orderBy: (grades, { asc }) => [asc(grades.order), asc(grades.name)],
|
||||
})
|
||||
|
||||
return successState(allGrades.map((g) => ({ id: g.id, name: g.name })))
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch grades:", error)
|
||||
return failState<{ id: string; name: string }[]>("Failed to load grades")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch grades:", error)
|
||||
return failState<{ id: string; name: string }[]>("Failed to load grades")
|
||||
if (error instanceof PermissionDeniedError) {
|
||||
return failState<{ id: string; name: string }[]>(error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function getCurrentUser() {
|
||||
return { id: "user_teacher_math", role: "teacher" }
|
||||
}
|
||||
|
||||
|
||||
@@ -155,21 +155,22 @@ export function ExamActions({ exam }: ExamActionsProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleView()
|
||||
}}
|
||||
title="Preview Exam"
|
||||
aria-label="Preview exam"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<Button variant="ghost" className="h-8 w-8 p-0" aria-label="Open menu">
|
||||
<span className="sr-only">Open menu</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
223
src/modules/exams/components/exam-ai-generator.tsx
Normal file
223
src/modules/exams/components/exam-ai-generator.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
"use client"
|
||||
|
||||
import type { Control, UseFormReturn } from "react-hook-form"
|
||||
import { Settings } from "lucide-react"
|
||||
import {
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormMessage,
|
||||
FormDescription,
|
||||
} from "@/shared/components/ui/form"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { AiProviderSettingsCard } from "@/modules/settings/components/ai-provider-settings-card"
|
||||
import type { AiProviderSummary } from "@/modules/settings/actions"
|
||||
import type { ExamFormValues, PreviewBackgroundTask } from "./exam-form-types"
|
||||
import { aiProviderLabels } from "./exam-form-types"
|
||||
|
||||
type ExamAiGeneratorProps = {
|
||||
form: UseFormReturn<ExamFormValues>
|
||||
control: Control<ExamFormValues>
|
||||
aiProviders: AiProviderSummary[]
|
||||
setAiProviders: (providers: AiProviderSummary[]) => void
|
||||
loadingAiProviders: boolean
|
||||
providerDialogOpen: boolean
|
||||
setProviderDialogOpen: (open: boolean) => void
|
||||
providerDialogKey: number
|
||||
setProviderDialogKey: (key: number | ((prev: number) => number)) => void
|
||||
handlePreview: () => void
|
||||
handleBackgroundPreview: () => void
|
||||
previewLoading: boolean
|
||||
previewTasks: PreviewBackgroundTask[]
|
||||
handleOpenPreviewTask: (taskId: string) => void
|
||||
activePreviewTaskCount: number
|
||||
runningPreviewTaskCount: number
|
||||
queuedPreviewTaskCount: number
|
||||
}
|
||||
|
||||
export function ExamAiGenerator({
|
||||
form,
|
||||
control,
|
||||
aiProviders,
|
||||
setAiProviders,
|
||||
loadingAiProviders,
|
||||
providerDialogOpen,
|
||||
setProviderDialogOpen,
|
||||
providerDialogKey,
|
||||
setProviderDialogKey,
|
||||
handlePreview,
|
||||
handleBackgroundPreview,
|
||||
previewLoading,
|
||||
previewTasks,
|
||||
handleOpenPreviewTask,
|
||||
activePreviewTaskCount,
|
||||
runningPreviewTaskCount,
|
||||
queuedPreviewTaskCount,
|
||||
}: ExamAiGeneratorProps) {
|
||||
const formatTaskTime = (value: number) => new Date(value).toLocaleString("zh-CN", {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>AI Generation</CardTitle>
|
||||
<CardDescription>
|
||||
Paste the exam text and generate a structured preview.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<FormField
|
||||
control={control}
|
||||
name="aiProviderId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<FormLabel>AI Provider</FormLabel>
|
||||
<Dialog
|
||||
open={providerDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setProviderDialogOpen(open)
|
||||
if (open) {
|
||||
setProviderDialogKey((value) => value + 1)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-muted-foreground hover:text-foreground">
|
||||
<Settings className="mr-1 h-3.5 w-3.5" />
|
||||
新建配置
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[960px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>AI Provider Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new provider or update existing configuration.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<AiProviderSettingsCard
|
||||
key={providerDialogKey}
|
||||
initialMode="new"
|
||||
onProvidersChanged={(rows) => {
|
||||
setAiProviders(rows)
|
||||
const preferred = rows.find((item) => item.isDefault) ?? rows[0]
|
||||
if (preferred) {
|
||||
form.setValue("aiProviderId", preferred.id)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
<Select value={field.value} onValueChange={field.onChange} disabled={loadingAiProviders}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={loadingAiProviders ? "Loading providers..." : "Select provider"} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{aiProviders.map((item) => (
|
||||
<SelectItem key={item.id} value={item.id}>
|
||||
{aiProviderLabels[item.provider] ?? item.provider} · {item.model}{item.isDefault ? " (Default)" : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
Select the AI configuration for this generation.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleBackgroundPreview}>
|
||||
{`加入后台队列(运行 ${runningPreviewTaskCount}/3,排队 ${queuedPreviewTaskCount})`}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handlePreview} disabled={previewLoading || activePreviewTaskCount > 0}>
|
||||
{previewLoading ? "Generating..." : "立即预览"}
|
||||
</Button>
|
||||
</div>
|
||||
<FormField
|
||||
control={control}
|
||||
name="aiSourceText"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Source Exam Text</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Paste the full exam text to parse into questions."
|
||||
className="min-h-[200px]"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
AI will extract questions and structure from this text.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{previewTasks.length > 0 ? (
|
||||
<div className="rounded-md border p-3 space-y-2">
|
||||
<div className="text-sm font-medium">后台生成记录</div>
|
||||
<div className="space-y-2">
|
||||
{previewTasks.slice(0, 6).map((task) => (
|
||||
<div key={task.id} className="rounded-md border p-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="text-sm font-medium truncate">{task.title}</div>
|
||||
<div className="text-xs text-muted-foreground">{formatTaskTime(task.createdAt)}</div>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{task.status === "queued"
|
||||
? "排队中"
|
||||
: task.status === "running"
|
||||
? "生成中"
|
||||
: task.status === "success"
|
||||
? "已完成"
|
||||
: `失败:${task.message || "生成失败"}`}
|
||||
</div>
|
||||
{task.status === "success" && task.result ? (
|
||||
<div className="mt-2 flex justify-end">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => handleOpenPreviewTask(task.id)}>
|
||||
打开预览
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
190
src/modules/exams/components/exam-basic-info-form.tsx
Normal file
190
src/modules/exams/components/exam-basic-info-form.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client"
|
||||
|
||||
import type { Control } from "react-hook-form"
|
||||
import {
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormMessage,
|
||||
FormDescription,
|
||||
} from "@/shared/components/ui/form"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import type { ExamFormValues } from "./exam-form-types"
|
||||
|
||||
type ExamBasicInfoFormProps = {
|
||||
control: Control<ExamFormValues>
|
||||
subjects: { id: string; name: string }[]
|
||||
grades: { id: string; name: string }[]
|
||||
loadingSubjects: boolean
|
||||
loadingGrades: boolean
|
||||
}
|
||||
|
||||
export function ExamBasicInfoForm({
|
||||
control,
|
||||
subjects,
|
||||
grades,
|
||||
loadingSubjects,
|
||||
loadingGrades,
|
||||
}: ExamBasicInfoFormProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Exam Details</CardTitle>
|
||||
<CardDescription>
|
||||
Define the core information for your exam.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-6">
|
||||
<FormField
|
||||
control={control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Title</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="e.g. Midterm Mathematics Exam" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
control={control}
|
||||
name="subject"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Subject</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value} disabled={loadingSubjects}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={loadingSubjects ? "Loading subjects..." : "Select subject"} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{subjects.map((subject) => (
|
||||
<SelectItem key={subject.id} value={subject.id}>
|
||||
{subject.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name="grade"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Grade Level</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value} disabled={loadingGrades}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={loadingGrades ? "Loading grades..." : "Select grade level"} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{grades.map((grade) => (
|
||||
<SelectItem key={grade.id} value={grade.id}>
|
||||
{grade.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<FormField
|
||||
control={control}
|
||||
name="difficulty"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Difficulty</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select level" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">Level 1 (Easy)</SelectItem>
|
||||
<SelectItem value="2">Level 2</SelectItem>
|
||||
<SelectItem value="3">Level 3 (Medium)</SelectItem>
|
||||
<SelectItem value="4">Level 4</SelectItem>
|
||||
<SelectItem value="5">Level 5 (Hard)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name="totalScore"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Total Score</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name="durationMin"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Duration (min)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="scheduledAt"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Schedule Start Time (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="datetime-local" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If set, this exam will be scheduled for a specific time.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
46
src/modules/exams/components/exam-form-types.test.ts
Normal file
46
src/modules/exams/components/exam-form-types.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { formSchema } from "./exam-form-types"
|
||||
|
||||
describe("formSchema", () => {
|
||||
it("should validate manual mode with required fields", () => {
|
||||
const result = formSchema.safeParse({
|
||||
mode: "manual",
|
||||
title: "Test Exam",
|
||||
subject: "math",
|
||||
grade: "g1",
|
||||
difficulty: "3",
|
||||
totalScore: 100,
|
||||
durationMin: 90,
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it("should reject manual mode without title", () => {
|
||||
const result = formSchema.safeParse({
|
||||
mode: "manual",
|
||||
title: "",
|
||||
subject: "math",
|
||||
grade: "g1",
|
||||
difficulty: "3",
|
||||
totalScore: 100,
|
||||
durationMin: 90,
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it("should validate AI mode with source text", () => {
|
||||
const result = formSchema.safeParse({
|
||||
mode: "ai",
|
||||
aiSourceText: "Some exam text content here",
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it("should reject AI mode without source text", () => {
|
||||
const result = formSchema.safeParse({
|
||||
mode: "ai",
|
||||
aiSourceText: "",
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
})
|
||||
133
src/modules/exams/components/exam-form-types.ts
Normal file
133
src/modules/exams/components/exam-form-types.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import * as z from "zod"
|
||||
import type { Question } from "@/modules/questions/types"
|
||||
import type { AiProviderSummary } from "@/modules/settings/actions"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
|
||||
export const formSchema = z.object({
|
||||
title: z.string().optional(),
|
||||
subject: z.string().optional(),
|
||||
grade: z.string().optional(),
|
||||
difficulty: z.string().optional(),
|
||||
totalScore: z.coerce.number().min(1, "Total score must be at least 1.").optional(),
|
||||
durationMin: z.coerce.number().min(10, "Duration must be at least 10 minutes.").optional(),
|
||||
scheduledAt: z.string().optional(),
|
||||
mode: z.enum(["manual", "ai"]),
|
||||
aiSourceText: z.string().optional(),
|
||||
aiQuestionCount: z.coerce.number().min(1).max(200).optional(),
|
||||
aiProviderId: z.string().optional(),
|
||||
}).superRefine((data, ctx) => {
|
||||
if (data.mode === "ai") {
|
||||
if (!data.aiSourceText?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["aiSourceText"],
|
||||
message: "Source exam text is required for AI generation.",
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!data.title?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["title"],
|
||||
message: "Title must be at least 2 characters.",
|
||||
})
|
||||
}
|
||||
if (!data.subject?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["subject"],
|
||||
message: "Subject is required.",
|
||||
})
|
||||
}
|
||||
if (!data.grade?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["grade"],
|
||||
message: "Grade is required.",
|
||||
})
|
||||
}
|
||||
if (!data.difficulty?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["difficulty"],
|
||||
message: "Difficulty is required.",
|
||||
})
|
||||
}
|
||||
if (typeof data.totalScore !== "number") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["totalScore"],
|
||||
message: "Total score must be at least 1.",
|
||||
})
|
||||
}
|
||||
if (typeof data.durationMin !== "number") {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["durationMin"],
|
||||
message: "Duration must be at least 10 minutes.",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type ExamFormValues = z.infer<typeof formSchema>
|
||||
|
||||
export type PreviewQuestion = {
|
||||
id: string
|
||||
type: Question["type"]
|
||||
difficulty: number
|
||||
score: number
|
||||
content: Question["content"]
|
||||
}
|
||||
|
||||
export type EditableQuestionContent = {
|
||||
text: string
|
||||
options: Array<{ id: string; text: string; isCorrect: boolean }>
|
||||
subQuestions: Array<{ id: string; text: string; answer?: string; score?: number }>
|
||||
}
|
||||
|
||||
export type PreviewSnapshotMeta = {
|
||||
subject: string
|
||||
grade: string
|
||||
durationMin: number
|
||||
totalScore: number
|
||||
}
|
||||
|
||||
export type PreviewBackgroundTask = {
|
||||
id: string
|
||||
createdAt: number
|
||||
status: "queued" | "running" | "success" | "failed"
|
||||
title: string
|
||||
signature: string
|
||||
message?: string
|
||||
result?: {
|
||||
title: string
|
||||
nodes: ExamNode[]
|
||||
rawOutput: string
|
||||
meta: PreviewSnapshotMeta
|
||||
formValues: Pick<ExamFormValues, "title" | "subject" | "grade" | "difficulty" | "totalScore" | "durationMin" | "aiSourceText" | "aiQuestionCount" | "aiProviderId">
|
||||
}
|
||||
}
|
||||
|
||||
export const aiProviderLabels: Record<AiProviderSummary["provider"], string> = {
|
||||
zhipu: "智谱",
|
||||
openai: "OpenAI",
|
||||
gemini: "Gemini",
|
||||
custom: "Custom",
|
||||
}
|
||||
|
||||
export const defaultValues: Partial<ExamFormValues> = {
|
||||
title: "",
|
||||
subject: "",
|
||||
grade: "",
|
||||
difficulty: "3",
|
||||
totalScore: 100,
|
||||
durationMin: 90,
|
||||
mode: "manual",
|
||||
scheduledAt: "",
|
||||
aiSourceText: "",
|
||||
aiQuestionCount: undefined,
|
||||
aiProviderId: "",
|
||||
}
|
||||
|
||||
export const previewTaskStorageKey = "exam-preview-background-tasks:v1"
|
||||
File diff suppressed because it is too large
Load Diff
85
src/modules/exams/components/exam-mode-selector.tsx
Normal file
85
src/modules/exams/components/exam-mode-selector.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import { Loader2, Sparkles, BookOpen } from "lucide-react"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
|
||||
type ExamModeSelectorProps = {
|
||||
mode: "manual" | "ai"
|
||||
setMode: (mode: "manual" | "ai") => void
|
||||
isPending: boolean
|
||||
handleCreateClick: () => void
|
||||
}
|
||||
|
||||
export function ExamModeSelector({
|
||||
mode,
|
||||
setMode,
|
||||
isPending,
|
||||
handleCreateClick,
|
||||
}: ExamModeSelectorProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Assembly Mode</CardTitle>
|
||||
<CardDescription>
|
||||
Choose how to build the exam structure.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col space-y-3">
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"relative flex cursor-pointer flex-col rounded-lg border p-4 shadow-sm outline-none transition-all hover:bg-accent hover:text-accent-foreground text-left",
|
||||
mode === "manual" ? "border-primary ring-1 ring-primary" : "border-border"
|
||||
)}
|
||||
onClick={() => setMode("manual")}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<BookOpen className="h-4 w-4 text-primary" />
|
||||
<span className="font-medium">Manual Assembly</span>
|
||||
</div>
|
||||
<span className="mt-1 text-xs text-muted-foreground">
|
||||
Manually select questions from the bank and organize structure.
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"relative flex cursor-pointer flex-col rounded-lg border p-4 shadow-sm outline-none transition-all hover:bg-accent hover:text-accent-foreground text-left",
|
||||
mode === "ai" ? "border-primary ring-1 ring-primary" : "border-border"
|
||||
)}
|
||||
onClick={() => setMode("ai")}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="h-4 w-4 text-primary" />
|
||||
<span className="font-medium">AI Generation</span>
|
||||
</div>
|
||||
<span className="mt-1 text-xs text-muted-foreground">
|
||||
Automatically generate a draft exam based on your input.
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter>
|
||||
<Button type="button" className="w-full" disabled={isPending} onClick={handleCreateClick}>
|
||||
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isPending
|
||||
? "Creating Draft..."
|
||||
: mode === "ai"
|
||||
? "后台生成试卷"
|
||||
: "Create & Start Building"}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
185
src/modules/exams/components/exam-preview-dialog.tsx
Normal file
185
src/modules/exams/components/exam-preview-dialog.tsx
Normal file
@@ -0,0 +1,185 @@
|
||||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
import type { EditableQuestionContent, PreviewSnapshotMeta } from "./exam-form-types"
|
||||
import { ExamPreviewQuestionEditor } from "./exam-preview-question-editor"
|
||||
|
||||
type ExamPreviewDialogProps = {
|
||||
previewOpen: boolean
|
||||
setPreviewOpen: (open: boolean) => void
|
||||
previewLoading: boolean
|
||||
previewNodes: ExamNode[]
|
||||
previewTitle: string
|
||||
previewRawOutput: string
|
||||
previewMeta: PreviewSnapshotMeta | null
|
||||
selectedQuestionId: string
|
||||
setSelectedQuestionId: (id: string) => void
|
||||
rewriteInstruction: string
|
||||
setRewriteInstruction: (value: string) => void
|
||||
rewritingQuestion: boolean
|
||||
previewQuestionRows: Array<{ node: ExamNode; sectionTitle?: string }>
|
||||
selectedPreviewQuestion: ExamNode | null
|
||||
selectedPreviewContent: EditableQuestionContent | null
|
||||
activePreviewMeta: PreviewSnapshotMeta
|
||||
updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
|
||||
parseEditableContent: (raw: unknown) => EditableQuestionContent
|
||||
handleRewriteSelectedQuestion: () => void
|
||||
handleConfirmCreate: () => void
|
||||
previewTitleValue?: string
|
||||
}
|
||||
|
||||
export function ExamPreviewDialog({
|
||||
previewOpen,
|
||||
setPreviewOpen,
|
||||
previewLoading,
|
||||
previewNodes,
|
||||
previewTitle,
|
||||
previewRawOutput,
|
||||
selectedQuestionId,
|
||||
setSelectedQuestionId,
|
||||
rewriteInstruction,
|
||||
setRewriteInstruction,
|
||||
rewritingQuestion,
|
||||
previewQuestionRows,
|
||||
selectedPreviewQuestion,
|
||||
selectedPreviewContent,
|
||||
activePreviewMeta,
|
||||
updatePreviewQuestionNode,
|
||||
parseEditableContent,
|
||||
handleRewriteSelectedQuestion,
|
||||
handleConfirmCreate,
|
||||
previewTitleValue,
|
||||
}: ExamPreviewDialogProps) {
|
||||
const renderSelectablePreview = (nodes: ExamNode[]) => {
|
||||
let questionCounter = 0
|
||||
const renderNode = (node: ExamNode, depth: number = 0): ReactNode => {
|
||||
if (node.type === "group") {
|
||||
return (
|
||||
<div key={node.id} className="space-y-3 mb-6">
|
||||
<h3 className={cn("font-semibold text-foreground/90", depth === 0 ? "text-base" : "text-sm")}>
|
||||
{node.title || "Section"}
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{(node.children ?? []).map((child) => renderNode(child, depth + 1))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (node.type === "question" && node.question && node.questionId) {
|
||||
questionCounter += 1
|
||||
const content = parseEditableContent(node.question.content)
|
||||
const active = node.questionId === selectedQuestionId
|
||||
return (
|
||||
<button
|
||||
key={node.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedQuestionId(node.questionId ?? "")}
|
||||
className={cn(
|
||||
"w-full rounded-md border p-3 text-left transition-colors",
|
||||
active ? "border-primary bg-primary/5" : "border-border hover:bg-accent"
|
||||
)}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<span className="font-semibold text-foreground min-w-[28px]">{questionCounter}.</span>
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="text-foreground/90 leading-relaxed whitespace-pre-wrap">
|
||||
{content.text || "未命名题目"}
|
||||
<span className="text-muted-foreground text-xs ml-2">({node.score ?? 0}分)</span>
|
||||
</div>
|
||||
{content.options.length > 0 ? (
|
||||
<div className="space-y-1.5">
|
||||
{content.options.map((opt) => (
|
||||
<div key={`${node.id}-${opt.id}`} className="text-sm text-foreground/80 flex gap-2">
|
||||
<span className="min-w-[28px]">{opt.id}.</span>
|
||||
<span className="whitespace-pre-wrap">{opt.text}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{content.subQuestions.length > 0 ? (
|
||||
<div className="space-y-1.5 rounded-md bg-muted/40 p-2">
|
||||
{content.subQuestions.map((item, index) => (
|
||||
<div key={`${node.id}-sub-${index}`} className="text-sm text-foreground/80 flex gap-2">
|
||||
<span className="min-w-[28px]">{item.id}.</span>
|
||||
<span className="whitespace-pre-wrap">{item.text || "未命名子题"}</span>
|
||||
{item.score ? <span className="text-xs text-muted-foreground">({item.score}分)</span> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{nodes.map((node) => renderNode(node))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
|
||||
<DialogContent className="max-w-7xl h-[90vh] flex flex-col p-0 gap-0">
|
||||
<div className="p-4 border-b shrink-0 flex items-center justify-between">
|
||||
<DialogTitle className="text-lg font-semibold tracking-tight">
|
||||
{previewTitle || previewTitleValue || "Exam Preview"}
|
||||
</DialogTitle>
|
||||
</div>
|
||||
{previewLoading ? (
|
||||
<div className="flex-1 py-20 text-center text-muted-foreground">Generating preview...</div>
|
||||
) : previewNodes.length > 0 ? (
|
||||
<div className="flex-1 grid grid-cols-12 min-h-0">
|
||||
<div className="col-span-5 border-r min-h-0 flex flex-col">
|
||||
<div className="p-4 border-b">
|
||||
<div className="text-sm font-medium">完整试卷预览</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{previewQuestionRows.length} 题 · 科目 {activePreviewMeta.subject} · 年级 {activePreviewMeta.grade} · {activePreviewMeta.durationMin} 分钟 · 总分 {activePreviewMeta.totalScore}
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
{renderSelectablePreview(previewNodes)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="col-span-7 min-h-0 flex flex-col">
|
||||
<ExamPreviewQuestionEditor
|
||||
selectedQuestion={selectedPreviewQuestion}
|
||||
selectedContent={selectedPreviewContent}
|
||||
selectedQuestionId={selectedQuestionId}
|
||||
updatePreviewQuestionNode={updatePreviewQuestionNode}
|
||||
parseEditableContent={parseEditableContent}
|
||||
rewriteInstruction={rewriteInstruction}
|
||||
setRewriteInstruction={setRewriteInstruction}
|
||||
rewritingQuestion={rewritingQuestion}
|
||||
handleRewriteSelectedQuestion={handleRewriteSelectedQuestion}
|
||||
previewRawOutput={previewRawOutput}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 py-20 text-center text-muted-foreground">No preview available</div>
|
||||
)}
|
||||
<div className="border-t p-4 flex justify-end">
|
||||
<Button type="button" disabled={previewLoading || previewNodes.length === 0} onClick={handleConfirmCreate}>
|
||||
Confirm & Create
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
173
src/modules/exams/components/exam-preview-question-editor.tsx
Normal file
173
src/modules/exams/components/exam-preview-question-editor.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
"use client"
|
||||
|
||||
import { Loader2, Wand2 } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
import type { Question } from "@/modules/questions/types"
|
||||
import type { EditableQuestionContent } from "./exam-form-types"
|
||||
import { QuestionOptionsEditor } from "./question-options-editor"
|
||||
import { QuestionSubQuestionsEditor } from "./question-sub-questions-editor"
|
||||
|
||||
type ExamPreviewQuestionEditorProps = {
|
||||
selectedQuestion: ExamNode | null
|
||||
selectedContent: EditableQuestionContent | null
|
||||
selectedQuestionId: string
|
||||
updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
|
||||
parseEditableContent: (raw: unknown) => EditableQuestionContent
|
||||
rewriteInstruction: string
|
||||
setRewriteInstruction: (value: string) => void
|
||||
rewritingQuestion: boolean
|
||||
handleRewriteSelectedQuestion: () => void
|
||||
previewRawOutput: string
|
||||
}
|
||||
|
||||
export function ExamPreviewQuestionEditor({
|
||||
selectedQuestion,
|
||||
selectedContent,
|
||||
selectedQuestionId,
|
||||
updatePreviewQuestionNode,
|
||||
parseEditableContent,
|
||||
rewriteInstruction,
|
||||
setRewriteInstruction,
|
||||
rewritingQuestion,
|
||||
handleRewriteSelectedQuestion,
|
||||
previewRawOutput,
|
||||
}: ExamPreviewQuestionEditorProps) {
|
||||
if (!selectedQuestion?.question || !selectedContent) {
|
||||
return <div className="flex-1 py-20 text-center text-muted-foreground">请选择左侧题目后进行编辑</div>
|
||||
}
|
||||
|
||||
const isChoiceQuestion = selectedQuestion.question.type === "single_choice" || selectedQuestion.question.type === "multiple_choice"
|
||||
|
||||
return (
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
<div className="p-4 border-b flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium">题目编辑</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">直接修改或通过 AI 指令重写当前题目</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="p-4 space-y-4">
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label>题型</Label>
|
||||
<Select
|
||||
value={selectedQuestion.question.type}
|
||||
onValueChange={(value) => {
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
return { ...node, question: { ...node.question, type: value as Question["type"] } }
|
||||
})
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="single_choice">single_choice</SelectItem>
|
||||
<SelectItem value="multiple_choice">multiple_choice</SelectItem>
|
||||
<SelectItem value="judgment">judgment</SelectItem>
|
||||
<SelectItem value="text">text</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>难度</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={5}
|
||||
value={selectedQuestion.question.difficulty ?? 3}
|
||||
onChange={(event) => {
|
||||
const next = Number.parseInt(event.target.value || "3", 10)
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
return { ...node, question: { ...node.question, difficulty: Number.isFinite(next) ? next : 3 } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>分值</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={selectedQuestion.score ?? 0}
|
||||
onChange={(event) => {
|
||||
const next = Number.parseInt(event.target.value || "0", 10)
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => ({ ...node, score: Number.isFinite(next) ? next : 0 }))
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label>题干</Label>
|
||||
<Textarea
|
||||
className="min-h-[140px]"
|
||||
value={selectedContent.text}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
return { ...node, question: { ...node.question, content: { ...current, text } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isChoiceQuestion ? (
|
||||
<QuestionOptionsEditor
|
||||
selectedQuestionId={selectedQuestionId}
|
||||
selectedContent={selectedContent}
|
||||
questionType={selectedQuestion.question.type}
|
||||
updatePreviewQuestionNode={updatePreviewQuestionNode}
|
||||
parseEditableContent={parseEditableContent}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<QuestionSubQuestionsEditor
|
||||
selectedQuestionId={selectedQuestionId}
|
||||
selectedContent={selectedContent}
|
||||
updatePreviewQuestionNode={updatePreviewQuestionNode}
|
||||
parseEditableContent={parseEditableContent}
|
||||
/>
|
||||
|
||||
<div className="rounded-md border p-3 space-y-2">
|
||||
<Label>AI 重写指令</Label>
|
||||
<Textarea
|
||||
className="min-h-[90px]"
|
||||
placeholder="例如:把这题改成更难、增加一个干扰项、保持总分不变。"
|
||||
value={rewriteInstruction}
|
||||
onChange={(event) => setRewriteInstruction(event.target.value)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="outline" onClick={handleRewriteSelectedQuestion} disabled={rewritingQuestion}>
|
||||
{rewritingQuestion ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Wand2 className="mr-2 h-4 w-4" />}
|
||||
AI 重写当前题目
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{previewRawOutput ? (
|
||||
<div className="rounded-md border bg-muted/30 p-3">
|
||||
<div className="text-xs font-medium mb-2">模型原始输出</div>
|
||||
<pre className="whitespace-pre-wrap text-xs text-muted-foreground">{previewRawOutput}</pre>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
205
src/modules/exams/components/exam-preview-utils.ts
Normal file
205
src/modules/exams/components/exam-preview-utils.ts
Normal file
@@ -0,0 +1,205 @@
|
||||
import { createId } from "@paralleldrive/cuid2"
|
||||
import type { AiPreviewData } from "../actions"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
import type { Question } from "@/modules/questions/types"
|
||||
import type { EditableQuestionContent, ExamFormValues, PreviewSnapshotMeta } from "./exam-form-types"
|
||||
|
||||
export function buildPreviewNodes(data: AiPreviewData): ExamNode[] {
|
||||
const now = new Date()
|
||||
const toQuestionNode = (q: { id: string; type: Question["type"]; difficulty: number; score: number; content: Question["content"] }): ExamNode => ({
|
||||
id: q.id,
|
||||
type: "question",
|
||||
questionId: q.id,
|
||||
score: q.score,
|
||||
question: {
|
||||
id: q.id,
|
||||
content: q.content,
|
||||
type: q.type,
|
||||
difficulty: q.difficulty,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
author: null,
|
||||
knowledgePoints: [],
|
||||
} satisfies Question,
|
||||
})
|
||||
|
||||
if (data.sections && data.sections.length > 0) {
|
||||
return data.sections.map((section) => ({
|
||||
id: section.id || createId(),
|
||||
type: "group",
|
||||
title: section.title,
|
||||
children: section.questions.map((q) => toQuestionNode(q)),
|
||||
}))
|
||||
}
|
||||
|
||||
return (data.questions ?? []).map((q) => toQuestionNode(q))
|
||||
}
|
||||
|
||||
export function parseEditableContent(raw: unknown): EditableQuestionContent {
|
||||
const parseFromObject = (value: unknown): EditableQuestionContent => {
|
||||
if (!value || typeof value !== "object") return { text: "", options: [], subQuestions: [] }
|
||||
const record = value as { text?: unknown; options?: unknown; subQuestions?: unknown }
|
||||
const text = typeof record.text === "string" ? record.text : ""
|
||||
const options = Array.isArray(record.options)
|
||||
? record.options.map((opt, index) => {
|
||||
const item = opt && typeof opt === "object" ? opt as { id?: unknown; text?: unknown; isCorrect?: unknown } : {}
|
||||
return {
|
||||
id: typeof item.id === "string" && item.id.trim().length > 0 ? item.id : String.fromCharCode(65 + index),
|
||||
text: typeof item.text === "string" ? item.text : "",
|
||||
isCorrect: typeof item.isCorrect === "boolean" ? item.isCorrect : false,
|
||||
}
|
||||
})
|
||||
: []
|
||||
const subQuestions = Array.isArray(record.subQuestions)
|
||||
? record.subQuestions.map((item, index) => {
|
||||
const row = item && typeof item === "object"
|
||||
? item as { id?: unknown; text?: unknown; answer?: unknown; score?: unknown }
|
||||
: {}
|
||||
const rawScore = typeof row.score === "number" ? row.score : Number.parseInt(String(row.score ?? ""), 10)
|
||||
return {
|
||||
id: typeof row.id === "string" && row.id.trim().length > 0 ? row.id : String(index + 1),
|
||||
text: typeof row.text === "string" ? row.text : "",
|
||||
answer: typeof row.answer === "string" ? row.answer : "",
|
||||
score: Number.isFinite(rawScore) ? rawScore : undefined,
|
||||
}
|
||||
})
|
||||
: []
|
||||
return { text, options, subQuestions }
|
||||
}
|
||||
|
||||
if (typeof raw === "string") {
|
||||
try {
|
||||
return parseFromObject(JSON.parse(raw))
|
||||
} catch {
|
||||
return { text: raw, options: [], subQuestions: [] }
|
||||
}
|
||||
}
|
||||
return parseFromObject(raw)
|
||||
}
|
||||
|
||||
export function flattenPreviewQuestions(nodes: ExamNode[]) {
|
||||
const rows: Array<{ node: ExamNode; sectionTitle?: string }> = []
|
||||
const walk = (items: ExamNode[], sectionTitle?: string) => {
|
||||
items.forEach((node) => {
|
||||
if (node.type === "question" && node.questionId && node.question) {
|
||||
rows.push({ node, sectionTitle })
|
||||
return
|
||||
}
|
||||
if (node.type === "group" && node.children) {
|
||||
walk(node.children, node.title || sectionTitle)
|
||||
}
|
||||
})
|
||||
}
|
||||
walk(nodes)
|
||||
return rows
|
||||
}
|
||||
|
||||
export function findPreviewQuestionNode(nodes: ExamNode[], questionId: string): ExamNode | null {
|
||||
for (const node of nodes) {
|
||||
if (node.type === "question" && node.questionId === questionId && node.question) {
|
||||
return node
|
||||
}
|
||||
if (node.type === "group" && node.children) {
|
||||
const found = findPreviewQuestionNode(node.children, questionId)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function updatePreviewQuestionNodeInList(questionId: string, items: ExamNode[], updater: (node: ExamNode) => ExamNode): ExamNode[] {
|
||||
return items.map((node) => {
|
||||
if (node.type === "question" && node.questionId === questionId && node.question) {
|
||||
return updater(node)
|
||||
}
|
||||
if (node.type === "group" && node.children) {
|
||||
return { ...node, children: updatePreviewQuestionNodeInList(questionId, node.children, updater) }
|
||||
}
|
||||
return node
|
||||
})
|
||||
}
|
||||
|
||||
export function buildPreviewSignature(values: ExamFormValues) {
|
||||
return JSON.stringify({
|
||||
sourceText: values.aiSourceText?.trim() || "",
|
||||
questionCount: values.aiQuestionCount ?? null,
|
||||
providerId: values.aiProviderId ?? "",
|
||||
title: values.title?.trim() || "",
|
||||
subject: values.subject?.trim() || "",
|
||||
grade: values.grade?.trim() || "",
|
||||
difficulty: values.difficulty ?? "",
|
||||
totalScore: values.totalScore ?? "",
|
||||
durationMin: values.durationMin ?? "",
|
||||
})
|
||||
}
|
||||
|
||||
export function buildPreviewPayload(nodes: ExamNode[]) {
|
||||
const questions: Array<{
|
||||
id: string
|
||||
type: Question["type"]
|
||||
difficulty: number
|
||||
score: number
|
||||
content: Question["content"]
|
||||
}> = []
|
||||
const seen = new Set<string>()
|
||||
const collect = (items: ExamNode[]) => {
|
||||
items.forEach((node) => {
|
||||
if (node.type === "question" && node.questionId && node.question) {
|
||||
if (!seen.has(node.questionId)) {
|
||||
seen.add(node.questionId)
|
||||
questions.push({
|
||||
id: node.questionId,
|
||||
type: node.question.type,
|
||||
difficulty: node.question.difficulty ?? 3,
|
||||
score: node.score ?? 0,
|
||||
content: node.question.content,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
if (node.type === "group" && node.children) collect(node.children)
|
||||
})
|
||||
}
|
||||
collect(nodes)
|
||||
|
||||
const cleanStructure = (items: ExamNode[]): Array<Omit<ExamNode, "question"> & { children?: unknown[] }> => {
|
||||
return items.map((node) => {
|
||||
const { question, ...rest } = node
|
||||
void question
|
||||
if (node.type === "group") {
|
||||
return { ...rest, children: cleanStructure(node.children || []) }
|
||||
}
|
||||
return rest
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
questions,
|
||||
structure: cleanStructure(nodes),
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPreviewRequestData(values: ExamFormValues) {
|
||||
const sourceText = values.aiSourceText?.trim()
|
||||
if (!sourceText) return null
|
||||
const formData = new FormData()
|
||||
if (values.title?.trim()) formData.append("title", values.title.trim())
|
||||
if (values.subject?.trim()) formData.append("subject", values.subject.trim())
|
||||
if (values.grade?.trim()) formData.append("grade", values.grade.trim())
|
||||
const previewDifficulty = Number.parseInt(String(values.difficulty ?? "3"), 10)
|
||||
const previewTotalScore = typeof values.totalScore === "number" && values.totalScore > 0 ? values.totalScore : 100
|
||||
const previewDurationMin = typeof values.durationMin === "number" && values.durationMin > 0 ? values.durationMin : 90
|
||||
formData.append("difficulty", Number.isFinite(previewDifficulty) && previewDifficulty >= 1 && previewDifficulty <= 5 ? String(previewDifficulty) : "3")
|
||||
formData.append("totalScore", String(previewTotalScore))
|
||||
formData.append("durationMin", String(previewDurationMin))
|
||||
formData.append("aiSourceText", sourceText)
|
||||
if (values.aiQuestionCount) formData.append("aiQuestionCount", values.aiQuestionCount.toString())
|
||||
if (values.aiProviderId) formData.append("aiProviderId", values.aiProviderId)
|
||||
const meta: PreviewSnapshotMeta = {
|
||||
subject: values.subject?.trim() || "—",
|
||||
grade: values.grade?.trim() || "—",
|
||||
durationMin: previewDurationMin,
|
||||
totalScore: previewTotalScore,
|
||||
}
|
||||
return { formData, meta, signature: buildPreviewSignature(values) }
|
||||
}
|
||||
130
src/modules/exams/components/question-options-editor.tsx
Normal file
130
src/modules/exams/components/question-options-editor.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
"use client"
|
||||
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Checkbox } from "@/shared/components/ui/checkbox"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
import type { EditableQuestionContent } from "./exam-form-types"
|
||||
|
||||
type QuestionOptionsEditorProps = {
|
||||
selectedQuestionId: string
|
||||
selectedContent: EditableQuestionContent
|
||||
questionType: string
|
||||
updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
|
||||
parseEditableContent: (raw: unknown) => EditableQuestionContent
|
||||
}
|
||||
|
||||
export function QuestionOptionsEditor({
|
||||
selectedQuestionId,
|
||||
selectedContent,
|
||||
questionType,
|
||||
updatePreviewQuestionNode,
|
||||
parseEditableContent,
|
||||
}: QuestionOptionsEditorProps) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>选项</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const nextId = String.fromCharCode(65 + current.options.length)
|
||||
return {
|
||||
...node,
|
||||
question: {
|
||||
...node.question,
|
||||
content: {
|
||||
...current,
|
||||
options: [...current.options, { id: nextId, text: "", isCorrect: false }],
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-1 h-3.5 w-3.5" />
|
||||
新增选项
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{selectedContent.options.map((option, optionIndex) => (
|
||||
<div key={`${option.id}-${optionIndex}`} className="flex items-center gap-2 rounded-md border p-2">
|
||||
<Input
|
||||
className="w-16"
|
||||
value={option.id}
|
||||
onChange={(event) => {
|
||||
const nextId = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const options = current.options.map((item, idx) => idx === optionIndex ? { ...item, id: nextId } : item)
|
||||
return { ...node, question: { ...node.question, content: { ...current, options } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
className="flex-1"
|
||||
value={option.text}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const options = current.options.map((item, idx) => idx === optionIndex ? { ...item, text } : item)
|
||||
return { ...node, question: { ...node.question, content: { ...current, options } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2 px-2">
|
||||
<Checkbox
|
||||
aria-label={`标记选项 ${option.id} 为正确答案`}
|
||||
checked={option.isCorrect}
|
||||
onCheckedChange={(checked) => {
|
||||
const isCorrect = Boolean(checked)
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const options = current.options.map((item, idx) => {
|
||||
if (idx !== optionIndex) {
|
||||
if (questionType === "single_choice") {
|
||||
return { ...item, isCorrect: false }
|
||||
}
|
||||
return item
|
||||
}
|
||||
return { ...item, isCorrect }
|
||||
})
|
||||
return { ...node, question: { ...node.question, content: { ...current, options } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">正确</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="删除选项"
|
||||
onClick={() => {
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const options = current.options.filter((_, idx) => idx !== optionIndex)
|
||||
return { ...node, question: { ...node.question, content: { ...current, options } } }
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
137
src/modules/exams/components/question-sub-questions-editor.tsx
Normal file
137
src/modules/exams/components/question-sub-questions-editor.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
"use client"
|
||||
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import type { ExamNode } from "./assembly/selected-question-list"
|
||||
import type { EditableQuestionContent } from "./exam-form-types"
|
||||
|
||||
type QuestionSubQuestionsEditorProps = {
|
||||
selectedQuestionId: string
|
||||
selectedContent: EditableQuestionContent
|
||||
updatePreviewQuestionNode: (questionId: string, updater: (node: ExamNode) => ExamNode) => void
|
||||
parseEditableContent: (raw: unknown) => EditableQuestionContent
|
||||
}
|
||||
|
||||
export function QuestionSubQuestionsEditor({
|
||||
selectedQuestionId,
|
||||
selectedContent,
|
||||
updatePreviewQuestionNode,
|
||||
parseEditableContent,
|
||||
}: QuestionSubQuestionsEditorProps) {
|
||||
return (
|
||||
<div className="space-y-2 rounded-md border p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>子题</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
return {
|
||||
...node,
|
||||
question: {
|
||||
...node.question,
|
||||
content: {
|
||||
...current,
|
||||
subQuestions: [
|
||||
...current.subQuestions,
|
||||
{ id: String(current.subQuestions.length + 1), text: "", answer: "", score: undefined },
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-1 h-3.5 w-3.5" />
|
||||
新增子题
|
||||
</Button>
|
||||
</div>
|
||||
{selectedContent.subQuestions.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{selectedContent.subQuestions.map((item, subIndex) => (
|
||||
<div key={`${item.id}-${subIndex}`} className="grid grid-cols-[64px_1fr_1fr_84px_36px] items-center gap-2 rounded-md border p-2">
|
||||
<Input
|
||||
value={item.id}
|
||||
onChange={(event) => {
|
||||
const nextId = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, id: nextId } : row)
|
||||
return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
value={item.text}
|
||||
placeholder="子题内容"
|
||||
onChange={(event) => {
|
||||
const text = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, text } : row)
|
||||
return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
value={item.answer ?? ""}
|
||||
placeholder="参考答案"
|
||||
onChange={(event) => {
|
||||
const answer = event.target.value
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex ? { ...row, answer } : row)
|
||||
return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={typeof item.score === "number" ? item.score : ""}
|
||||
placeholder="分值"
|
||||
onChange={(event) => {
|
||||
const next = Number.parseInt(event.target.value, 10)
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const subQuestions = current.subQuestions.map((row, idx) => idx === subIndex
|
||||
? { ...row, score: Number.isFinite(next) ? next : undefined }
|
||||
: row)
|
||||
return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
updatePreviewQuestionNode(selectedQuestionId, (node) => {
|
||||
if (!node.question) return node
|
||||
const current = parseEditableContent(node.question.content)
|
||||
const subQuestions = current.subQuestions.filter((_, idx) => idx !== subIndex)
|
||||
return { ...node, question: { ...node.question, content: { ...current, subQuestions } } }
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">当前题目没有子题</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { db } from "@/shared/db"
|
||||
import { exams, examQuestions, questions, subjects, grades } from "@/shared/db/schema"
|
||||
import { eq, desc, like, and, or } from "drizzle-orm"
|
||||
import { exams, examQuestions, questions, subjects, grades, classes } from "@/shared/db/schema"
|
||||
import { eq, desc, like, and, or, inArray } from "drizzle-orm"
|
||||
import { cache } from "react"
|
||||
|
||||
import type { Exam, ExamDifficulty, ExamStatus } from "./types"
|
||||
import type { AiGeneratedQuestion, AiGeneratedStructureNode } from "./ai-pipeline"
|
||||
import type { DataScope } from "@/shared/types/permissions"
|
||||
|
||||
export type GetExamsParams = {
|
||||
q?: string
|
||||
@@ -49,7 +50,7 @@ const toExamDifficulty = (n: number | undefined): ExamDifficulty => {
|
||||
}
|
||||
|
||||
|
||||
export const getExams = cache(async (params: GetExamsParams) => {
|
||||
export const getExams = cache(async (params: GetExamsParams & { scope: DataScope }) => {
|
||||
const conditions = []
|
||||
|
||||
if (params.q) {
|
||||
@@ -61,7 +62,28 @@ export const getExams = cache(async (params: GetExamsParams) => {
|
||||
conditions.push(eq(exams.status, params.status))
|
||||
}
|
||||
|
||||
// Note: Difficulty is stored in JSON description field in current schema,
|
||||
// Data scope filtering
|
||||
if (params.scope.type === "owned") {
|
||||
conditions.push(eq(exams.creatorId, params.scope.userId))
|
||||
}
|
||||
if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
|
||||
// Teacher can see exams for grades their classes belong to
|
||||
const teacherGradeIds = await db
|
||||
.selectDistinct({ gradeId: classes.gradeId })
|
||||
.from(classes)
|
||||
.where(inArray(classes.id, params.scope.classIds))
|
||||
const gradeIds = teacherGradeIds.map(g => g.gradeId).filter(Boolean) as string[]
|
||||
if (gradeIds.length > 0) {
|
||||
conditions.push(inArray(exams.gradeId, gradeIds))
|
||||
}
|
||||
}
|
||||
if (params.scope.type === "grade_managed" && params.scope.gradeIds.length > 0) {
|
||||
conditions.push(inArray(exams.gradeId, params.scope.gradeIds))
|
||||
}
|
||||
// "all" type: no filtering
|
||||
// "class_members": student sees published exams for their grade (would need student's gradeId)
|
||||
|
||||
// Note: Difficulty is stored in JSON description field in current schema,
|
||||
// so we might need to filter in memory or adjust schema.
|
||||
// For now, let's fetch and filter in memory if difficulty is needed,
|
||||
// or just ignore strict DB filtering for JSON fields to keep it simple.
|
||||
@@ -104,7 +126,7 @@ export const getExams = cache(async (params: GetExamsParams) => {
|
||||
return result
|
||||
})
|
||||
|
||||
export const getExamById = cache(async (id: string) => {
|
||||
export const getExamById = cache(async (id: string, scope?: DataScope) => {
|
||||
const exam = await db.query.exams.findFirst({
|
||||
where: eq(exams.id, id),
|
||||
with: {
|
||||
@@ -121,6 +143,26 @@ export const getExamById = cache(async (id: string) => {
|
||||
|
||||
if (!exam) return null
|
||||
|
||||
// Data scope verification for single-item fetch
|
||||
if (scope && scope.type !== "all") {
|
||||
if (scope.type === "owned" && exam.creatorId !== scope.userId) {
|
||||
return null
|
||||
}
|
||||
if (scope.type === "grade_managed" && scope.gradeIds.length > 0 && !scope.gradeIds.includes(exam.gradeId ?? "")) {
|
||||
return null
|
||||
}
|
||||
if (scope.type === "class_taught" && scope.classIds.length > 0) {
|
||||
const teacherGradeIds = await db
|
||||
.selectDistinct({ gradeId: classes.gradeId })
|
||||
.from(classes)
|
||||
.where(inArray(classes.id, scope.classIds))
|
||||
const gradeIds = teacherGradeIds.map(g => g.gradeId).filter(Boolean) as string[]
|
||||
if (gradeIds.length > 0 && !gradeIds.includes(exam.gradeId ?? "")) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const meta = parseExamMeta(exam.description || null)
|
||||
|
||||
return {
|
||||
|
||||
295
src/modules/exams/hooks/use-exam-preview.ts
Normal file
295
src/modules/exams/hooks/use-exam-preview.ts
Normal file
@@ -0,0 +1,295 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import type { UseFormReturn } from "react-hook-form"
|
||||
import { toast } from "sonner"
|
||||
import PQueue from "p-queue"
|
||||
import { createId } from "@paralleldrive/cuid2"
|
||||
|
||||
import { previewAiExamAction, regenerateAiQuestionAction, type AiPreviewData, type AiRewriteQuestionData } from "../actions"
|
||||
import type { ExamNode } from "../components/assembly/selected-question-list"
|
||||
import {
|
||||
type ExamFormValues,
|
||||
type PreviewSnapshotMeta,
|
||||
type PreviewBackgroundTask,
|
||||
previewTaskStorageKey,
|
||||
} from "../components/exam-form-types"
|
||||
import {
|
||||
buildPreviewNodes,
|
||||
parseEditableContent,
|
||||
flattenPreviewQuestions,
|
||||
findPreviewQuestionNode,
|
||||
updatePreviewQuestionNodeInList,
|
||||
buildPreviewSignature,
|
||||
buildPreviewPayload,
|
||||
buildPreviewRequestData,
|
||||
} from "../components/exam-preview-utils"
|
||||
|
||||
export function useExamPreview(form: UseFormReturn<ExamFormValues>) {
|
||||
const [previewOpen, setPreviewOpen] = useState(false)
|
||||
const [previewLoading, setPreviewLoading] = useState(false)
|
||||
const [previewNodes, setPreviewNodes] = useState<ExamNode[]>([])
|
||||
const [previewTitle, setPreviewTitle] = useState("")
|
||||
const [previewRawOutput, setPreviewRawOutput] = useState("")
|
||||
const [previewSignature, setPreviewSignature] = useState("")
|
||||
const [previewMeta, setPreviewMeta] = useState<PreviewSnapshotMeta | null>(null)
|
||||
const [previewTasks, setPreviewTasks] = useState<PreviewBackgroundTask[]>([])
|
||||
const [selectedQuestionId, setSelectedQuestionId] = useState<string>("")
|
||||
const [rewriteInstruction, setRewriteInstruction] = useState("")
|
||||
const [rewritingQuestion, setRewritingQuestion] = useState(false)
|
||||
|
||||
const previewQueueRef = useRef<PQueue | null>(null)
|
||||
if (!previewQueueRef.current) {
|
||||
previewQueueRef.current = new PQueue({ concurrency: 3 })
|
||||
}
|
||||
const previewQueue = previewQueueRef.current
|
||||
|
||||
const persistPreviewTasks = (tasks: PreviewBackgroundTask[]) => {
|
||||
try {
|
||||
window.localStorage.setItem(previewTaskStorageKey, JSON.stringify(tasks.slice(0, 20)))
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(previewTaskStorageKey)
|
||||
if (!raw) return
|
||||
const parsed = JSON.parse(raw) as PreviewBackgroundTask[]
|
||||
if (!Array.isArray(parsed)) return
|
||||
const restoredTasks = parsed
|
||||
.filter((task) => task && typeof task.id === "string")
|
||||
.map((task) => {
|
||||
if (task.status === "queued" || task.status === "running") {
|
||||
return {
|
||||
...task,
|
||||
status: "failed" as const,
|
||||
message: "页面刷新后任务已中断,请重新生成",
|
||||
}
|
||||
}
|
||||
return task
|
||||
})
|
||||
setPreviewTasks(restoredTasks)
|
||||
if (restoredTasks.length > 0) {
|
||||
form.setValue("mode", "ai")
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
setPreviewTasks([])
|
||||
}
|
||||
}, [form])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
previewQueue.clear()
|
||||
}
|
||||
}, [previewQueue])
|
||||
|
||||
useEffect(() => {
|
||||
persistPreviewTasks(previewTasks)
|
||||
}, [previewTasks])
|
||||
|
||||
const updatePreviewQuestionNode = (questionId: string, updater: (node: ExamNode) => ExamNode) => {
|
||||
setPreviewNodes((prev) => updatePreviewQuestionNodeInList(questionId, prev, updater))
|
||||
}
|
||||
|
||||
const updateSelectedQuestionFromAi = (questionId: string, data: AiRewriteQuestionData) => {
|
||||
updatePreviewQuestionNode(questionId, (node) => {
|
||||
if (!node.question) return node
|
||||
return {
|
||||
...node,
|
||||
score: data.score,
|
||||
question: {
|
||||
...node.question,
|
||||
type: data.type,
|
||||
difficulty: data.difficulty,
|
||||
content: data.content,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const applyPreviewResult = (input: { data: AiPreviewData; signature: string; meta: PreviewSnapshotMeta }) => {
|
||||
setPreviewTitle(input.data.title)
|
||||
const nextNodes = buildPreviewNodes(input.data)
|
||||
setPreviewNodes(nextNodes)
|
||||
const firstQuestion = flattenPreviewQuestions(nextNodes)[0]
|
||||
setSelectedQuestionId(firstQuestion?.node.questionId ?? "")
|
||||
setPreviewRawOutput(input.data.rawOutput ?? "")
|
||||
setPreviewSignature(input.signature)
|
||||
setPreviewMeta(input.meta)
|
||||
setRewriteInstruction("")
|
||||
setPreviewOpen(true)
|
||||
}
|
||||
|
||||
const handlePreview = async () => {
|
||||
const values = form.getValues()
|
||||
const requestData = buildPreviewRequestData(values)
|
||||
if (!requestData) {
|
||||
toast.error("Please paste the full exam text first")
|
||||
return
|
||||
}
|
||||
|
||||
setPreviewOpen(false)
|
||||
setPreviewLoading(true)
|
||||
setPreviewNodes([])
|
||||
setPreviewRawOutput("")
|
||||
setPreviewSignature("")
|
||||
setSelectedQuestionId("")
|
||||
setRewriteInstruction("")
|
||||
try {
|
||||
const result = await previewAiExamAction(null, requestData.formData)
|
||||
if (result.success && result.data) {
|
||||
applyPreviewResult({
|
||||
data: result.data,
|
||||
signature: requestData.signature,
|
||||
meta: requestData.meta,
|
||||
})
|
||||
} else {
|
||||
toast.error(result.message || "Failed to generate preview")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to generate preview")
|
||||
} finally {
|
||||
setPreviewLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBackgroundPreview = () => {
|
||||
const values = form.getValues()
|
||||
const requestData = buildPreviewRequestData(values)
|
||||
if (!requestData) {
|
||||
toast.error("Please paste the full exam text first")
|
||||
return
|
||||
}
|
||||
const taskId = createId()
|
||||
const taskTitle = values.title?.trim() || "未命名试卷"
|
||||
setPreviewTasks((prev) => {
|
||||
const next = [{ id: taskId, createdAt: Date.now(), status: "queued" as const, title: taskTitle, signature: requestData.signature }, ...prev]
|
||||
persistPreviewTasks(next)
|
||||
return next
|
||||
})
|
||||
toast.success("已加入后台队列,可继续编辑页面")
|
||||
void previewQueue.add(async () => {
|
||||
setPreviewTasks((prev) => prev.map((task) => task.id === taskId
|
||||
? { ...task, status: "running" }
|
||||
: task))
|
||||
try {
|
||||
const result = await previewAiExamAction(null, requestData.formData)
|
||||
const data = result.data
|
||||
if (result.success && data) {
|
||||
const nextNodes = buildPreviewNodes(data)
|
||||
setPreviewTasks((prev) => prev.map((task) => task.id === taskId
|
||||
? {
|
||||
...task,
|
||||
status: "success",
|
||||
result: {
|
||||
title: data.title,
|
||||
nodes: nextNodes,
|
||||
rawOutput: data.rawOutput ?? "",
|
||||
meta: requestData.meta,
|
||||
formValues: { title: values.title, subject: values.subject, grade: values.grade, difficulty: values.difficulty, totalScore: values.totalScore, durationMin: values.durationMin, aiSourceText: values.aiSourceText, aiQuestionCount: values.aiQuestionCount, aiProviderId: values.aiProviderId },
|
||||
},
|
||||
}
|
||||
: task))
|
||||
toast.success(`后台生成完成:${taskTitle}`)
|
||||
return
|
||||
}
|
||||
setPreviewTasks((prev) => prev.map((task) => task.id === taskId
|
||||
? { ...task, status: "failed", message: result.message || "Failed to generate preview" }
|
||||
: task))
|
||||
toast.error(`后台生成失败:${taskTitle}`)
|
||||
} catch {
|
||||
setPreviewTasks((prev) => prev.map((task) => task.id === taskId
|
||||
? { ...task, status: "failed", message: "Failed to generate preview" }
|
||||
: task))
|
||||
toast.error(`后台生成失败:${taskTitle}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handleOpenPreviewTask = (taskId: string) => {
|
||||
const task = previewTasks.find((item) => item.id === taskId)
|
||||
if (!task || task.status !== "success" || !task.result) return
|
||||
const tv = task.result.formValues
|
||||
const fields = ["title", "subject", "grade", "difficulty", "totalScore", "durationMin", "aiSourceText", "aiQuestionCount", "aiProviderId"] as const
|
||||
fields.forEach((key) => {
|
||||
if (typeof tv[key] !== "undefined") form.setValue(key, tv[key])
|
||||
})
|
||||
setPreviewTitle(task.result.title)
|
||||
setPreviewNodes(task.result.nodes)
|
||||
setPreviewRawOutput(task.result.rawOutput)
|
||||
setPreviewSignature(task.signature)
|
||||
setPreviewMeta(task.result.meta)
|
||||
const firstQuestion = flattenPreviewQuestions(task.result.nodes)[0]
|
||||
setSelectedQuestionId(firstQuestion?.node.questionId ?? "")
|
||||
setRewriteInstruction("")
|
||||
setPreviewOpen(true)
|
||||
}
|
||||
|
||||
const handleRewriteSelectedQuestion = async () => {
|
||||
if (!selectedQuestionId) {
|
||||
toast.error("请先选择一个题目")
|
||||
return
|
||||
}
|
||||
const selected = findPreviewQuestionNode(previewNodes, selectedQuestionId)
|
||||
if (!selected?.question) {
|
||||
toast.error("未找到选中的题目")
|
||||
return
|
||||
}
|
||||
const instruction = rewriteInstruction.trim()
|
||||
if (!instruction) {
|
||||
toast.error("请输入重写指令")
|
||||
return
|
||||
}
|
||||
setRewritingQuestion(true)
|
||||
try {
|
||||
const content = parseEditableContent(selected.question.content)
|
||||
const questionPayload = {
|
||||
type: selected.question.type,
|
||||
difficulty: selected.question.difficulty ?? 3,
|
||||
score: selected.score ?? 0,
|
||||
content: {
|
||||
text: content.text,
|
||||
options: content.options.map((opt) => ({
|
||||
id: opt.id, text: opt.text, isCorrect: opt.isCorrect,
|
||||
})),
|
||||
subQuestions: content.subQuestions.map((item) => ({
|
||||
id: item.id, text: item.text, answer: item.answer, score: item.score,
|
||||
})),
|
||||
},
|
||||
}
|
||||
const formData = new FormData()
|
||||
formData.append("instruction", instruction)
|
||||
formData.append("questionJson", JSON.stringify(questionPayload))
|
||||
const providerId = form.getValues("aiProviderId")
|
||||
const sourceText = form.getValues("aiSourceText")
|
||||
if (providerId) formData.append("aiProviderId", providerId)
|
||||
if (sourceText) formData.append("sourceText", sourceText)
|
||||
const result = await regenerateAiQuestionAction(null, formData)
|
||||
if (!result.success || !result.data) {
|
||||
toast.error(result.message || "AI 重写失败")
|
||||
return
|
||||
}
|
||||
updateSelectedQuestionFromAi(selectedQuestionId, result.data)
|
||||
setRewriteInstruction("")
|
||||
toast.success("题目已按指令重写")
|
||||
} catch {
|
||||
toast.error("AI 重写失败")
|
||||
} finally {
|
||||
setRewritingQuestion(false)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
previewOpen, setPreviewOpen, previewLoading, previewNodes, setPreviewNodes,
|
||||
previewTitle, previewRawOutput, previewSignature, previewMeta, previewTasks,
|
||||
selectedQuestionId, setSelectedQuestionId, rewriteInstruction, setRewriteInstruction,
|
||||
rewritingQuestion, buildPreviewNodes, parseEditableContent, flattenPreviewQuestions,
|
||||
findPreviewQuestionNode, updatePreviewQuestionNode, buildPreviewPayload,
|
||||
buildPreviewRequestData, buildPreviewSignature, handlePreview, handleBackgroundPreview,
|
||||
handleOpenPreviewTask, handleRewriteSelectedQuestion,
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { Exam, ExamSubmission } from "./types"
|
||||
|
||||
export let MOCK_EXAMS: Exam[] = [
|
||||
{
|
||||
id: "exam_001",
|
||||
title: "Algebra Midterm",
|
||||
subject: "Mathematics",
|
||||
grade: "Grade 10",
|
||||
status: "draft",
|
||||
difficulty: 3,
|
||||
totalScore: 100,
|
||||
durationMin: 90,
|
||||
questionCount: 25,
|
||||
scheduledAt: undefined,
|
||||
createdAt: new Date().toISOString(),
|
||||
tags: ["Algebra", "Functions"],
|
||||
},
|
||||
{
|
||||
id: "exam_002",
|
||||
title: "Physics Mechanics Quiz",
|
||||
subject: "Physics",
|
||||
grade: "Grade 11",
|
||||
status: "published",
|
||||
difficulty: 4,
|
||||
totalScore: 50,
|
||||
durationMin: 45,
|
||||
questionCount: 15,
|
||||
scheduledAt: new Date(Date.now() + 86400000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
tags: ["Mechanics", "Kinematics"],
|
||||
},
|
||||
{
|
||||
id: "exam_003",
|
||||
title: "English Reading Comprehension",
|
||||
subject: "English",
|
||||
grade: "Grade 12",
|
||||
status: "published",
|
||||
difficulty: 2,
|
||||
totalScore: 80,
|
||||
durationMin: 60,
|
||||
questionCount: 20,
|
||||
scheduledAt: new Date(Date.now() + 2 * 86400000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
tags: ["Reading", "Vocabulary"],
|
||||
},
|
||||
{
|
||||
id: "exam_004",
|
||||
title: "Chemistry Final",
|
||||
subject: "Chemistry",
|
||||
grade: "Grade 12",
|
||||
status: "archived",
|
||||
difficulty: 5,
|
||||
totalScore: 120,
|
||||
durationMin: 120,
|
||||
questionCount: 40,
|
||||
scheduledAt: new Date(Date.now() - 30 * 86400000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
tags: ["Organic", "Inorganic"],
|
||||
},
|
||||
{
|
||||
id: "exam_005",
|
||||
title: "Geometry Chapter Test",
|
||||
subject: "Mathematics",
|
||||
grade: "Grade 9",
|
||||
status: "published",
|
||||
difficulty: 3,
|
||||
totalScore: 60,
|
||||
durationMin: 50,
|
||||
questionCount: 18,
|
||||
scheduledAt: new Date(Date.now() + 3 * 86400000).toISOString(),
|
||||
createdAt: new Date().toISOString(),
|
||||
tags: ["Geometry", "Triangles"],
|
||||
},
|
||||
]
|
||||
|
||||
export const MOCK_SUBMISSIONS: ExamSubmission[] = [
|
||||
{
|
||||
id: "sub_001",
|
||||
examId: "exam_002",
|
||||
examTitle: "Physics Mechanics Quiz",
|
||||
studentName: "Alice Zhang",
|
||||
submittedAt: new Date().toISOString(),
|
||||
status: "pending",
|
||||
},
|
||||
{
|
||||
id: "sub_002",
|
||||
examId: "exam_003",
|
||||
examTitle: "English Reading Comprehension",
|
||||
studentName: "Bob Li",
|
||||
submittedAt: new Date().toISOString(),
|
||||
score: 72,
|
||||
status: "graded",
|
||||
},
|
||||
]
|
||||
|
||||
export function addMockExam(exam: Exam) {
|
||||
MOCK_EXAMS = [exam, ...MOCK_EXAMS]
|
||||
}
|
||||
|
||||
export function updateMockExam(id: string, updates: Partial<Exam>) {
|
||||
MOCK_EXAMS = MOCK_EXAMS.map((e) => (e.id === id ? { ...e, ...updates } : e))
|
||||
}
|
||||
Reference in New Issue
Block a user