feat: 新增备课模块并修复全模块 P0/P1/P2 缺陷
Some checks failed
Security / deep-security-scan (push) Failing after 20m5s
DR Drill / dr-drill (push) Failing after 1m31s
CI / scheduled-backup (push) Failing after 1m31s
CI / backup-verify (push) Has been skipped
CI / weekly-dr-drill (push) Failing after 0s
CI / build-deploy (push) Has been cancelled
CI / security-scan (push) Has been cancelled

主要变更:

- 新增 lesson-preparation 模块: 备课编辑器、节点编辑、AI 建议、知识点选择、版本历史、作业发布

- 新增 shared 通用组件: charts/question-bank-filters/schedule-list/ui (chip-nav/filter-bar/page-header/stat-card/stat-item)

- 新增 student/admin 端 loading.tsx 与 error.tsx, 优化加载与错误态体验

- 新增 teacher/lesson-plans 页面 (列表/新建/编辑)

- 新增 drizzle 迁移 0002_tiny_lionheart 及 snapshot

- 新增 textbooks/schema.ts 与 exams/utils/normalize-structure.ts

- 修复 Tiptap v3 SSR hydration 崩溃 (rich-text-block immediatelyRender: false)

- 重构多模块 data-access/actions/组件, 修复权限校验与类型规范

- 同步架构文档 004/005 反映新增模块、导出、依赖关系

