feat(exam-homework): add audit report, i18n, error boundaries, and permission hardening

- Add comprehensive audit report for exam and homework module

- Create exam-homework i18n message files (zh-CN + en) and register namespace

- Add permission check to gradeHomeworkSubmissionAction to prevent horizontal privilege escalation

- Add Error Boundary + loading.tsx for 5 key pages (exam build/proctoring, homework assignment/submissions, student assignment)

- Refactor exam-columns to createExamColumns(t) factory for i18n support

- Refactor exam-data-table to manage columns internally via useTranslations

- Replace hardcoded strings with i18n keys in all exam/homework components and pages

- Add getHomeworkSubmissionForGrading data-access for secure grading flow
This commit is contained in:
SpecialX
2026-06-22 16:08:39 +08:00
parent fde711ce46
commit 21c7e65fee
26 changed files with 2059 additions and 463 deletions

View File

@@ -2,6 +2,7 @@
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { MoreHorizontal, Eye, Pencil, Trash, Archive, UploadCloud, Undo2, Copy } from "lucide-react"
import { toast } from "sonner"
@@ -43,6 +44,7 @@ interface ExamActionsProps {
export function ExamActions({ exam }: ExamActionsProps) {
const router = useRouter()
const t = useTranslations("examHomework")
const [showViewDialog, setShowViewDialog] = useState(false)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [isWorking, setIsWorking] = useState(false)
@@ -76,11 +78,11 @@ export function ExamActions({ exam }: ExamActionsProps) {
const nodes = Array.isArray(structure) ? hydrate(structure) : []
setPreviewNodes(nodes)
} else {
toast.error("Failed to load exam preview")
toast.error(t("exam.actions.previewFailed"))
setShowViewDialog(false)
}
} catch {
toast.error("Failed to load exam preview")
toast.error(t("exam.actions.previewFailed"))
setShowViewDialog(false)
} finally {
setLoadingPreview(false)
@@ -89,7 +91,7 @@ export function ExamActions({ exam }: ExamActionsProps) {
const copyId = () => {
navigator.clipboard.writeText(exam.id)
toast.success("Exam ID copied to clipboard")
toast.success(t("exam.actions.idCopied"))
}
const setStatus = async (status: Exam["status"]) => {
@@ -100,13 +102,13 @@ export function ExamActions({ exam }: ExamActionsProps) {
formData.set("status", status)
const result = await updateExamAction(null, formData)
if (result.success) {
toast.success(status === "published" ? "Exam published" : status === "archived" ? "Exam archived" : "Exam moved to draft")
toast.success(status === "published" ? t("exam.actions.publishSuccess") : status === "archived" ? t("exam.actions.archiveSuccess") : t("exam.actions.draftSuccess"))
router.refresh()
} else {
toast.error(result.message || "Failed to update exam")
toast.error(result.message || t("exam.actions.updateFailed"))
}
} catch {
toast.error("Failed to update exam")
toast.error(t("exam.actions.updateFailed"))
} finally {
setIsWorking(false)
}
@@ -119,14 +121,14 @@ export function ExamActions({ exam }: ExamActionsProps) {
formData.set("examId", exam.id)
const result = await duplicateExamAction(null, formData)
if (result.success && result.data) {
toast.success("Exam duplicated")
toast.success(t("exam.actions.duplicateSuccess"))
router.push(`/teacher/exams/${result.data}/build`)
router.refresh()
} else {
toast.error(result.message || "Failed to duplicate exam")
toast.error(result.message || t("exam.actions.duplicateFailed"))
}
} catch {
toast.error("Failed to duplicate exam")
toast.error(t("exam.actions.duplicateFailed"))
} finally {
setIsWorking(false)
}
@@ -139,14 +141,14 @@ export function ExamActions({ exam }: ExamActionsProps) {
formData.set("examId", exam.id)
const result = await deleteExamAction(null, formData)
if (result.success) {
toast.success("Exam deleted successfully")
toast.success(t("exam.actions.deleteSuccess"))
setShowDeleteDialog(false)
router.refresh()
} else {
toast.error(result.message || "Failed to delete exam")
toast.error(result.message || t("exam.actions.deleteFailed"))
}
} catch {
toast.error("Failed to delete exam")
toast.error(t("exam.actions.deleteFailed"))
} finally {
setIsWorking(false)
}
@@ -163,75 +165,74 @@ export function ExamActions({ exam }: ExamActionsProps) {
e.stopPropagation()
handleView()
}}
title="Preview Exam"
aria-label="Preview exam"
title={t("exam.actions.preview")}
aria-label={t("exam.actions.preview")}
>
<Eye className="h-4 w-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0" aria-label="Open menu">
<span className="sr-only">Open menu</span>
<Button variant="ghost" className="h-8 w-8 p-0" aria-label={t("exam.actions.openMenu")}>
<span className="sr-only">{t("exam.actions.openMenu")}</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuLabel>{t("exam.actions.copyId")}</DropdownMenuLabel>
<DropdownMenuItem onClick={copyId}>
<Copy className="mr-2 h-4 w-4" /> Copy ID
<Copy className="mr-2 h-4 w-4" /> {t("exam.actions.copyId")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push(`/teacher/exams/${exam.id}/build`)}>
<Pencil className="mr-2 h-4 w-4" /> Edit
<Pencil className="mr-2 h-4 w-4" /> {t("exam.actions.edit")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push(`/teacher/exams/${exam.id}/build`)}>
<MoreHorizontal className="mr-2 h-4 w-4" /> Build
<MoreHorizontal className="mr-2 h-4 w-4" /> {t("exam.actions.build")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={duplicateExam} disabled={isWorking}>
<Copy className="mr-2 h-4 w-4" /> Duplicate
<Copy className="mr-2 h-4 w-4" /> {t("exam.actions.duplicate")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setStatus("published")}
disabled={isWorking || exam.status === "published"}
>
<UploadCloud className="mr-2 h-4 w-4" /> Publish
<UploadCloud className="mr-2 h-4 w-4" /> {t("exam.actions.publish")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatus("draft")}
disabled={isWorking || exam.status === "draft"}
>
<Undo2 className="mr-2 h-4 w-4" /> Move to Draft
<Undo2 className="mr-2 h-4 w-4" /> {t("exam.actions.moveToDraft")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setStatus("archived")}
disabled={isWorking || exam.status === "archived"}
>
<Archive className="mr-2 h-4 w-4" /> Archive
<Archive className="mr-2 h-4 w-4" /> {t("exam.actions.archive")}
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => setShowDeleteDialog(true)}
disabled={isWorking}
>
<Trash className="mr-2 h-4 w-4" /> Delete
<Trash className="mr-2 h-4 w-4" /> {t("exam.actions.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogTitle>{t("exam.actions.deleteConfirmTitle")}</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete the exam
&quot;{exam.title}&quot; and remove all associated data.
{t("exam.actions.deleteConfirmDescription", { title: exam.title })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogCancel>{t("exam.actions.cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={(e) => {
@@ -240,7 +241,7 @@ export function ExamActions({ exam }: ExamActionsProps) {
}}
disabled={isWorking}
>
Delete
{t("exam.actions.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -253,10 +254,10 @@ export function ExamActions({ exam }: ExamActionsProps) {
</div>
<ScrollArea className="flex-1">
{loadingPreview ? (
<div className="py-20 text-center text-muted-foreground">Loading preview...</div>
<div className="py-20 text-center text-muted-foreground">{t("exam.actions.loadingPreview")}</div>
) : previewNodes && previewNodes.length > 0 ? (
<div className="max-w-3xl mx-auto py-8 px-6">
<ExamPaperPreview
<ExamPaperPreview
title={exam.title}
subject={exam.subject}
grade={exam.grade}
@@ -267,7 +268,7 @@ export function ExamActions({ exam }: ExamActionsProps) {
</div>
) : (
<div className="py-20 text-center text-muted-foreground">
No questions in this exam.
{t("exam.actions.noQuestions")}
</div>
)}
</ScrollArea>

View File

@@ -7,152 +7,154 @@ import { cn, formatDate } from "@/shared/lib/utils"
import { Exam } from "../types"
import { ExamActions } from "./exam-actions"
export const examColumns: ColumnDef<Exam>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
size: 36,
},
{
accessorKey: "title",
header: "Exam Info",
cell: ({ row }) => (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<span className="font-semibold text-base">{row.original.title}</span>
{row.original.tags && row.original.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{row.original.tags.slice(0, 2).map((t, idx) => (
<Badge key={`${t}-${idx}`} variant="secondary" className="h-5 px-1.5 text-[10px]">
{t}
</Badge>
))}
{row.original.tags.length > 2 && (
<Badge variant="secondary" className="h-5 px-1.5 text-[10px]">+{row.original.tags.length - 2}</Badge>
)}
</div>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium text-foreground/80">{row.original.subject}</span>
<span></span>
<span>{row.original.grade}</span>
</div>
</div>
),
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => {
const status = row.original.status
// Use 'default' as base for published/success to ensure type safety,
// but override with className below
const variant: BadgeProps["variant"] =
status === "published"
? "default"
: status === "archived"
? "secondary"
: "outline"
return (
<Badge
variant={variant}
className={cn(
"capitalize",
status === "published" && "bg-green-600 hover:bg-green-700 border-transparent",
status === "draft" && "bg-amber-100 text-amber-800 hover:bg-amber-200 border-amber-200 dark:bg-amber-900/30 dark:text-amber-400 dark:border-amber-800"
)}
>
{status}
</Badge>
)
type TranslationFn = (key: string, params?: Record<string, unknown>) => string
export function createExamColumns(t: TranslationFn): ColumnDef<Exam>[] {
return [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label={t("exam.actions.selectAll")}
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label={t("exam.actions.selectRow")}
/>
),
enableSorting: false,
enableHiding: false,
size: 36,
},
},
{
id: "stats",
header: "Stats",
cell: ({ row }) => (
<div className="flex flex-col gap-1 text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<span className="font-medium text-foreground">{row.original.questionCount} Qs</span>
<span></span>
<span>{row.original.totalScore} Pts</span>
</div>
<div className="flex items-center gap-1">
<span>{row.original.durationMin} min</span>
</div>
</div>
),
},
{
accessorKey: "difficulty",
header: "Difficulty",
cell: ({ row }) => {
const diff = row.original.difficulty
return (
{
accessorKey: "title",
header: t("exam.columns.examInfo"),
cell: ({ row }) => (
<div className="flex flex-col gap-1">
<div className="flex gap-0.5">
{[1, 2, 3, 4, 5].map((level) => (
<div
key={level}
className={cn(
"h-1.5 w-3 rounded-full",
level <= diff
? diff <= 2 ? "bg-green-500" : diff === 3 ? "bg-yellow-500" : "bg-red-500"
: "bg-muted"
<div className="flex items-center gap-2">
<span className="font-semibold text-base">{row.original.title}</span>
{row.original.tags && row.original.tags.length > 0 && (
<div className="flex flex-wrap gap-1">
{row.original.tags.slice(0, 2).map((tag, idx) => (
<Badge key={`${tag}-${idx}`} variant="secondary" className="h-5 px-1.5 text-[10px]">
{tag}
</Badge>
))}
{row.original.tags.length > 2 && (
<Badge variant="secondary" className="h-5 px-1.5 text-[10px]">+{row.original.tags.length - 2}</Badge>
)}
/>
))}
</div>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium text-foreground/80">{row.original.subject}</span>
<span></span>
<span>{row.original.grade}</span>
</div>
<span className="text-[10px] text-muted-foreground font-medium">
{diff === 1 ? "Easy" : diff === 2 ? "Easy-Med" : diff === 3 ? "Medium" : diff === 4 ? "Med-Hard" : "Hard"}
</span>
</div>
)
),
},
},
{
id: "dates",
header: "Date",
cell: ({ row }) => {
const scheduled = row.original.scheduledAt
const created = row.original.createdAt
return (
<div className="flex flex-col gap-0.5 text-xs">
{scheduled ? (
<>
<span className="font-medium text-blue-600 dark:text-blue-400">Scheduled</span>
<span className="text-muted-foreground">{formatDate(scheduled)}</span>
</>
) : (
<>
<span className="text-muted-foreground">Created</span>
<span>{formatDate(created)}</span>
</>
)}
{
accessorKey: "status",
header: t("exam.columns.status"),
cell: ({ row }) => {
const status = row.original.status
const variant: BadgeProps["variant"] =
status === "published"
? "default"
: status === "archived"
? "secondary"
: "outline"
return (
<Badge
variant={variant}
className={cn(
"capitalize",
status === "published" && "bg-green-600 hover:bg-green-700 border-transparent",
status === "draft" && "bg-amber-100 text-amber-800 hover:bg-amber-200 border-amber-200 dark:bg-amber-900/30 dark:text-amber-400 dark:border-amber-800"
)}
>
{t(`exam.status.${status}`)}
</Badge>
)
},
},
{
id: "stats",
header: t("exam.columns.stats"),
cell: ({ row }) => (
<div className="flex flex-col gap-1 text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<span className="font-medium text-foreground">{row.original.questionCount} {t("exam.columns.questions")}</span>
<span></span>
<span>{row.original.totalScore} {t("exam.columns.points")}</span>
</div>
<div className="flex items-center gap-1">
<span>{row.original.durationMin} min</span>
</div>
</div>
)
),
},
},
{
id: "actions",
cell: ({ row }) => <ExamActions exam={row.original} />,
},
]
{
accessorKey: "difficulty",
header: t("exam.columns.difficulty"),
cell: ({ row }) => {
const diff = row.original.difficulty
return (
<div className="flex flex-col gap-1">
<div className="flex gap-0.5">
{[1, 2, 3, 4, 5].map((level) => (
<div
key={level}
className={cn(
"h-1.5 w-3 rounded-full",
level <= diff
? diff <= 2 ? "bg-green-500" : diff === 3 ? "bg-yellow-500" : "bg-red-500"
: "bg-muted"
)}
/>
))}
</div>
<span className="text-[10px] text-muted-foreground font-medium">
{t(`exam.difficulty.${diff}`)}
</span>
</div>
)
},
},
{
id: "dates",
header: t("exam.columns.date"),
cell: ({ row }) => {
const scheduled = row.original.scheduledAt
const created = row.original.createdAt
return (
<div className="flex flex-col gap-0.5 text-xs">
{scheduled ? (
<>
<span className="font-medium text-blue-600 dark:text-blue-400">{t("exam.columns.scheduled")}</span>
<span className="text-muted-foreground">{formatDate(scheduled)}</span>
</>
) : (
<>
<span className="text-muted-foreground">{t("exam.columns.created")}</span>
<span>{formatDate(created)}</span>
</>
)}
</div>
)
},
},
{
id: "actions",
cell: ({ row }) => <ExamActions exam={row.original} />,
},
]
}

View File

@@ -2,7 +2,6 @@
import * as React from "react"
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
@@ -12,6 +11,7 @@ import {
getFilteredRowModel,
RowSelectionState,
} from "@tanstack/react-table"
import { useTranslations } from "next-intl"
import {
Table,
@@ -23,16 +23,23 @@ import {
} from "@/shared/components/ui/table"
import { Button } from "@/shared/components/ui/button"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { Exam } from "../types"
import { createExamColumns } from "./exam-columns"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
interface DataTableProps {
data: Exam[]
}
export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<TData, TValue>) {
export function ExamDataTable({ data }: DataTableProps) {
const t = useTranslations("examHomework")
const [sorting, setSorting] = React.useState<SortingState>([])
const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({})
const columns = React.useMemo(
() => createExamColumns((key, params) => t(key, params as Record<string, string | number | Date> | undefined)),
[t]
)
const table = useReactTable({
data,
columns,
@@ -81,7 +88,7 @@ export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<T
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
{t("common.noResults")}
</TableCell>
</TableRow>
)}
@@ -90,14 +97,13 @@ export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<T
</div>
<div className="flex items-center justify-between px-2 py-4">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of {table.getFilteredRowModel().rows.length} row(s)
selected.
{table.getFilteredSelectedRowModel().rows.length} {t("common.of")} {table.getFilteredRowModel().rows.length} {t("common.rows")} {t("common.selected")}.
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Page</p>
<p className="text-sm font-medium">{t("common.page")}</p>
<span className="text-sm font-medium">
{table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
{table.getState().pagination.pageIndex + 1} {t("common.of")} {table.getPageCount()}
</span>
</div>
<div className="flex items-center space-x-2">
@@ -107,7 +113,7 @@ export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<T
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<span className="sr-only">{t("common.page")}</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
@@ -116,7 +122,7 @@ export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<T
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<span className="sr-only">{t("common.page")}</span>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
@@ -125,4 +131,3 @@ export function ExamDataTable<TData, TValue>({ columns, data }: DataTableProps<T
</div>
)
}