refactor: fix all P0/P1/P2 bugs and architecture issues

Bug fixes (from bugs/ directory):

- Fix cross-module DB queries in 9 modules (homework, grades, parent, diagnostic, elective, proctoring, notifications, scheduling, classes) by routing through data-access functions

- Fix shared/lib <-> auth circular dependency via new session.ts module

- Fix divide-by-zero guard in grades data-access

- Fix audit export data truncation (paginated fetch for full datasets)

- Fix missing transactions in homework grading and elective lottery

- Fix missing revalidatePath in course-plans actions

- Fix frontend permission checks using requirePermission instead of requireAuth

- Fix dashboard role routing using session.user.roles

- Fix student auth pattern (migrate getDemoStudentUser to users module)

- Fix ActionState return type handling in components

Code quality fixes:

- Remove 60+ as type assertions (replace with type guards)

- Remove non-null assertions (use optional chaining or explicit checks)

- Convert dynamic imports to static imports (grades, diagnostic)

- Add React.cache() wrapping for read functions

- Parallelize independent queries with Promise.all

- Add explicit return types to 30+ arrow functions

- Replace any with unknown + type guards

- Fix import type for type-only imports

- Add Zod validation schemas for classes and diagnostic modules

- Extract duplicate code (normalizeRoleName, normalizeBcryptHash, logger IP extraction)

- Add console.error to silent catch blocks

- Fix permission naming consistency (exam:proctor_read -> exam:proctor:read)

Architecture doc sync:

- Update 004_architecture_impact_map.md and 005_architecture_data.json

- Update management-modules-audit.md for P0-7 cross-module fix

Moved deleted proctoring event route to deletes/ folder.
This commit is contained in:
SpecialX
2026-06-19 05:13:09 +08:00
parent 063baffe4c
commit 49291fcc31
114 changed files with 12548 additions and 3395 deletions

View File

@@ -4,7 +4,7 @@ import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guar
import { Permissions } from "@/shared/types/permissions";
import { CreateQuestionSchema } from "./schema";
import type { CreateQuestionInput } from "./schema";
import { ActionState } from "@/shared/types/action-state";
import type { ActionState } from "@/shared/types/action-state";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import {
@@ -17,6 +17,12 @@ import {
} from "./data-access";
import type { KnowledgePointOption } from "./types";
/** Result type of getQuestions (data + meta) */
type QuestionsListResult = Awaited<ReturnType<typeof getQuestions>>;
/** Result type of getKnowledgePointOptions */
type KnowledgePointOptionsResult = KnowledgePointOption[];
export async function createNestedQuestion(
prevState: ActionState<string> | undefined,
formData: FormData | CreateQuestionInput
@@ -151,26 +157,34 @@ export async function deleteQuestionAction(
}
}
export async function getQuestionsAction(params: GetQuestionsParams) {
export async function getQuestionsAction(
params: GetQuestionsParams
): Promise<ActionState<QuestionsListResult>> {
try {
await requirePermission(Permissions.QUESTION_READ);
return await getQuestions(params);
const data = await getQuestions(params);
return { success: true, data };
} catch (e) {
if (e instanceof PermissionDeniedError) {
throw e;
return { success: false, message: e.message };
}
throw e;
const message = e instanceof Error ? e.message : "Failed to fetch questions";
return { success: false, message };
}
}
export async function getKnowledgePointOptionsAction(): Promise<KnowledgePointOption[]> {
export async function getKnowledgePointOptionsAction(): Promise<
ActionState<KnowledgePointOptionsResult>
> {
try {
await requirePermission(Permissions.QUESTION_READ);
return await getKnowledgePointOptions();
const data = await getKnowledgePointOptions();
return { success: true, data };
} catch (e) {
if (e instanceof PermissionDeniedError) {
throw e;
return { success: false, message: e.message };
}
throw e;
const message = e instanceof Error ? e.message : "Failed to fetch knowledge point options";
return { success: false, message };
}
}

View File

@@ -160,8 +160,8 @@ export function CreateQuestionDialog({
if (!open) return
setIsLoadingKnowledgePoints(true)
getKnowledgePointOptionsAction()
.then((rows) => {
setKnowledgePointOptions(rows)
.then((result) => {
setKnowledgePointOptions(result.success && result.data ? result.data : [])
})
.catch(() => {
toast.error("Failed to load knowledge points")

View File

@@ -25,8 +25,8 @@ export function QuestionFilters() {
useEffect(() => {
getKnowledgePointOptionsAction()
.then((rows) => {
setKnowledgePointOptions(rows)
.then((result) => {
setKnowledgePointOptions(result.success && result.data ? result.data : [])
})
.catch(() => {
setKnowledgePointOptions([])

View File

@@ -297,3 +297,43 @@ export async function getKnowledgePointOptions(): Promise<KnowledgePointOption[]
grade: row.grade ?? null,
}));
}
// ---------------------------------------------------------------------------
// Cross-module query interfaces — read-only access for other modules
// ---------------------------------------------------------------------------
export type QuestionKnowledgePoint = {
questionId: string
knowledgePointId: string
knowledgePointName: string
}
/** Returns knowledge points associated with the given question ids. */
export const getKnowledgePointsForQuestions = cache(
async (questionIds: string[]): Promise<Map<string, QuestionKnowledgePoint[]>> => {
const result = new Map<string, QuestionKnowledgePoint[]>()
const uniqueIds = Array.from(new Set(questionIds.filter((v): v is string => typeof v === "string" && v.length > 0)))
if (uniqueIds.length === 0) return result
const rows = await db
.select({
questionId: questionsToKnowledgePoints.questionId,
knowledgePointId: knowledgePoints.id,
knowledgePointName: knowledgePoints.name,
})
.from(questionsToKnowledgePoints)
.innerJoin(knowledgePoints, eq(knowledgePoints.id, questionsToKnowledgePoints.knowledgePointId))
.where(inArray(questionsToKnowledgePoints.questionId, uniqueIds))
for (const r of rows) {
const list = result.get(r.questionId) ?? []
list.push({
questionId: r.questionId,
knowledgePointId: r.knowledgePointId,
knowledgePointName: r.knowledgePointName,
})
result.set(r.questionId, list)
}
return result
}
)

View File

@@ -3,7 +3,7 @@ import { z } from "zod"
export const QuestionTypeEnum = z.enum(["single_choice", "multiple_choice", "text", "judgment", "composite"])
export const BaseQuestionSchema = z.object({
content: z.any().describe("JSON content for the question (e.g. Slate nodes)"),
content: z.unknown().describe("JSON content for the question (e.g. Slate nodes)"),
type: QuestionTypeEnum,
difficulty: z.number().min(1).max(5).default(1),
knowledgePointIds: z.array(z.string()).optional(),