- 归档 bugs/* 测试报告与 e2e 测试脚本 (admin/parent/student/teacher web_test)
This commit is contained in:
SpecialX
2026-06-22 01:06:16 +08:00
parent d8962aba96
commit 978d9a8309
327 changed files with 34070 additions and 5642 deletions

View File

@@ -28,12 +28,12 @@ import {
export function ElectiveCourseList({
courses,
createHref,
editHrefBuilder,
editBaseHref,
canManage,
}: {
courses: ElectiveCourseWithDetails[]
createHref?: string
editHrefBuilder?: (id: string) => string
editBaseHref?: string
canManage?: boolean
}) {
const router = useRouter()
@@ -165,13 +165,13 @@ export function ElectiveCourseList({
{manageResolved ? (
<div className="mt-auto flex flex-wrap gap-2 pt-2">
{editHrefBuilder ? (
{editBaseHref ? (
<Button
asChild
variant="outline"
size="sm"
>
<a href={editHrefBuilder(course.id)}>
<a href={`${editBaseHref}/${course.id}/edit`}>
<Pencil className="mr-1 h-3 w-3" />
Edit
</a>

View File

@@ -46,7 +46,12 @@ export async function runLottery(courseId: string): Promise<{
return { enrolled: 0, waitlist: 0 }
}
const shuffled = [...selections].sort(() => Math.random() - 0.5)
// Fisher-Yates shuffle: 无偏均匀随机排列,避免 sort(() => Math.random() - 0.5) 的分布偏差
const shuffled = [...selections]
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
}
const capacity = course.capacity
const now = new Date()
@@ -99,13 +104,26 @@ export async function selectCourse(
studentId: string,
priority?: number
): Promise<{ status: CourseSelectionStatus; message: string }> {
const [courseRows, existingRows] = await Promise.all([
db
return db.transaction(async (tx) => {
// 锁定课程行,防止 FCFS 模式下并发超卖
const [course] = await tx
.select()
.from(electiveCourses)
.where(eq(electiveCourses.id, courseId))
.limit(1),
db
.for("update")
.limit(1)
if (!course) throw new Error("Course not found")
if (course.status !== "open") throw new Error("Course selection is not open")
const now = new Date()
if (course.selectionStartAt && now < course.selectionStartAt) {
throw new Error("Selection has not started yet")
}
if (course.selectionEndAt && now > course.selectionEndAt) {
throw new Error("Selection has ended")
}
const [existing] = await tx
.select()
.from(courseSelections)
.where(
@@ -115,68 +133,55 @@ export async function selectCourse(
inArray(courseSelections.status, ["selected", "enrolled", "waitlist"])
)
)
.limit(1),
])
const course = courseRows[0]
if (!course) throw new Error("Course not found")
if (course.status !== "open") throw new Error("Course selection is not open")
.limit(1)
if (existing) throw new Error("Already selected this course")
const now = new Date()
if (course.selectionStartAt && now < course.selectionStartAt) {
throw new Error("Selection has not started yet")
}
if (course.selectionEndAt && now > course.selectionEndAt) {
throw new Error("Selection has ended")
}
const id = createId()
let status: CourseSelectionStatus = "selected"
let enrolledAt: Date | null = null
const existing = existingRows[0]
if (existing) throw new Error("Already selected this course")
if (course.selectionMode === "fcfs" && course.enrolledCount < course.capacity) {
status = "enrolled"
enrolledAt = now
await tx
.update(electiveCourses)
.set({
enrolledCount: course.enrolledCount + 1,
updatedAt: now,
})
.where(eq(electiveCourses.id, courseId))
} else if (course.selectionMode === "fcfs") {
status = "waitlist"
}
const id = createId()
let status: CourseSelectionStatus = "selected"
let enrolledAt: Date | null = null
await tx.insert(courseSelections).values({
id,
courseId,
studentId,
status,
priority: priority ?? 1,
selectedAt: now,
enrolledAt,
})
if (course.selectionMode === "fcfs" && course.enrolledCount < course.capacity) {
status = "enrolled"
enrolledAt = now
await db
.update(electiveCourses)
.set({
enrolledCount: course.enrolledCount + 1,
updatedAt: now,
})
.where(eq(electiveCourses.id, courseId))
} else if (course.selectionMode === "fcfs") {
status = "waitlist"
}
await db.insert(courseSelections).values({
id,
courseId,
studentId,
status,
priority: priority ?? 1,
selectedAt: now,
enrolledAt,
return {
status,
message:
status === "enrolled"
? "Enrolled successfully"
: status === "waitlist"
? "Added to waitlist"
: "Selection submitted",
}
})
return {
status,
message:
status === "enrolled"
? "Enrolled successfully"
: status === "waitlist"
? "Added to waitlist"
: "Selection submitted",
}
}
export async function dropCourse(
courseId: string,
studentId: string
): Promise<void> {
const [existingRows, courseRows] = await Promise.all([
db
await db.transaction(async (tx) => {
const [existing] = await tx
.select()
.from(courseSelections)
.where(
@@ -186,32 +191,31 @@ export async function dropCourse(
inArray(courseSelections.status, ["selected", "enrolled", "waitlist"])
)
)
.limit(1),
db
.limit(1)
if (!existing) throw new Error("No active selection found")
// 锁定课程行,确保 enrolledCount 更新与候补递补的原子性
const [course] = await tx
.select()
.from(electiveCourses)
.where(eq(electiveCourses.id, courseId))
.limit(1),
])
const existing = existingRows[0]
if (!existing) throw new Error("No active selection found")
.for("update")
.limit(1)
const course = courseRows[0]
const now = new Date()
await db
.update(courseSelections)
.set({ status: "dropped", droppedAt: now, updatedAt: now })
.where(eq(courseSelections.id, existing.id))
const now = new Date()
await tx
.update(courseSelections)
.set({ status: "dropped", droppedAt: now, updatedAt: now })
.where(eq(courseSelections.id, existing.id))
if (existing.status === "enrolled") {
if (course && course.selectionMode === "fcfs") {
if (existing.status === "enrolled" && course && course.selectionMode === "fcfs") {
const newEnrolledCount = Math.max(0, course.enrolledCount - 1)
await db
await tx
.update(electiveCourses)
.set({ enrolledCount: newEnrolledCount, updatedAt: now })
.where(eq(electiveCourses.id, courseId))
const [nextWait] = await db
const [nextWait] = await tx
.select()
.from(courseSelections)
.where(
@@ -223,7 +227,7 @@ export async function dropCourse(
.orderBy(asc(courseSelections.priority), asc(courseSelections.selectedAt))
.limit(1)
if (nextWait) {
await db
await tx
.update(courseSelections)
.set({
status: "enrolled",
@@ -231,11 +235,11 @@ export async function dropCourse(
updatedAt: now,
})
.where(eq(courseSelections.id, nextWait.id))
await db
await tx
.update(electiveCourses)
.set({ enrolledCount: newEnrolledCount + 1, updatedAt: now })
.where(eq(electiveCourses.id, courseId))
}
}
}
})
}

View File

@@ -10,16 +10,19 @@ import {
} from "@/shared/db/schema"
import { getStudentActiveGradeId } from "@/modules/classes/data-access"
import { getGradeOptions, getSubjectOptions } from "@/modules/school/data-access"
import { getUserNamesByIds } from "@/modules/users/data-access"
import {
buildCourseSelect,
mapCourseRow,
resolveCourseDisplayNames,
type CourseCoreRow,
} from "./data-access"
import type {
CourseSelectionWithDetails,
ElectiveCourseWithDetails,
} from "./types"
type CourseCoreRow = typeof electiveCourses.$inferSelect
type SelectionCoreRow = {
id: string
courseId: string
@@ -43,36 +46,6 @@ const toIso = (d: Date | null | undefined): string | null =>
const toIsoRequired = (d: Date): string => d.toISOString()
const mapCourseRow = (
r: CourseCoreRow,
teacherNames: Map<string, string | null>,
subjectNames: Map<string, string>,
gradeNames: Map<string, string>
): ElectiveCourseWithDetails => ({
id: r.id,
name: r.name,
subjectId: r.subjectId,
teacherId: r.teacherId,
gradeId: r.gradeId,
description: r.description,
capacity: r.capacity,
enrolledCount: r.enrolledCount,
classroom: r.classroom,
schedule: r.schedule,
startDate: r.startDate ? new Date(r.startDate).toISOString().slice(0, 10) : null,
endDate: r.endDate ? new Date(r.endDate).toISOString().slice(0, 10) : null,
selectionStartAt: toIso(r.selectionStartAt),
selectionEndAt: toIso(r.selectionEndAt),
status: r.status,
selectionMode: r.selectionMode,
credit: String(r.credit),
createdAt: toIsoRequired(r.createdAt),
updatedAt: toIsoRequired(r.updatedAt),
teacherName: r.teacherId ? (teacherNames.get(r.teacherId) ?? null) : null,
subjectName: r.subjectId ? (subjectNames.get(r.subjectId) ?? null) : null,
gradeName: r.gradeId ? (gradeNames.get(r.gradeId) ?? null) : null,
})
const mapSelectionRow = (
r: SelectionCoreRow,
studentNames: Map<string, string | null>
@@ -95,31 +68,6 @@ const mapSelectionRow = (
courseStatus: r.courseStatus,
})
const buildCourseCoreSelect = () =>
db
.select({
id: electiveCourses.id,
name: electiveCourses.name,
subjectId: electiveCourses.subjectId,
teacherId: electiveCourses.teacherId,
gradeId: electiveCourses.gradeId,
description: electiveCourses.description,
capacity: electiveCourses.capacity,
enrolledCount: electiveCourses.enrolledCount,
classroom: electiveCourses.classroom,
schedule: electiveCourses.schedule,
startDate: electiveCourses.startDate,
endDate: electiveCourses.endDate,
selectionStartAt: electiveCourses.selectionStartAt,
selectionEndAt: electiveCourses.selectionEndAt,
status: electiveCourses.status,
selectionMode: electiveCourses.selectionMode,
credit: electiveCourses.credit,
createdAt: electiveCourses.createdAt,
updatedAt: electiveCourses.updatedAt,
})
.from(electiveCourses)
const buildSelectionCoreSelect = () =>
db
.select({
@@ -142,30 +90,6 @@ const buildSelectionCoreSelect = () =>
.from(courseSelections)
.leftJoin(electiveCourses, eq(electiveCourses.id, courseSelections.courseId))
const resolveCourseDisplayNames = async (rows: CourseCoreRow[]): Promise<{
teacherNames: Map<string, string | null>
subjectNames: Map<string, string>
gradeNames: Map<string, string>
}> => {
const teacherIds = Array.from(new Set(rows.map((r) => r.teacherId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const [userMap, subjects, grades] = await Promise.all([
getUserNamesByIds(teacherIds),
getSubjectOptions(),
getGradeOptions(),
])
const teacherNames = new Map<string, string | null>()
for (const [id, user] of userMap.entries()) {
teacherNames.set(id, user.name)
}
const subjectNames = new Map<string, string>()
for (const s of subjects) subjectNames.set(s.id, s.name)
const gradeNames = new Map<string, string>()
for (const g of grades) gradeNames.set(g.id, g.name)
return { teacherNames, subjectNames, gradeNames }
}
const resolveStudentDisplayNames = async (rows: SelectionCoreRow[]): Promise<Map<string, string | null>> => {
const studentIds = Array.from(new Set(rows.map((r) => r.studentId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const userMap = await getUserNamesByIds(studentIds)
@@ -216,7 +140,7 @@ export const getAvailableCoursesForStudent = cache(
sql`(${electiveCourses.gradeId} = ${resolvedGradeId} OR ${electiveCourses.gradeId} IS NULL)`
)
}
const rows = await buildCourseCoreSelect()
const rows: CourseCoreRow[] = await buildCourseSelect()
.where(and(...conditions))
.orderBy(desc(electiveCourses.createdAt))
const displayMaps = await resolveCourseDisplayNames(rows)

View File

@@ -2,16 +2,13 @@ import "server-only"
import { cache } from "react"
import { createId } from "@paralleldrive/cuid2"
import { and, asc, desc, eq, inArray, sql, type SQL } from "drizzle-orm"
import { and, desc, eq, inArray, sql, type SQL } from "drizzle-orm"
import { db } from "@/shared/db"
import {
electiveCourses,
grades,
subjects,
users,
} from "@/shared/db/schema"
import { electiveCourses } from "@/shared/db/schema"
import type { DataScope } from "@/shared/types/permissions"
import { getGradeOptions, getSubjectOptions } from "@/modules/school/data-access"
import { getUserNamesByIds } from "@/modules/users/data-access"
import type {
ElectiveCourseWithDetails,
@@ -43,12 +40,13 @@ const buildScopeFilter = (scope: DataScope, userId?: string): SQL | null => {
return sql`1=0`
}
const mapCourseRow = (
r: typeof electiveCourses.$inferSelect & {
teacherName: string | null
subjectName: string | null
gradeName: string | null
}
export type CourseCoreRow = typeof electiveCourses.$inferSelect
export const mapCourseRow = (
r: CourseCoreRow,
teacherNames: Map<string, string | null>,
subjectNames: Map<string, string>,
gradeNames: Map<string, string>
): ElectiveCourseWithDetails => ({
id: r.id,
name: r.name,
@@ -69,12 +67,12 @@ const mapCourseRow = (
credit: String(r.credit),
createdAt: toIsoRequired(r.createdAt),
updatedAt: toIsoRequired(r.updatedAt),
teacherName: r.teacherName,
subjectName: r.subjectName,
gradeName: r.gradeName,
teacherName: r.teacherId ? (teacherNames.get(r.teacherId) ?? null) : null,
subjectName: r.subjectId ? (subjectNames.get(r.subjectId) ?? null) : null,
gradeName: r.gradeId ? (gradeNames.get(r.gradeId) ?? null) : null,
})
const buildCourseSelect = () =>
export const buildCourseSelect = () =>
db
.select({
id: electiveCourses.id,
@@ -96,14 +94,32 @@ const buildCourseSelect = () =>
credit: electiveCourses.credit,
createdAt: electiveCourses.createdAt,
updatedAt: electiveCourses.updatedAt,
teacherName: users.name,
subjectName: subjects.name,
gradeName: grades.name,
})
.from(electiveCourses)
.leftJoin(users, eq(users.id, electiveCourses.teacherId))
.leftJoin(subjects, eq(subjects.id, electiveCourses.subjectId))
.leftJoin(grades, eq(grades.id, electiveCourses.gradeId))
export const resolveCourseDisplayNames = async (rows: CourseCoreRow[]): Promise<{
teacherNames: Map<string, string | null>
subjectNames: Map<string, string>
gradeNames: Map<string, string>
}> => {
const teacherIds = Array.from(new Set(rows.map((r) => r.teacherId).filter((v): v is string => typeof v === "string" && v.length > 0)))
const [userMap, subjects, grades] = await Promise.all([
getUserNamesByIds(teacherIds),
getSubjectOptions(),
getGradeOptions(),
])
const teacherNames = new Map<string, string | null>()
for (const [id, user] of userMap.entries()) {
teacherNames.set(id, user.name)
}
const subjectNames = new Map<string, string>()
for (const s of subjects) subjectNames.set(s.id, s.name)
const gradeNames = new Map<string, string>()
for (const g of grades) gradeNames.set(g.id, g.name)
return { teacherNames, subjectNames, gradeNames }
}
export const getElectiveCourses = cache(
async (
@@ -131,7 +147,9 @@ export const getElectiveCourses = cache(
: query
).orderBy(desc(electiveCourses.createdAt))
return rows.map(mapCourseRow)
if (rows.length === 0) return []
const displayMaps = await resolveCourseDisplayNames(rows)
return rows.map((r) => mapCourseRow(r, displayMaps.teacherNames, displayMaps.subjectNames, displayMaps.gradeNames))
} catch (error) {
console.error("getElectiveCourses failed:", error)
return []
@@ -146,7 +164,8 @@ export const getElectiveCourseById = cache(
.where(eq(electiveCourses.id, id))
.limit(1)
if (!row) return null
return mapCourseRow(row)
const displayMaps = await resolveCourseDisplayNames([row])
return mapCourseRow(row, displayMaps.teacherNames, displayMaps.subjectNames, displayMaps.gradeNames)
} catch (error) {
console.error("getElectiveCourseById failed:", error)
return null
@@ -228,17 +247,4 @@ export async function closeSelection(courseId: string): Promise<void> {
.where(eq(electiveCourses.id, courseId))
}
export async function getSubjectOptions(): Promise<{ id: string; name: string }[]> {
try {
const rows = await db
.select({ id: subjects.id, name: subjects.name })
.from(subjects)
.orderBy(asc(subjects.order), asc(subjects.name))
return rows.map((r) => ({ id: r.id, name: r.name }))
} catch (error) {
console.error("getSubjectOptions failed:", error)
return []
}
}
export type { ElectiveCourseWithDetails }