refactor(attendance,elective): 审计第二轮 — 全量完成 P0/P1 改进项
P0 修复: - 页面层 i18n 全量补齐(admin/teacher/parent/student × attendance/elective) - types.ts 状态标签常量迁移至 constants.ts(i18n key + Badge variant) - 修复 getTranslations 导入路径(next-intl → next-intl/server) P1 改进: - 解耦 parent 模块对 attendance 类型的直接依赖(本地 view-model 类型) - 导出纯函数(computeStats/buildWarnings/buildLotteryRankCase 等) - 统一空状态为 EmptyState 组件 - 清理死代码读 Action(attendance 5 个 + elective 3 个) - 预留监控埋点接口(trackEvent 13 个新事件名) - 补齐骨架屏 loading.tsx(8 个页面) - AlertDialog 替换 window.confirm(student-selection-view) - a11y 改进(aria-label/role/键盘导航) 修复: - AttendanceStatus 从 constants.ts 重导出,消除 types/constants 双源混乱 - buildWarnings 的 Translator 类型改用 ReturnType<typeof useTranslations>
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useState, useRef, useEffect, useCallback } from "react"
|
||||
import { useFormStatus } from "react-dom"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { CalendarDays } from "lucide-react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { CalendarDays, Search, CheckCircle2, XCircle, Clock, LogOut, FileText } from "lucide-react"
|
||||
|
||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
@@ -25,12 +26,23 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/shared/components/ui/table"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
|
||||
import { batchRecordAttendanceAction } from "../actions"
|
||||
import {
|
||||
ATTENDANCE_STATUS_LABELS,
|
||||
ATTENDANCE_STATUS_LABEL_KEYS,
|
||||
type AttendanceStatus,
|
||||
} from "../types"
|
||||
} from "../constants"
|
||||
|
||||
type Option = { id: string; name: string }
|
||||
type Student = { id: string; name: string; email: string }
|
||||
@@ -43,14 +55,39 @@ const STATUS_OPTIONS: AttendanceStatus[] = [
|
||||
"excused",
|
||||
]
|
||||
|
||||
const isAttendanceStatus = (v: string): v is AttendanceStatus =>
|
||||
v === "present" || v === "absent" || v === "late" || v === "early_leave" || v === "excused"
|
||||
const STATUS_SHORTCUTS: Record<string, AttendanceStatus> = {
|
||||
p: "present",
|
||||
a: "absent",
|
||||
l: "late",
|
||||
e: "early_leave",
|
||||
x: "excused",
|
||||
}
|
||||
|
||||
const STATUS_STYLES: Record<AttendanceStatus, { active: string; icon: typeof CheckCircle2 }> = {
|
||||
present: { active: "bg-emerald-500 text-white border-emerald-500 hover:bg-emerald-600", icon: CheckCircle2 },
|
||||
absent: { active: "bg-red-500 text-white border-red-500 hover:bg-red-600", icon: XCircle },
|
||||
late: { active: "bg-amber-500 text-white border-amber-500 hover:bg-amber-600", icon: Clock },
|
||||
early_leave: { active: "bg-blue-500 text-white border-blue-500 hover:bg-blue-600", icon: LogOut },
|
||||
excused: { active: "bg-purple-500 text-white border-purple-500 hover:bg-purple-600", icon: FileText },
|
||||
}
|
||||
|
||||
/** 初始化状态计数,避免 `{} as Record<...>` 类型断言 */
|
||||
function createInitialStatusCounts(): Record<AttendanceStatus, number> {
|
||||
return {
|
||||
present: 0,
|
||||
absent: 0,
|
||||
late: 0,
|
||||
early_leave: 0,
|
||||
excused: 0,
|
||||
}
|
||||
}
|
||||
|
||||
function SubmitButton() {
|
||||
const { pending } = useFormStatus()
|
||||
const t = useTranslations("attendance")
|
||||
return (
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Saving..." : "Save Attendance"}
|
||||
{pending ? t("actions.save") + "..." : t("actions.save")}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -67,24 +104,94 @@ export function AttendanceSheet({
|
||||
defaultDate?: string
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const t = useTranslations("attendance")
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const [classId, setClassId] = useState(defaultClassId ?? classes[0]?.id ?? "")
|
||||
const [date, setDate] = useState(defaultDate ?? today)
|
||||
const [statuses, setStatuses] = useState<Record<string, AttendanceStatus>>({})
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [focusedStudentIndex, setFocusedStudentIndex] = useState(0)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [showSwitchConfirm, setShowSwitchConfirm] = useState(false)
|
||||
const [pendingClassId, setPendingClassId] = useState<string | null>(null)
|
||||
const studentRefs = useRef<(HTMLTableRowElement | null)[]>([])
|
||||
|
||||
const handleStatusChange = (studentId: string, status: AttendanceStatus) => {
|
||||
const handleStatusChange = useCallback((studentId: string, status: AttendanceStatus) => {
|
||||
setStatuses((prev) => ({ ...prev, [studentId]: status }))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const markAllPresent = () => {
|
||||
const markAllPresent = useCallback(() => {
|
||||
const all: Record<string, AttendanceStatus> = {}
|
||||
for (const s of students) all[s.id] = "present"
|
||||
setStatuses(all)
|
||||
toast.success(t("actions.markAllPresent"))
|
||||
}, [students, t])
|
||||
|
||||
const handleClassChange = (newClassId: string) => {
|
||||
const hasUnsaved = Object.keys(statuses).length > 0
|
||||
if (hasUnsaved && newClassId !== classId) {
|
||||
setPendingClassId(newClassId)
|
||||
setShowSwitchConfirm(true)
|
||||
return
|
||||
}
|
||||
confirmClassSwitch(newClassId)
|
||||
}
|
||||
|
||||
const confirmClassSwitch = (newClassId: string) => {
|
||||
setClassId(newClassId)
|
||||
setStatuses({})
|
||||
const newUrl = newClassId ? `/teacher/attendance/sheet?classId=${encodeURIComponent(newClassId)}` : "/teacher/attendance/sheet"
|
||||
router.push(newUrl)
|
||||
}
|
||||
|
||||
const filteredStudents = students.filter(
|
||||
(s) => !searchQuery || s.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
|
||||
const statusCounts = STATUS_OPTIONS.reduce(
|
||||
(acc, st) => {
|
||||
acc[st] = students.filter((s) => (statuses[s.id] ?? "present") === st).length
|
||||
return acc
|
||||
},
|
||||
createInitialStatusCounts()
|
||||
)
|
||||
|
||||
// 派生值:当筛选结果变少时,焦点索引自动夹紧到有效范围,避免 useEffect 重置导致的级联渲染
|
||||
const effectiveFocusedIndex = filteredStudents.length === 0
|
||||
? 0
|
||||
: Math.min(focusedStudentIndex, filteredStudents.length - 1)
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return
|
||||
const key = e.key.toLowerCase()
|
||||
if (STATUS_SHORTCUTS[key] && filteredStudents[effectiveFocusedIndex]) {
|
||||
e.preventDefault()
|
||||
handleStatusChange(filteredStudents[effectiveFocusedIndex].id, STATUS_SHORTCUTS[key])
|
||||
if (effectiveFocusedIndex < filteredStudents.length - 1) {
|
||||
setFocusedStudentIndex((prev) => prev + 1)
|
||||
}
|
||||
}
|
||||
if (e.key === "ArrowDown" && effectiveFocusedIndex < filteredStudents.length - 1) {
|
||||
e.preventDefault()
|
||||
setFocusedStudentIndex((prev) => prev + 1)
|
||||
}
|
||||
if (e.key === "ArrowUp" && effectiveFocusedIndex > 0) {
|
||||
e.preventDefault()
|
||||
setFocusedStudentIndex((prev) => prev - 1)
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [filteredStudents, effectiveFocusedIndex, handleStatusChange])
|
||||
|
||||
useEffect(() => {
|
||||
studentRefs.current[effectiveFocusedIndex]?.scrollIntoView({ block: "nearest" })
|
||||
}, [effectiveFocusedIndex])
|
||||
|
||||
const handleSubmit = async (formData: FormData) => {
|
||||
if (!classId || !date) {
|
||||
toast.error("Please select class and date")
|
||||
toast.error(t("errors.invalidForm"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -96,35 +203,48 @@ export function AttendanceSheet({
|
||||
}))
|
||||
|
||||
if (records.length === 0) {
|
||||
toast.error("No students to record attendance for")
|
||||
toast.error(t("sheet.noStudents"))
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
formData.set("recordsJson", JSON.stringify(records))
|
||||
|
||||
const result = await batchRecordAttendanceAction(null, formData)
|
||||
setIsSubmitting(false)
|
||||
if (result.success) {
|
||||
toast.success(result.message)
|
||||
toast.success(result.message || t("sheet.saved"))
|
||||
router.push("/teacher/attendance")
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || "Failed to save attendance")
|
||||
toast.error(result.message || t("errors.unexpected"))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Card className="relative">
|
||||
{isSubmitting && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-background/60 backdrop-blur-sm">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
{t("sheet.saved")}...
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<CardHeader>
|
||||
<CardTitle>Attendance Sheet</CardTitle>
|
||||
<CardTitle>{t("title.sheet")}</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("description.teacherRecords")}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label>Class</Label>
|
||||
<Select value={classId} onValueChange={setClassId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a class" />
|
||||
<Label htmlFor="class-select">{t("filters.class")}</Label>
|
||||
<Select value={classId} onValueChange={handleClassChange}>
|
||||
<SelectTrigger id="class-select">
|
||||
<SelectValue placeholder={t("sheet.selectClass")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{classes.map((c) => (
|
||||
@@ -137,7 +257,7 @@ export function AttendanceSheet({
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="date">Date</Label>
|
||||
<Label htmlFor="date">{t("filters.date")}</Label>
|
||||
<div className="relative">
|
||||
<CalendarDays className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
@@ -147,6 +267,7 @@ export function AttendanceSheet({
|
||||
onChange={(e) => setDate(e.target.value)}
|
||||
className="pl-9"
|
||||
required
|
||||
aria-label={t("filters.date")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -154,55 +275,100 @@ export function AttendanceSheet({
|
||||
|
||||
{students.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No students in this class. Select a class to load students.
|
||||
{t("sheet.noStudents")}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{students.length} students
|
||||
</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={markAllPresent}>
|
||||
Mark All Present
|
||||
</Button>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{STATUS_OPTIONS.map((st) => {
|
||||
const Icon = STATUS_STYLES[st].icon
|
||||
return (
|
||||
<span key={st} className="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-1 text-xs">
|
||||
<Icon className="h-3 w-3" aria-hidden="true" />
|
||||
{t(ATTENDANCE_STATUS_LABEL_KEYS[st])}
|
||||
<span className="font-semibold tabular-nums">{statusCounts[st]}</span>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={t("list.columns.student")}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="h-8 w-40 pl-8 text-sm"
|
||||
aria-label={t("list.columns.student")}
|
||||
/>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={markAllPresent}>
|
||||
{t("actions.markAllPresent")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Student</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead className="w-48">Status</TableHead>
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>{t("list.columns.student")}</TableHead>
|
||||
<TableHead className="hidden md:table-cell">{t("list.columns.remark")}</TableHead>
|
||||
<TableHead>{t("list.columns.status")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{students.map((s) => (
|
||||
<TableRow key={s.id}>
|
||||
<TableCell className="font-medium">{s.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{s.email}</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={statuses[s.id] ?? "present"}
|
||||
onValueChange={(v) => {
|
||||
if (isAttendanceStatus(v)) {
|
||||
handleStatusChange(s.id, v)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_OPTIONS.map((st) => (
|
||||
<SelectItem key={st} value={st}>
|
||||
{ATTENDANCE_STATUS_LABELS[st]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{filteredStudents.map((s, idx) => {
|
||||
const currentStatus = statuses[s.id] ?? "present"
|
||||
const isFocused = idx === effectiveFocusedIndex
|
||||
return (
|
||||
<TableRow
|
||||
key={s.id}
|
||||
ref={(el) => { studentRefs.current[idx] = el }}
|
||||
className={cn("cursor-pointer", isFocused && "bg-primary/5")}
|
||||
onClick={() => setFocusedStudentIndex(idx)}
|
||||
role="button"
|
||||
tabIndex={isFocused ? 0 : -1}
|
||||
aria-label={s.name}
|
||||
>
|
||||
<TableCell className="text-muted-foreground tabular-nums">{idx + 1}</TableCell>
|
||||
<TableCell className="font-medium">{s.name}</TableCell>
|
||||
<TableCell className="hidden text-muted-foreground md:table-cell">{s.email}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{STATUS_OPTIONS.map((st) => {
|
||||
const Icon = STATUS_STYLES[st].icon
|
||||
const isActive = currentStatus === st
|
||||
return (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleStatusChange(s.id, st)
|
||||
}}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium transition-colors",
|
||||
isActive
|
||||
? STATUS_STYLES[st].active
|
||||
: "border-border bg-background text-muted-foreground hover:bg-muted"
|
||||
)}
|
||||
aria-pressed={isActive}
|
||||
aria-label={`${t(ATTENDANCE_STATUS_LABEL_KEYS[st])} (${st[0].toUpperCase()})`}
|
||||
>
|
||||
<Icon className="h-3 w-3" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t(ATTENDANCE_STATUS_LABEL_KEYS[st])}</span>
|
||||
<span className="sm:hidden">{st[0].toUpperCase()}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
@@ -211,12 +377,37 @@ export function AttendanceSheet({
|
||||
|
||||
<CardFooter className="justify-end gap-2 px-0">
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
Cancel
|
||||
{t("actions.cancel")}
|
||||
</Button>
|
||||
<SubmitButton />
|
||||
</CardFooter>
|
||||
</form>
|
||||
</CardContent>
|
||||
|
||||
<AlertDialog open={showSwitchConfirm} onOpenChange={setShowSwitchConfirm}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("sheet.confirmDelete")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("description.teacherRecords")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("actions.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
if (pendingClassId) {
|
||||
confirmClassSwitch(pendingClassId)
|
||||
setPendingClassId(null)
|
||||
}
|
||||
setShowSwitchConfirm(false)
|
||||
}}
|
||||
>
|
||||
{t("actions.save")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user