feat(homework,classes,course-plans): add scans, student data, take confirm, error boundaries, dialogs, hooks, calendar
homework: - Add data-access-scans, data-access-student, data-access-utils, data-access-exam-cross - Add excellent-submissions, homework-take-confirm-dialog, homework-take-sidebar components classes: - Add class-delete-dialog, class-error-boundary, class-form-dialog, class-form-utils - Add class-list-table, class-list-toolbar, class-skeleton - Add schedule-create-dialog, schedule-delete-dialog, schedule-edit-dialog, schedule-utils - Add data-access-teacher and hooks directory course-plans: - Add course-plan-calendar, sortable-week-row, template-picker-dialog components - Add lib directory
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import "server-only"
|
||||
|
||||
import { cache } from "react"
|
||||
import { and, asc, count, desc, eq, gt, inArray, isNull, lt, lte, or, sql } from "drizzle-orm"
|
||||
import { and, asc, count, desc, eq, gt, inArray, lt, sql } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import {
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
homeworkAssignments,
|
||||
homeworkSubmissions,
|
||||
} from "@/shared/db/schema"
|
||||
import { isRecord } from "@/shared/lib/type-guards"
|
||||
import { getStudentIdsByClassId, getStudentIdsByClassIds } from "@/modules/classes/data-access"
|
||||
import { getExamIdsByGradeIds, getExamSubjectIdMap, getExamForProctoringCrossModule } from "@/modules/exams/data-access"
|
||||
import { getSubjectOptions } from "@/modules/school/data-access"
|
||||
import { getExamIdsByGradeIds } from "@/modules/exams/data-access"
|
||||
|
||||
import type {
|
||||
HomeworkAssignmentListItem,
|
||||
@@ -23,14 +23,10 @@ import type {
|
||||
HomeworkSubmissionDetails,
|
||||
HomeworkSubmissionListItem,
|
||||
HomeworkSubmissionStatus,
|
||||
StudentHomeworkAssignmentListItem,
|
||||
StudentHomeworkProgressStatus,
|
||||
StudentHomeworkTakeData,
|
||||
ExcellentSubmissionItem,
|
||||
} from "./types"
|
||||
import type { DataScope } from "@/shared/types/permissions"
|
||||
|
||||
export const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null
|
||||
|
||||
const isHomeworkAssignmentStatus = (v: unknown): v is HomeworkAssignmentStatus =>
|
||||
v === "draft" || v === "published" || v === "archived"
|
||||
|
||||
@@ -40,7 +36,7 @@ const toHomeworkAssignmentStatus = (v: string | null | undefined): HomeworkAssig
|
||||
const isHomeworkSubmissionStatus = (v: unknown): v is HomeworkSubmissionStatus =>
|
||||
v === "started" || v === "submitted" || v === "graded"
|
||||
|
||||
const toHomeworkSubmissionStatus = (v: string | null | undefined): HomeworkSubmissionStatus =>
|
||||
export const toHomeworkSubmissionStatus = (v: string | null | undefined): HomeworkSubmissionStatus =>
|
||||
isHomeworkSubmissionStatus(v) ? v : "started"
|
||||
|
||||
const isHomeworkQuestionContent = (v: unknown): v is HomeworkQuestionContent =>
|
||||
@@ -495,128 +491,6 @@ export const getHomeworkAssignmentById = cache(async (id: string, scope?: DataSc
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* V3-8: 获取关联到指定考试的所有作业(跨模块读接口)
|
||||
*
|
||||
* 供 exams 模块的考试分析仪表盘调用,获取该考试派生的所有作业及其提交统计。
|
||||
*/
|
||||
export const getHomeworkAssignmentsByExamId = cache(async (examId: string): Promise<Array<{
|
||||
id: string
|
||||
title: string
|
||||
status: string | null
|
||||
targetCount: number
|
||||
submittedCount: number
|
||||
gradedCount: number
|
||||
dueAt: string | null
|
||||
}>> => {
|
||||
const assignments = await db.query.homeworkAssignments.findMany({
|
||||
where: eq(homeworkAssignments.sourceExamId, examId),
|
||||
columns: { id: true, title: true, status: true, dueAt: true },
|
||||
})
|
||||
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
const assignmentIds = assignments.map((a) => a.id)
|
||||
|
||||
const [targetsRows, submittedRows, gradedRows] = await Promise.all([
|
||||
db
|
||||
.select({ assignmentId: homeworkAssignmentTargets.assignmentId, c: count() })
|
||||
.from(homeworkAssignmentTargets)
|
||||
.where(inArray(homeworkAssignmentTargets.assignmentId, assignmentIds))
|
||||
.groupBy(homeworkAssignmentTargets.assignmentId),
|
||||
db
|
||||
.select({ assignmentId: homeworkSubmissions.assignmentId, c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
|
||||
.from(homeworkSubmissions)
|
||||
.where(
|
||||
and(
|
||||
inArray(homeworkSubmissions.assignmentId, assignmentIds),
|
||||
inArray(homeworkSubmissions.status, ["submitted", "graded"])
|
||||
)
|
||||
)
|
||||
.groupBy(homeworkSubmissions.assignmentId),
|
||||
db
|
||||
.select({ assignmentId: homeworkSubmissions.assignmentId, c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
|
||||
.from(homeworkSubmissions)
|
||||
.where(
|
||||
and(
|
||||
inArray(homeworkSubmissions.assignmentId, assignmentIds),
|
||||
eq(homeworkSubmissions.status, "graded")
|
||||
)
|
||||
)
|
||||
.groupBy(homeworkSubmissions.assignmentId),
|
||||
])
|
||||
|
||||
const targetMap = new Map(targetsRows.map((r) => [r.assignmentId, Number(r.c)]))
|
||||
const submittedMap = new Map(submittedRows.map((r) => [r.assignmentId, Number(r.c)]))
|
||||
const gradedMap = new Map(gradedRows.map((r) => [r.assignmentId, Number(r.c)]))
|
||||
|
||||
return assignments.map((a) => ({
|
||||
id: a.id,
|
||||
title: a.title,
|
||||
status: a.status,
|
||||
targetCount: targetMap.get(a.id) ?? 0,
|
||||
submittedCount: submittedMap.get(a.id) ?? 0,
|
||||
gradedCount: gradedMap.get(a.id) ?? 0,
|
||||
dueAt: a.dueAt ? a.dueAt.toISOString() : null,
|
||||
}))
|
||||
})
|
||||
|
||||
/**
|
||||
* V3-8: 获取指定考试所有作业的已批改提交(跨模块读接口)
|
||||
*
|
||||
* 供 exams 模块的考试分析仪表盘调用,获取学生姓名、分数、答案内容用于统计分析。
|
||||
*/
|
||||
export const getGradedSubmissionsByExamId = cache(async (examId: string): Promise<Array<{
|
||||
submissionId: string
|
||||
assignmentId: string
|
||||
studentId: string
|
||||
studentName: string
|
||||
score: number
|
||||
answers: Array<{ questionId: string; score: number; answerContent: unknown }>
|
||||
}>> => {
|
||||
const assignments = await db.query.homeworkAssignments.findMany({
|
||||
where: eq(homeworkAssignments.sourceExamId, examId),
|
||||
columns: { id: true },
|
||||
})
|
||||
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
const assignmentIds = assignments.map((a) => a.id)
|
||||
|
||||
const submissions = await db.query.homeworkSubmissions.findMany({
|
||||
where: and(
|
||||
inArray(homeworkSubmissions.assignmentId, assignmentIds),
|
||||
eq(homeworkSubmissions.status, "graded")
|
||||
),
|
||||
with: {
|
||||
student: true,
|
||||
answers: {
|
||||
columns: { questionId: true, score: true, answerContent: true },
|
||||
},
|
||||
},
|
||||
orderBy: (s, { desc }) => [desc(s.updatedAt)],
|
||||
})
|
||||
|
||||
// Deduplicate: keep only the latest submission per student
|
||||
const latestByStudent = new Map<string, (typeof submissions)[number]>()
|
||||
for (const s of submissions) {
|
||||
if (!latestByStudent.has(s.studentId)) latestByStudent.set(s.studentId, s)
|
||||
}
|
||||
|
||||
return Array.from(latestByStudent.values()).map((s) => ({
|
||||
submissionId: s.id,
|
||||
assignmentId: s.assignmentId,
|
||||
studentId: s.studentId,
|
||||
studentName: s.student.name || "Unknown",
|
||||
score: s.score ?? 0,
|
||||
answers: s.answers.map((a) => ({
|
||||
questionId: a.questionId,
|
||||
score: a.score ?? 0,
|
||||
answerContent: a.answerContent,
|
||||
})),
|
||||
}))
|
||||
})
|
||||
|
||||
export const getHomeworkSubmissionDetails = cache(async (submissionId: string): Promise<HomeworkSubmissionDetails | null> => {
|
||||
const submission = await db.query.homeworkSubmissions.findFirst({
|
||||
where: eq(homeworkSubmissions.id, submissionId),
|
||||
@@ -702,307 +576,139 @@ export const getHomeworkSubmissionDetails = cache(async (submissionId: string):
|
||||
})
|
||||
|
||||
/**
|
||||
* V3-9: 获取学生在指定作业的最新提交结果(用于提交后反馈页)
|
||||
* 查询某作业下的优秀提交(P3-1:优秀作业展示)。
|
||||
*
|
||||
* 查找学生最近一次已提交/已批改的 submission,返回完整详情含答案。
|
||||
* 评分规则:
|
||||
* - 仅返回 `status = "graded"` 且 `score IS NOT NULL` 的提交。
|
||||
* - 同一学生多次提交时,仅保留最高分(避免重复展示)。
|
||||
* - 按得分百分比 `score / maxScore` 降序排列。
|
||||
* - 过滤出百分比 ≥ `minPercentage`(默认 80)的提交。
|
||||
*
|
||||
* 权限说明:调用方必须在外层通过 `requirePermission()` 校验,
|
||||
* 并通过 `scope` 参数传入数据范围(教师仅可见自己班级的学生提交)。
|
||||
*/
|
||||
export const getStudentSubmissionResult = cache(async (
|
||||
assignmentId: string,
|
||||
studentId: string
|
||||
): Promise<HomeworkSubmissionDetails | null> => {
|
||||
const latestSubmission = await db.query.homeworkSubmissions.findFirst({
|
||||
where: and(
|
||||
eq(homeworkSubmissions.assignmentId, assignmentId),
|
||||
eq(homeworkSubmissions.studentId, studentId),
|
||||
inArray(homeworkSubmissions.status, ["submitted", "graded"])
|
||||
),
|
||||
orderBy: [desc(homeworkSubmissions.updatedAt)],
|
||||
columns: { id: true },
|
||||
export const getExcellentSubmissions = cache(async (params: {
|
||||
assignmentId: string
|
||||
minPercentage?: number
|
||||
limit?: number
|
||||
scope?: DataScope
|
||||
}): Promise<ExcellentSubmissionItem[]> => {
|
||||
const minPct = params.minPercentage ?? 80
|
||||
const limit = Math.max(1, Math.min(50, params.limit ?? 10))
|
||||
|
||||
// 1. 拉取该作业所有已批改提交
|
||||
const conditions = [
|
||||
eq(homeworkSubmissions.assignmentId, params.assignmentId),
|
||||
eq(homeworkSubmissions.status, "graded"),
|
||||
sql`${homeworkSubmissions.score} IS NOT NULL`,
|
||||
]
|
||||
|
||||
if (params.scope) {
|
||||
if (params.scope.type === "class_taught" && params.scope.classIds.length > 0) {
|
||||
const classStudentIds = await getStudentIdsByClassIds(params.scope.classIds)
|
||||
conditions.push(inArray(homeworkSubmissions.studentId, classStudentIds))
|
||||
} else if (params.scope.type === "owned") {
|
||||
const creatorAssignmentIds = db
|
||||
.select({ assignmentId: homeworkAssignments.id })
|
||||
.from(homeworkAssignments)
|
||||
.where(eq(homeworkAssignments.creatorId, params.scope.userId))
|
||||
|
||||
conditions.push(inArray(homeworkSubmissions.assignmentId, creatorAssignmentIds))
|
||||
}
|
||||
// grade_managed / all 不额外过滤(依赖 assignment 维度即可)
|
||||
}
|
||||
|
||||
const submissions = await db.query.homeworkSubmissions.findMany({
|
||||
where: and(...conditions),
|
||||
with: {
|
||||
student: true,
|
||||
assignment: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!latestSubmission) return null
|
||||
// 2. 计算总分阈值(来自作业题目分数之和)
|
||||
const maxScoreRows = await db
|
||||
.select({
|
||||
maxScore: sql<number>`COALESCE(SUM(${homeworkAssignmentQuestions.score}), 0)`,
|
||||
})
|
||||
.from(homeworkAssignmentQuestions)
|
||||
.where(eq(homeworkAssignmentQuestions.assignmentId, params.assignmentId))
|
||||
|
||||
return getHomeworkSubmissionDetails(latestSubmission.id)
|
||||
const maxScore = Number(maxScoreRows[0]?.maxScore ?? 0)
|
||||
|
||||
// 3. 同一学生取最高分
|
||||
const bestByStudent = new Map<string, ExcellentSubmissionItem>()
|
||||
for (const s of submissions) {
|
||||
if (s.score === null) continue
|
||||
const percentage = maxScore > 0 ? Math.round((s.score / maxScore) * 1000) / 10 : 0
|
||||
if (percentage < minPct) continue
|
||||
|
||||
const existing = bestByStudent.get(s.studentId)
|
||||
if (existing && existing.percentage >= percentage) continue
|
||||
|
||||
bestByStudent.set(s.studentId, {
|
||||
submissionId: s.id,
|
||||
assignmentId: s.assignmentId,
|
||||
assignmentTitle: s.assignment.title,
|
||||
studentName: s.student.name || "Unknown",
|
||||
totalScore: s.score,
|
||||
maxScore,
|
||||
percentage,
|
||||
submittedAt: s.submittedAt ? s.submittedAt.toISOString() : "",
|
||||
isLate: s.isLate,
|
||||
})
|
||||
}
|
||||
|
||||
// 4. 排序 + 截断
|
||||
return Array.from(bestByStudent.values())
|
||||
.sort((a, b) => b.percentage - a.percentage)
|
||||
.slice(0, limit)
|
||||
})
|
||||
|
||||
/**
|
||||
* V3-11: 获取学生的考试结果列表(供家长端展示)
|
||||
* 查询某作业下尚未提交(或未开始)的学生列表(P3-2:作业催交提醒)。
|
||||
*
|
||||
* 查找学生所有已批改的、关联到考试的作业提交,
|
||||
* 返回考试标题、科目、分数、提交时间等。
|
||||
* 逻辑:
|
||||
* - 从 `homeworkAssignmentTargets` 获取作业目标学生。
|
||||
* - 排除已有 `submitted` 或 `graded` 状态提交的学生。
|
||||
* - 返回学生 ID + 姓名,用于发送催交通知。
|
||||
*
|
||||
* 权限:调用方必须通过 `requirePermission()` 校验。
|
||||
*/
|
||||
export const getStudentExamResults = cache(async (studentId: string): Promise<Array<{
|
||||
submissionId: string
|
||||
examId: string
|
||||
examTitle: string
|
||||
export const getUnsubmittedStudents = cache(async (params: {
|
||||
assignmentId: string
|
||||
assignmentTitle: string
|
||||
score: number
|
||||
maxScore: number
|
||||
submittedAt: string | null
|
||||
status: string
|
||||
}>> => {
|
||||
const submissions = await db.query.homeworkSubmissions.findMany({
|
||||
where: and(
|
||||
eq(homeworkSubmissions.studentId, studentId),
|
||||
eq(homeworkSubmissions.status, "graded")
|
||||
),
|
||||
scope?: DataScope
|
||||
}): Promise<Array<{ studentId: string; studentName: string }>> => {
|
||||
// 1. 获取作业目标学生
|
||||
const targets = await db.query.homeworkAssignmentTargets.findMany({
|
||||
where: eq(homeworkAssignmentTargets.assignmentId, params.assignmentId),
|
||||
with: {
|
||||
assignment: {
|
||||
with: { sourceExam: true },
|
||||
},
|
||||
student: true,
|
||||
},
|
||||
orderBy: [desc(homeworkSubmissions.updatedAt)],
|
||||
limit: 50,
|
||||
})
|
||||
|
||||
// Filter to only exam-linked submissions, deduplicate by examId
|
||||
const latestByExamId = new Map<string, (typeof submissions)[number]>()
|
||||
for (const s of submissions) {
|
||||
const examId = s.assignment.sourceExamId
|
||||
if (!examId) continue
|
||||
if (!latestByExamId.has(examId)) latestByExamId.set(examId, s)
|
||||
}
|
||||
if (targets.length === 0) return []
|
||||
|
||||
const examIds = Array.from(latestByExamId.keys())
|
||||
if (examIds.length === 0) return []
|
||||
|
||||
// Get max scores for each assignment
|
||||
const assignmentIds = Array.from(latestByExamId.values()).map((s) => s.assignmentId)
|
||||
const maxScoreMap = await getAssignmentMaxScoreById(assignmentIds)
|
||||
|
||||
return Array.from(latestByExamId.entries()).map(([examId, s]) => ({
|
||||
submissionId: s.id,
|
||||
examId,
|
||||
examTitle: s.assignment.sourceExam?.title ?? s.assignment.title,
|
||||
assignmentId: s.assignmentId,
|
||||
assignmentTitle: s.assignment.title,
|
||||
score: s.score ?? 0,
|
||||
maxScore: maxScoreMap.get(s.assignmentId) ?? 0,
|
||||
submittedAt: s.submittedAt ? s.submittedAt.toISOString() : null,
|
||||
status: s.status ?? "graded",
|
||||
}))
|
||||
})
|
||||
|
||||
const toStudentProgressStatus = (v: string | null | undefined): StudentHomeworkProgressStatus => {
|
||||
if (v === "started") return "in_progress"
|
||||
if (v === "submitted") return "submitted"
|
||||
if (v === "graded") return "graded"
|
||||
return "not_started"
|
||||
}
|
||||
|
||||
export const getStudentHomeworkAssignments = cache(async (studentId: string): Promise<StudentHomeworkAssignmentListItem[]> => {
|
||||
const now = new Date()
|
||||
|
||||
const targetAssignmentIds = db
|
||||
.select({ assignmentId: homeworkAssignmentTargets.assignmentId })
|
||||
.from(homeworkAssignmentTargets)
|
||||
.where(eq(homeworkAssignmentTargets.studentId, studentId))
|
||||
|
||||
const assignments = await db
|
||||
.select({
|
||||
id: homeworkAssignments.id,
|
||||
title: homeworkAssignments.title,
|
||||
sourceExamId: homeworkAssignments.sourceExamId,
|
||||
dueAt: homeworkAssignments.dueAt,
|
||||
availableAt: homeworkAssignments.availableAt,
|
||||
maxAttempts: homeworkAssignments.maxAttempts,
|
||||
createdAt: homeworkAssignments.createdAt,
|
||||
})
|
||||
.from(homeworkAssignments)
|
||||
.where(
|
||||
and(
|
||||
eq(homeworkAssignments.status, "published"),
|
||||
inArray(homeworkAssignments.id, targetAssignmentIds),
|
||||
or(isNull(homeworkAssignments.availableAt), lte(homeworkAssignments.availableAt, now))
|
||||
)
|
||||
)
|
||||
.orderBy(desc(homeworkAssignments.dueAt), desc(homeworkAssignments.createdAt))
|
||||
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
// Fetch subject names via cross-module interfaces
|
||||
// 快速作业无 sourceExamId,过滤 null 后再查询科目映射
|
||||
const examIds = assignments
|
||||
.map((a) => a.sourceExamId)
|
||||
.filter((id): id is string => id !== null)
|
||||
const [examSubjectIdMap, subjectOptions] = await Promise.all([
|
||||
getExamSubjectIdMap(examIds),
|
||||
getSubjectOptions(),
|
||||
])
|
||||
const subjectNameById = new Map<string, string>()
|
||||
for (const s of subjectOptions) subjectNameById.set(s.id, s.name)
|
||||
|
||||
const assignmentIds = assignments.map((a) => a.id)
|
||||
const submissions = await db.query.homeworkSubmissions.findMany({
|
||||
where: and(eq(homeworkSubmissions.studentId, studentId), inArray(homeworkSubmissions.assignmentId, assignmentIds)),
|
||||
orderBy: [desc(homeworkSubmissions.updatedAt)],
|
||||
})
|
||||
|
||||
const attemptsByAssignmentId = new Map<string, number>()
|
||||
const latestByAssignmentId = new Map<string, (typeof submissions)[number]>()
|
||||
const latestSubmittedByAssignmentId = new Map<string, (typeof submissions)[number]>()
|
||||
|
||||
for (const s of submissions) {
|
||||
attemptsByAssignmentId.set(s.assignmentId, (attemptsByAssignmentId.get(s.assignmentId) ?? 0) + 1)
|
||||
if (!latestByAssignmentId.has(s.assignmentId)) latestByAssignmentId.set(s.assignmentId, s)
|
||||
if (s.status === "submitted" || s.status === "graded") {
|
||||
if (!latestSubmittedByAssignmentId.has(s.assignmentId)) latestSubmittedByAssignmentId.set(s.assignmentId, s)
|
||||
}
|
||||
}
|
||||
|
||||
return assignments.map((a) => {
|
||||
const latest = latestSubmittedByAssignmentId.get(a.id) ?? latestByAssignmentId.get(a.id) ?? null
|
||||
const attemptsUsed = attemptsByAssignmentId.get(a.id) ?? 0
|
||||
const subjectId = a.sourceExamId ? (examSubjectIdMap.get(a.sourceExamId) ?? null) : null
|
||||
const subjectName = subjectId ? subjectNameById.get(subjectId) ?? null : null
|
||||
|
||||
const item: StudentHomeworkAssignmentListItem = {
|
||||
id: a.id,
|
||||
title: a.title,
|
||||
subjectName: subjectName ?? null,
|
||||
dueAt: a.dueAt ? a.dueAt.toISOString() : null,
|
||||
availableAt: a.availableAt ? a.availableAt.toISOString() : null,
|
||||
maxAttempts: a.maxAttempts,
|
||||
attemptsUsed,
|
||||
progressStatus: toStudentProgressStatus(latest?.status),
|
||||
latestSubmissionId: latest?.id ?? null,
|
||||
latestSubmittedAt: latest?.submittedAt ? latest.submittedAt.toISOString() : null,
|
||||
latestScore: latest?.score ?? null,
|
||||
}
|
||||
return item
|
||||
})
|
||||
})
|
||||
|
||||
export const getStudentHomeworkTakeData = cache(async (assignmentId: string, studentId: string): Promise<StudentHomeworkTakeData | null> => {
|
||||
const target = await db.query.homeworkAssignmentTargets.findFirst({
|
||||
where: and(eq(homeworkAssignmentTargets.assignmentId, assignmentId), eq(homeworkAssignmentTargets.studentId, studentId)),
|
||||
})
|
||||
if (!target) return null
|
||||
|
||||
const assignment = await db.query.homeworkAssignments.findFirst({
|
||||
where: eq(homeworkAssignments.id, assignmentId),
|
||||
})
|
||||
if (!assignment) return null
|
||||
if (assignment.status !== "published") return null
|
||||
|
||||
const now = new Date()
|
||||
if (assignment.availableAt && assignment.availableAt > now) return null
|
||||
|
||||
const startedSubmission = await db.query.homeworkSubmissions.findFirst({
|
||||
// 2. 获取已提交的学生 ID(submitted 或 graded 状态)
|
||||
const submitted = await db.query.homeworkSubmissions.findMany({
|
||||
where: and(
|
||||
eq(homeworkSubmissions.assignmentId, assignmentId),
|
||||
eq(homeworkSubmissions.studentId, studentId),
|
||||
eq(homeworkSubmissions.status, "started")
|
||||
eq(homeworkSubmissions.assignmentId, params.assignmentId),
|
||||
inArray(homeworkSubmissions.status, ["submitted", "graded"])
|
||||
),
|
||||
orderBy: (s, { desc }) => [desc(s.createdAt)],
|
||||
columns: { studentId: true },
|
||||
})
|
||||
|
||||
const latestSubmission =
|
||||
startedSubmission ??
|
||||
(await db.query.homeworkSubmissions.findFirst({
|
||||
where: and(eq(homeworkSubmissions.assignmentId, assignmentId), eq(homeworkSubmissions.studentId, studentId)),
|
||||
orderBy: (s, { desc }) => [desc(s.createdAt)],
|
||||
const submittedIds = new Set(submitted.map((s) => s.studentId))
|
||||
|
||||
// 3. 过滤出未提交的学生
|
||||
const unsubmitted = targets
|
||||
.filter((t) => !submittedIds.has(t.studentId))
|
||||
.map((t) => ({
|
||||
studentId: t.studentId,
|
||||
studentName: t.student.name || "Unknown",
|
||||
}))
|
||||
|
||||
const assignmentQuestions = await db.query.homeworkAssignmentQuestions.findMany({
|
||||
where: eq(homeworkAssignmentQuestions.assignmentId, assignmentId),
|
||||
with: {
|
||||
question: {
|
||||
with: {
|
||||
knowledgePoints: {
|
||||
with: {
|
||||
knowledgePoint: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: (q, { asc }) => [asc(q.order)],
|
||||
})
|
||||
|
||||
const answersByQuestionId = new Map<string, { answer: unknown; score: number | null; feedback: string | null }>()
|
||||
if (latestSubmission) {
|
||||
const answers = await db.query.homeworkAnswers.findMany({
|
||||
where: eq(homeworkAnswers.submissionId, latestSubmission.id),
|
||||
})
|
||||
for (const ans of answers) {
|
||||
answersByQuestionId.set(ans.questionId, {
|
||||
answer: ans.answerContent,
|
||||
score: ans.score,
|
||||
feedback: ans.feedback,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// P0-竞品修复:获取考试模式配置(仅当作业关联考试时)
|
||||
let examModeConfig: StudentHomeworkTakeData["examModeConfig"] = null
|
||||
if (assignment.sourceExamId) {
|
||||
const examConfig = await getExamForProctoringCrossModule(assignment.sourceExamId)
|
||||
if (examConfig) {
|
||||
examModeConfig = {
|
||||
examMode: (examConfig.examMode === "timed" || examConfig.examMode === "proctored" || examConfig.examMode === "homework")
|
||||
? examConfig.examMode
|
||||
: "homework",
|
||||
durationMinutes: examConfig.durationMinutes,
|
||||
shuffleQuestions: examConfig.shuffleQuestions ?? false,
|
||||
allowLateStart: examConfig.allowLateStart ?? false,
|
||||
lateStartGraceMinutes: examConfig.lateStartGraceMinutes ?? 0,
|
||||
antiCheatEnabled: examConfig.antiCheatEnabled ?? false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
assignment: {
|
||||
id: assignment.id,
|
||||
title: assignment.title,
|
||||
description: assignment.description,
|
||||
availableAt: assignment.availableAt ? assignment.availableAt.toISOString() : null,
|
||||
dueAt: assignment.dueAt ? assignment.dueAt.toISOString() : null,
|
||||
allowLate: assignment.allowLate,
|
||||
lateDueAt: assignment.lateDueAt ? assignment.lateDueAt.toISOString() : null,
|
||||
maxAttempts: assignment.maxAttempts,
|
||||
},
|
||||
examModeConfig,
|
||||
submission: latestSubmission
|
||||
? {
|
||||
id: latestSubmission.id,
|
||||
status: toHomeworkSubmissionStatus(latestSubmission.status),
|
||||
attemptNo: latestSubmission.attemptNo,
|
||||
submittedAt: latestSubmission.submittedAt ? latestSubmission.submittedAt.toISOString() : null,
|
||||
score: latestSubmission.score ?? null,
|
||||
startedAt: latestSubmission.createdAt ? latestSubmission.createdAt.toISOString() : null,
|
||||
}
|
||||
: null,
|
||||
questions: assignmentQuestions.map((aq) => {
|
||||
const saved = answersByQuestionId.get(aq.questionId)
|
||||
// Use optional chaining or fallback to empty array if knowledgePoints is not loaded/undefined
|
||||
const kps = aq.question.knowledgePoints ?? []
|
||||
return {
|
||||
questionId: aq.questionId,
|
||||
questionType: aq.question.type,
|
||||
questionContent: toQuestionContent(aq.question.content),
|
||||
maxScore: aq.score ?? 0,
|
||||
order: aq.order ?? 0,
|
||||
savedAnswer: saved?.answer ?? null,
|
||||
score: saved?.score ?? null,
|
||||
feedback: saved?.feedback ?? null,
|
||||
knowledgePoints: kps.map((kp) => ({
|
||||
id: kp.knowledgePoint.id,
|
||||
name: kp.knowledgePoint.name,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
}
|
||||
return unsubmitted
|
||||
})
|
||||
|
||||
// Re-export stats functions for backward compatibility
|
||||
// New code should import directly from "./stats-service"
|
||||
export {
|
||||
getTeacherGradeTrends,
|
||||
getHomeworkAssignmentAnalytics,
|
||||
getStudentDashboardGrades,
|
||||
getHomeworkDashboardStats,
|
||||
} from "./stats-service"
|
||||
export type { HomeworkDashboardStats } from "./stats-service"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user