Files
NextEdu/src/modules/parent/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

227 lines
6.2 KiB
TypeScript

import "server-only"
import { cache } from "react"
import { and, asc, eq } from "drizzle-orm"
import { db } from "@/shared/db"
import { parentStudentRelations } from "@/shared/db/schema"
import {
getStudentActiveClass,
getStudentClasses,
getStudentSchedule,
} from "@/modules/classes/data-access"
import {
getStudentDashboardGrades,
getStudentHomeworkAssignments,
} from "@/modules/homework/data-access"
import { getStudentGradeSummary } from "@/modules/grades/data-access"
import { getGradeNameById } from "@/modules/school/data-access"
import { getUserBasicInfo, getUserNamesByIds } from "@/modules/users/data-access"
import type {
ChildBasicInfo,
ChildDashboardData,
ChildHomeworkSummaryData,
ChildScheduleItem,
ParentChildRelation,
ParentDashboardData,
} from "./types"
type Weekday = 1 | 2 | 3 | 4 | 5 | 6 | 7
const isWeekday = (n: number): n is Weekday => n >= 1 && n <= 7
const toWeekday = (d: Date): Weekday => {
const day = d.getDay()
// getDay() returns 0 (Sun) - 6 (Sat); normalize Sunday (0) to 7
const normalized = day === 0 ? 7 : day
return isWeekday(normalized) ? normalized : 1
}
export const getChildren = cache(async (parentId: string): Promise<ParentChildRelation[]> => {
const id = parentId.trim()
if (!id) return []
const rows = await db
.select({
id: parentStudentRelations.id,
parentId: parentStudentRelations.parentId,
studentId: parentStudentRelations.studentId,
relation: parentStudentRelations.relation,
createdAt: parentStudentRelations.createdAt,
})
.from(parentStudentRelations)
.where(eq(parentStudentRelations.parentId, id))
.orderBy(asc(parentStudentRelations.createdAt))
return rows.map((r) => ({
id: r.id,
parentId: r.parentId,
studentId: r.studentId,
relation: r.relation,
createdAt: r.createdAt.toISOString(),
}))
})
/**
* 校验家长与子女的关系是否存在,并返回关系类型。
* 同时按 parentId 与 studentId 过滤,防止跨家庭信息泄露。
*/
export const verifyParentChildRelation = cache(
async (studentId: string, parentId: string): Promise<string | null> => {
const [row] = await db
.select({ relation: parentStudentRelations.relation })
.from(parentStudentRelations)
.where(
and(
eq(parentStudentRelations.studentId, studentId),
eq(parentStudentRelations.parentId, parentId),
),
)
.limit(1)
return row?.relation ?? null
},
)
export const getChildBasicInfo = cache(
async (
studentId: string,
relation: string | null = null,
): Promise<ChildBasicInfo | null> => {
const student = await getUserBasicInfo(studentId)
if (!student) return null
// gradeName 与 activeClass 相互独立,并行拉取
const [gradeName, activeClass] = await Promise.all([
student.gradeId ? getGradeNameById(student.gradeId) : Promise.resolve(null),
getStudentActiveClass(studentId),
])
return {
id: student.id,
name: student.name,
email: student.email,
image: student.image,
gradeName,
className: activeClass?.className ?? null,
classId: activeClass?.classId ?? null,
relation,
}
},
)
const buildHomeworkSummary = (
assignments: Awaited<ReturnType<typeof getStudentHomeworkAssignments>>,
): ChildHomeworkSummaryData => {
const now = new Date()
let pendingCount = 0
let submittedCount = 0
let gradedCount = 0
let overdueCount = 0
for (const a of assignments) {
if (a.progressStatus === "graded") {
gradedCount += 1
continue
}
if (a.progressStatus === "submitted") {
submittedCount += 1
}
if (a.progressStatus === "not_started" || a.progressStatus === "in_progress") {
pendingCount += 1
}
if (a.dueAt) {
const due = new Date(a.dueAt)
if (due < now && a.progressStatus !== "submitted") {
overdueCount += 1
}
}
}
const recentAssignments = assignments
.toSorted((a, b) => {
const aDue = a.dueAt ? new Date(a.dueAt).getTime() : Number.POSITIVE_INFINITY
const bDue = b.dueAt ? new Date(b.dueAt).getTime() : Number.POSITIVE_INFINITY
return aDue - bDue
})
.slice(0, 5)
return {
pendingCount,
submittedCount,
gradedCount,
overdueCount,
recentAssignments,
}
}
const buildTodaySchedule = (
schedule: Awaited<ReturnType<typeof getStudentSchedule>>,
): ChildScheduleItem[] => {
const todayWeekday = toWeekday(new Date())
return schedule
.filter((s) => s.weekday === todayWeekday)
.map((s) => ({
id: s.id,
classId: s.classId,
className: s.className,
course: s.course,
startTime: s.startTime,
endTime: s.endTime,
location: s.location ?? null,
}))
.sort((a, b) => a.startTime.localeCompare(b.startTime))
}
export const getChildDashboardData = cache(
async (studentId: string, relation: string | null = null): Promise<ChildDashboardData | null> => {
const basicInfo = await getChildBasicInfo(studentId, relation)
if (!basicInfo) return null
const [enrolledClasses, schedule, assignments, gradeTrend, gradeSummary] = await Promise.all([
getStudentClasses(studentId),
getStudentSchedule(studentId),
getStudentHomeworkAssignments(studentId),
getStudentDashboardGrades(studentId),
getStudentGradeSummary(studentId),
])
return {
basicInfo,
enrolledClasses,
todaySchedule: buildTodaySchedule(schedule),
homeworkSummary: buildHomeworkSummary(assignments),
gradeTrend,
gradeSummary,
}
},
)
export const getParentDashboardData = cache(
async (parentId: string): Promise<ParentDashboardData> => {
const id = parentId.trim()
if (!id) return { parentName: null, children: [] }
const [parentInfo, relations] = await Promise.all([
getUserNamesByIds([id]),
getChildren(id),
])
const parentName = parentInfo.get(id)?.name ?? null
if (relations.length === 0) {
return { parentName, children: [] }
}
const children = await Promise.all(
relations.map((r) => getChildDashboardData(r.studentId, r.relation)),
)
return {
parentName,
children: children.filter((c): c is ChildDashboardData => c !== null),
}
},
)