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

@@ -1,10 +1,12 @@
import "server-only"
import { cache } from "react"
import { count, desc, eq, gt, inArray } from "drizzle-orm"
import { and, count, desc, eq, gt, inArray } from "drizzle-orm"
import { auth } from "@/auth"
import { db } from "@/shared/db"
import { roles, sessions, users, usersToRoles } from "@/shared/db/schema"
import { resolvePrimaryRole } from "@/shared/lib/role-utils"
export type UserProfile = {
id: string
@@ -21,25 +23,6 @@ export type UserProfile = {
updatedAt: Date
}
const rolePriority = ["admin", "teacher", "parent", "student"] as const
const normalizeRoleName = (value: string) => {
const role = value.trim().toLowerCase()
if (role === "grade_head" || role === "teaching_head") return "teacher"
if (role === "admin" || role === "teacher" || role === "parent" || role === "student") return role
return ""
}
const resolvePrimaryRole = (roleNames: string[]) => {
const mapped = roleNames.map(normalizeRoleName).filter(Boolean)
if (mapped.length) {
for (const role of rolePriority) {
if (mapped.includes(role)) return role
}
}
return "student"
}
export const getUserProfile = cache(async (userId: string): Promise<UserProfile | null> => {
const user = await db.query.users.findFirst({
where: eq(users.id, userId),
@@ -70,6 +53,45 @@ export const getUserProfile = cache(async (userId: string): Promise<UserProfile
}
})
/** Input for updating a user's profile (self-service) */
export type UpdateUserProfileInput = {
name?: string
phone?: string
address?: string
gender?: string
age?: number
}
/**
* Update a user's profile by id (self-service fields only).
* Returns the updated user profile or null if the user was not found.
*/
export async function updateUserProfileById(
userId: string,
data: UpdateUserProfileInput
): Promise<UserProfile | null> {
const updateData: Partial<typeof users.$inferInsert> = {}
if (data.name !== undefined) updateData.name = data.name
// Convert empty strings to null for cleaner DB
if (data.phone !== undefined) updateData.phone = data.phone || null
if (data.address !== undefined) updateData.address = data.address || null
if (data.gender !== undefined) updateData.gender = data.gender || null
if (data.age !== undefined) updateData.age = data.age
if (Object.keys(updateData).length === 0) {
return await getUserProfile(userId)
}
await db
.update(users)
.set(updateData)
.where(eq(users.id, userId))
// Invalidate cache by re-querying (cache is per-request anyway)
return await getUserProfile(userId)
}
export type UsersDashboardStats = {
userCount: number
activeSessionsCount: number
@@ -150,3 +172,135 @@ export const getUsersDashboardStats = cache(async (): Promise<UsersDashboardStat
recentUsers,
}
})
// ---------------------------------------------------------------------------
// Cross-module query interfaces — read-only access for other modules
// ---------------------------------------------------------------------------
export type UserNameOption = {
id: string
name: string | null
email: string
}
export type TeacherOption = {
id: string
name: string | null
email: string
}
/** Returns the user row if the user has the specified role, otherwise null. */
export const getUserWithRole = cache(
async (userId: string, roleName: string): Promise<{ id: string; name: string | null; email: string } | null> => {
const id = userId.trim()
if (!id) return null
const [row] = await db
.select({ id: users.id, name: users.name, email: users.email })
.from(users)
.innerJoin(usersToRoles, eq(usersToRoles.userId, users.id))
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
.where(and(eq(users.id, id), eq(roles.name, roleName)))
.limit(1)
return row ?? null
}
)
/**
* Returns the current authenticated student user (id + name) by reading the
* session and verifying the "student" role via JOIN users + usersToRoles + roles.
* Returns null if not authenticated or the user does not have the student role.
*/
export const getCurrentStudentUser = cache(async (): Promise<{ id: string; name: string } | null> => {
const session = await auth()
const userId = String(session?.user?.id ?? "").trim()
if (!userId) return null
const student = await getUserWithRole(userId, "student")
if (!student) return null
return { id: student.id, name: student.name || "Student" }
})
/** Returns a map of userId -> { name, email } for the given user ids. */
export const getUserNamesByIds = cache(
async (ids: string[]): Promise<Map<string, UserNameOption>> => {
const uniqueIds = Array.from(new Set(ids.filter((v): v is string => typeof v === "string" && v.length > 0)))
const result = new Map<string, UserNameOption>()
if (uniqueIds.length === 0) return result
const rows = await db
.select({ id: users.id, name: users.name, email: users.email })
.from(users)
.where(inArray(users.id, uniqueIds))
for (const r of rows) {
result.set(r.id, { id: r.id, name: r.name, email: r.email })
}
return result
}
)
/** Returns teachers (users with the "teacher" role) for the given user ids. */
export const getTeachersByIds = cache(
async (teacherIds: string[]): Promise<TeacherOption[]> => {
const uniqueIds = Array.from(new Set(teacherIds.filter((v): v is string => typeof v === "string" && v.length > 0)))
if (uniqueIds.length === 0) return []
const rows = await db
.select({ id: users.id, name: users.name, email: users.email })
.from(users)
.innerJoin(usersToRoles, eq(usersToRoles.userId, users.id))
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
.where(and(eq(roles.name, "teacher"), inArray(users.id, uniqueIds)))
.groupBy(users.id, users.name, users.email)
return rows.map((r) => ({ id: r.id, name: r.name, email: r.email }))
}
)
export type UserBasicInfo = {
id: string
name: string | null
email: string
image: string | null
gradeId: string | null
}
/** Returns basic user info (id, name, email, image, gradeId) for a single user. */
export const getUserBasicInfo = cache(
async (userId: string): Promise<UserBasicInfo | null> => {
const id = userId.trim()
if (!id) return null
const [row] = await db
.select({
id: users.id,
name: users.name,
email: users.email,
image: users.image,
gradeId: users.gradeId,
})
.from(users)
.where(eq(users.id, id))
.limit(1)
return row ?? null
}
)
/** Returns user IDs for all users with the given gradeId. */
export const getUserIdsByGradeId = cache(
async (gradeId: string): Promise<string[]> => {
const id = gradeId.trim()
if (!id) return []
const rows = await db
.select({ id: users.id })
.from(users)
.where(eq(users.gradeId, id))
return rows.map((r) => r.id)
}
)