Files
NextEdu/src/modules/elective/data-access.ts
SpecialX 978d9a8309
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
feat: 新增备课模块并修复全模块 P0/P1/P2 缺陷
主要变更:

- 新增 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)
2026-06-22 01:06:16 +08:00

251 lines
9.0 KiB
TypeScript

import "server-only"
import { cache } from "react"
import { createId } from "@paralleldrive/cuid2"
import { and, desc, eq, inArray, sql, type SQL } from "drizzle-orm"
import { db } from "@/shared/db"
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,
GetElectiveCoursesParams,
} from "./types"
import type {
CreateElectiveCourseInput,
UpdateElectiveCourseInput,
} from "./schema"
const toIso = (d: Date | null | undefined): string | null =>
d ? d.toISOString() : null
const toIsoRequired = (d: Date): string => d.toISOString()
const buildScopeFilter = (scope: DataScope, userId?: string): SQL | null => {
if (scope.type === "all") return null
if (scope.type === "owned" && userId) return eq(electiveCourses.teacherId, userId)
if (scope.type === "class_taught" && userId) {
return eq(electiveCourses.teacherId, userId)
}
if (scope.type === "grade_managed") {
return scope.gradeIds.length > 0
? inArray(electiveCourses.gradeId, scope.gradeIds)
: sql`1=0`
}
if (scope.type === "class_members") return null
if (scope.type === "children") return null
return sql`1=0`
}
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,
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,
})
export const buildCourseSelect = () =>
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)
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 (
params?: GetElectiveCoursesParams & { scope?: DataScope; currentUserId?: string }
): Promise<ElectiveCourseWithDetails[]> => {
try {
const conditions: SQL[] = []
if (params?.status)
conditions.push(
eq(electiveCourses.status, params.status)
)
if (params?.gradeId) conditions.push(eq(electiveCourses.gradeId, params.gradeId))
if (params?.subjectId)
conditions.push(eq(electiveCourses.subjectId, params.subjectId))
if (params?.teacherId)
conditions.push(eq(electiveCourses.teacherId, params.teacherId))
if (params?.scope) {
const scopeFilter = buildScopeFilter(params.scope, params.currentUserId)
if (scopeFilter) conditions.push(scopeFilter)
}
const query = buildCourseSelect()
const rows = await (conditions.length > 0
? query.where(and(...conditions))
: query
).orderBy(desc(electiveCourses.createdAt))
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 []
}
}
)
export const getElectiveCourseById = cache(
async (id: string): Promise<ElectiveCourseWithDetails | null> => {
try {
const [row] = await buildCourseSelect()
.where(eq(electiveCourses.id, id))
.limit(1)
if (!row) return null
const displayMaps = await resolveCourseDisplayNames([row])
return mapCourseRow(row, displayMaps.teacherNames, displayMaps.subjectNames, displayMaps.gradeNames)
} catch (error) {
console.error("getElectiveCourseById failed:", error)
return null
}
}
)
export async function createElectiveCourse(
data: CreateElectiveCourseInput,
teacherId: string
): Promise<string> {
const id = createId()
await db.insert(electiveCourses).values({
id,
name: data.name,
subjectId: data.subjectId,
teacherId: data.teacherId ?? teacherId,
gradeId: data.gradeId,
description: data.description,
capacity: data.capacity,
enrolledCount: 0,
classroom: data.classroom,
schedule: data.schedule,
startDate: data.startDate ? new Date(data.startDate) : null,
endDate: data.endDate ? new Date(data.endDate) : null,
selectionStartAt: data.selectionStartAt ? new Date(data.selectionStartAt) : null,
selectionEndAt: data.selectionEndAt ? new Date(data.selectionEndAt) : null,
status: "draft",
selectionMode: data.selectionMode,
credit: data.credit,
})
return id
}
export async function updateElectiveCourse(
id: string,
data: Partial<UpdateElectiveCourseInput>
): Promise<void> {
const update: Partial<typeof electiveCourses.$inferSelect> = {}
if (data.name !== undefined) update.name = data.name
if (data.subjectId !== undefined) update.subjectId = data.subjectId
if (data.teacherId !== undefined) update.teacherId = data.teacherId
if (data.gradeId !== undefined) update.gradeId = data.gradeId
if (data.description !== undefined) update.description = data.description
if (data.capacity !== undefined) update.capacity = data.capacity
if (data.classroom !== undefined) update.classroom = data.classroom
if (data.schedule !== undefined) update.schedule = data.schedule
if (data.startDate !== undefined)
update.startDate = data.startDate ? new Date(data.startDate) : null
if (data.endDate !== undefined)
update.endDate = data.endDate ? new Date(data.endDate) : null
if (data.selectionStartAt !== undefined)
update.selectionStartAt = data.selectionStartAt ? new Date(data.selectionStartAt) : null
if (data.selectionEndAt !== undefined)
update.selectionEndAt = data.selectionEndAt ? new Date(data.selectionEndAt) : null
if (data.status !== undefined) update.status = data.status
if (data.selectionMode !== undefined) update.selectionMode = data.selectionMode
if (data.credit !== undefined) update.credit = data.credit
if (Object.keys(update).length === 0) return
await db.update(electiveCourses).set(update).where(eq(electiveCourses.id, id))
}
export async function deleteElectiveCourse(id: string): Promise<void> {
await db.delete(electiveCourses).where(eq(electiveCourses.id, id))
}
export async function openSelection(courseId: string): Promise<void> {
await db
.update(electiveCourses)
.set({ status: "open", updatedAt: new Date() })
.where(eq(electiveCourses.id, courseId))
}
export async function closeSelection(courseId: string): Promise<void> {
await db
.update(electiveCourses)
.set({ status: "closed", updatedAt: new Date() })
.where(eq(electiveCourses.id, courseId))
}
export type { ElectiveCourseWithDetails }