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:
@@ -1,12 +1,16 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { PermissionDeniedError, requireAuth, requirePermission } from "@/shared/lib/auth-guard"
|
||||
import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard"
|
||||
import { Permissions } from "@/shared/types/permissions"
|
||||
import type { ActionState } from "@/shared/types/action-state"
|
||||
import { sendNotification } from "@/modules/notifications/dispatcher"
|
||||
|
||||
import { SendMessageSchema } from "./schema"
|
||||
import {
|
||||
SendMessageSchema,
|
||||
MessageIdSchema,
|
||||
UpdateNotificationPreferencesSchema,
|
||||
} from "./schema"
|
||||
import {
|
||||
getMessages,
|
||||
getMessageById,
|
||||
@@ -87,9 +91,15 @@ export async function sendMessageAction(
|
||||
export async function markMessageAsReadAction(messageId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
await markMessageAsRead(messageId, ctx.userId)
|
||||
|
||||
const parsed = MessageIdSchema.safeParse({ messageId })
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
|
||||
}
|
||||
|
||||
await markMessageAsRead(parsed.data.messageId, ctx.userId)
|
||||
revalidatePath("/messages")
|
||||
revalidatePath(`/messages/${messageId}`)
|
||||
revalidatePath(`/messages/${parsed.data.messageId}`)
|
||||
return { success: true, message: "Marked as read" }
|
||||
} catch (e) {
|
||||
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
|
||||
@@ -101,9 +111,15 @@ export async function markMessageAsReadAction(messageId: string): Promise<Action
|
||||
export async function deleteMessageAction(messageId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_DELETE)
|
||||
await deleteMessage(messageId, ctx.userId)
|
||||
|
||||
const parsed = MessageIdSchema.safeParse({ messageId })
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
|
||||
}
|
||||
|
||||
await deleteMessage(parsed.data.messageId, ctx.userId)
|
||||
revalidatePath("/messages")
|
||||
revalidatePath(`/messages/${messageId}`)
|
||||
revalidatePath(`/messages/${parsed.data.messageId}`)
|
||||
return { success: true, message: "Message deleted" }
|
||||
} catch (e) {
|
||||
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
|
||||
@@ -129,11 +145,18 @@ export async function getMessagesAction(
|
||||
export async function getMessageDetailAction(messageId: string): Promise<ActionState<Message>> {
|
||||
try {
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
const message = await getMessageById(messageId, ctx.userId)
|
||||
|
||||
const parsed = MessageIdSchema.safeParse({ messageId })
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
|
||||
}
|
||||
|
||||
const validMessageId = parsed.data.messageId
|
||||
const message = await getMessageById(validMessageId, ctx.userId)
|
||||
if (!message) return { success: false, message: "Message not found" }
|
||||
// Auto-mark as read when viewed by receiver
|
||||
if (!message.isRead && message.receiverId === ctx.userId) {
|
||||
await markMessageAsRead(messageId, ctx.userId)
|
||||
await markMessageAsRead(validMessageId, ctx.userId)
|
||||
revalidatePath("/messages")
|
||||
}
|
||||
return { success: true, data: message }
|
||||
@@ -160,7 +183,7 @@ export async function getNotificationsAction(
|
||||
params?: { page?: number; pageSize?: number; unreadOnly?: boolean }
|
||||
): Promise<ActionState<{ items: Notification[]; total: number; page: number; pageSize: number; totalPages: number }>> {
|
||||
try {
|
||||
const ctx = await requireAuth()
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
const result = await getNotifications(ctx.userId, params)
|
||||
return { success: true, data: result }
|
||||
} catch (e) {
|
||||
@@ -174,7 +197,7 @@ export async function markNotificationAsReadAction(
|
||||
notificationId: string
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requireAuth()
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
await markNotificationAsRead(notificationId, ctx.userId)
|
||||
revalidatePath("/messages")
|
||||
return { success: true, message: "Notification marked as read" }
|
||||
@@ -187,7 +210,7 @@ export async function markNotificationAsReadAction(
|
||||
|
||||
export async function markAllNotificationsAsReadAction(): Promise<ActionState<string>> {
|
||||
try {
|
||||
const ctx = await requireAuth()
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
await markAllNotificationsAsRead(ctx.userId)
|
||||
revalidatePath("/messages")
|
||||
return { success: true, message: "All notifications marked as read" }
|
||||
@@ -200,7 +223,7 @@ export async function markAllNotificationsAsReadAction(): Promise<ActionState<st
|
||||
|
||||
export async function getNotificationPreferencesAction(): Promise<ActionState<NotificationPreferences>> {
|
||||
try {
|
||||
const ctx = await requireAuth()
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
const prefs = await getNotificationPreferences(ctx.userId)
|
||||
return { success: true, data: prefs }
|
||||
} catch (e) {
|
||||
@@ -215,12 +238,12 @@ export async function updateNotificationPreferencesAction(
|
||||
formData: FormData
|
||||
): Promise<ActionState<NotificationPreferences>> {
|
||||
try {
|
||||
const ctx = await requireAuth()
|
||||
const ctx = await requirePermission(Permissions.MESSAGE_READ)
|
||||
|
||||
// 从 FormData 中解析布尔值(checkbox 提交 "on" 或不提交)
|
||||
const parseBool = (key: string): boolean => formData.get(key) === "on"
|
||||
|
||||
const input: UpdateNotificationPreferencesInput = {
|
||||
const parsed = UpdateNotificationPreferencesSchema.safeParse({
|
||||
emailEnabled: parseBool("emailEnabled"),
|
||||
smsEnabled: parseBool("smsEnabled"),
|
||||
pushEnabled: parseBool("pushEnabled"),
|
||||
@@ -229,8 +252,14 @@ export async function updateNotificationPreferencesAction(
|
||||
announcementNotifications: parseBool("announcementNotifications"),
|
||||
messageNotifications: parseBool("messageNotifications"),
|
||||
attendanceNotifications: parseBool("attendanceNotifications"),
|
||||
})
|
||||
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
|
||||
}
|
||||
|
||||
const input: UpdateNotificationPreferencesInput = parsed.data
|
||||
|
||||
const updated = await upsertNotificationPreferences(ctx.userId, input)
|
||||
if (!updated) {
|
||||
return { success: false, message: "Failed to update notification preferences" }
|
||||
|
||||
Reference in New Issue
Block a user