feat(attendance): add correlation, trend, warnings, report print, and services
- Add attendance-grade-correlation-card and data-access-correlation, correlation-compute - Add attendance-trend-chart and trend-compute for trend analysis - Add attendance-warnings-card and warning-compute for attendance warnings - Add attendance-report-print for printable reports - Add class-comparison-card for class attendance comparison - Add notifications and services directory
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from "react"
|
||||
import { useState, useRef, useEffect, useCallback, useMemo } from "react"
|
||||
import { useFormStatus } from "react-dom"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { CalendarDays, Search, CheckCircle2, XCircle, Clock, LogOut, FileText } from "lucide-react"
|
||||
import { CalendarDays, Search, CheckCircle2, XCircle, Clock, LogOut, FileText, School } from "lucide-react"
|
||||
|
||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
@@ -37,30 +37,37 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { resolveActionError } from "@/shared/lib/resolve-action-error"
|
||||
|
||||
import { batchRecordAttendanceAction } from "../actions"
|
||||
import {
|
||||
ATTENDANCE_STATUS_OPTIONS,
|
||||
ATTENDANCE_STATUS_SHORTCUTS,
|
||||
ATTENDANCE_STATUS_LABEL_KEYS,
|
||||
createInitialStatusCounts,
|
||||
type AttendanceStatus,
|
||||
} from "../constants"
|
||||
import type { AttendancePeriod } from "../types"
|
||||
|
||||
type Option = { id: string; name: string }
|
||||
type Student = { id: string; name: string; email: string }
|
||||
|
||||
const STATUS_OPTIONS: AttendanceStatus[] = [
|
||||
"present",
|
||||
"absent",
|
||||
"late",
|
||||
"early_leave",
|
||||
"excused",
|
||||
/** L-6:节次选项(顺序即选择器中的展示顺序)。 */
|
||||
const ATTENDANCE_PERIOD_OPTIONS: AttendancePeriod[] = [
|
||||
"full_day",
|
||||
"morning_reading",
|
||||
"morning",
|
||||
"afternoon",
|
||||
"evening",
|
||||
]
|
||||
|
||||
const STATUS_SHORTCUTS: Record<string, AttendanceStatus> = {
|
||||
p: "present",
|
||||
a: "absent",
|
||||
l: "late",
|
||||
e: "early_leave",
|
||||
x: "excused",
|
||||
/** L-6:节次对应的 i18n key 后缀。 */
|
||||
const ATTENDANCE_PERIOD_LABEL_KEYS: Record<AttendancePeriod, string> = {
|
||||
full_day: "period.full_day",
|
||||
morning_reading: "period.morning_reading",
|
||||
morning: "period.morning",
|
||||
afternoon: "period.afternoon",
|
||||
evening: "period.evening",
|
||||
}
|
||||
|
||||
const STATUS_STYLES: Record<AttendanceStatus, { active: string; icon: typeof CheckCircle2 }> = {
|
||||
@@ -69,18 +76,17 @@ const STATUS_STYLES: Record<AttendanceStatus, { active: string; icon: typeof Che
|
||||
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 },
|
||||
school_activity: { active: "bg-cyan-500 text-white border-cyan-500 hover:bg-cyan-600", icon: School },
|
||||
}
|
||||
|
||||
/** 初始化状态计数,避免 `{} as Record<...>` 类型断言 */
|
||||
function createInitialStatusCounts(): Record<AttendanceStatus, number> {
|
||||
return {
|
||||
present: 0,
|
||||
absent: 0,
|
||||
late: 0,
|
||||
early_leave: 0,
|
||||
excused: 0,
|
||||
}
|
||||
}
|
||||
/** 需要填写原因的状态(缺勤/迟到/早退/请假/校内活动)。 */
|
||||
const STATUSES_REQUIRING_REASON: ReadonlySet<AttendanceStatus> = new Set([
|
||||
"absent",
|
||||
"late",
|
||||
"early_leave",
|
||||
"excused",
|
||||
"school_activity",
|
||||
])
|
||||
|
||||
function SubmitButton() {
|
||||
const { pending } = useFormStatus()
|
||||
@@ -108,22 +114,40 @@ export function AttendanceSheet({
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const [classId, setClassId] = useState(defaultClassId ?? classes[0]?.id ?? "")
|
||||
const [date, setDate] = useState(defaultDate ?? today)
|
||||
// L-6:节次默认 full_day(向后兼容已有数据)
|
||||
const [period, setPeriod] = useState<AttendancePeriod>("full_day")
|
||||
const [statuses, setStatuses] = useState<Record<string, AttendanceStatus>>({})
|
||||
const [reasons, setReasons] = useState<Record<string, string>>({})
|
||||
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 containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleStatusChange = useCallback((studentId: string, status: AttendanceStatus) => {
|
||||
setStatuses((prev) => ({ ...prev, [studentId]: status }))
|
||||
// 切回 present 时清除原因(present 不需要原因)
|
||||
if (status === "present") {
|
||||
setReasons((prev) => {
|
||||
if (!prev[studentId]) return prev
|
||||
const next = { ...prev }
|
||||
delete next[studentId]
|
||||
return next
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleReasonChange = useCallback((studentId: string, reason: string) => {
|
||||
setReasons((prev) => ({ ...prev, [studentId]: reason }))
|
||||
}, [])
|
||||
|
||||
const markAllPresent = useCallback(() => {
|
||||
const all: Record<string, AttendanceStatus> = {}
|
||||
for (const s of students) all[s.id] = "present"
|
||||
setStatuses(all)
|
||||
setReasons({})
|
||||
toast.success(t("actions.markAllPresent"))
|
||||
}, [students, t])
|
||||
|
||||
@@ -140,6 +164,7 @@ export function AttendanceSheet({
|
||||
const confirmClassSwitch = (newClassId: string) => {
|
||||
setClassId(newClassId)
|
||||
setStatuses({})
|
||||
setReasons({})
|
||||
const newUrl = newClassId ? `/teacher/attendance/sheet?classId=${encodeURIComponent(newClassId)}` : "/teacher/attendance/sheet"
|
||||
router.push(newUrl)
|
||||
}
|
||||
@@ -148,12 +173,16 @@ export function AttendanceSheet({
|
||||
(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()
|
||||
const statusCounts = useMemo(
|
||||
() =>
|
||||
ATTENDANCE_STATUS_OPTIONS.reduce(
|
||||
(acc, st) => {
|
||||
acc[st] = students.filter((s) => (statuses[s.id] ?? "present") === st).length
|
||||
return acc
|
||||
},
|
||||
createInitialStatusCounts()
|
||||
),
|
||||
[students, statuses]
|
||||
)
|
||||
|
||||
// 派生值:当筛选结果变少时,焦点索引自动夹紧到有效范围,避免 useEffect 重置导致的级联渲染
|
||||
@@ -162,12 +191,23 @@ export function AttendanceSheet({
|
||||
: Math.min(focusedStudentIndex, filteredStudents.length - 1)
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return
|
||||
// P2-7 修复:限制监听范围到容器内,并排除所有可交互元素
|
||||
const target = e.target
|
||||
if (
|
||||
target instanceof HTMLInputElement ||
|
||||
target instanceof HTMLTextAreaElement ||
|
||||
target instanceof HTMLSelectElement ||
|
||||
(target instanceof HTMLElement && target.isContentEditable)
|
||||
) {
|
||||
return
|
||||
}
|
||||
const key = e.key.toLowerCase()
|
||||
if (STATUS_SHORTCUTS[key] && filteredStudents[effectiveFocusedIndex]) {
|
||||
if (ATTENDANCE_STATUS_SHORTCUTS[key] && filteredStudents[effectiveFocusedIndex]) {
|
||||
e.preventDefault()
|
||||
handleStatusChange(filteredStudents[effectiveFocusedIndex].id, STATUS_SHORTCUTS[key])
|
||||
handleStatusChange(filteredStudents[effectiveFocusedIndex].id, ATTENDANCE_STATUS_SHORTCUTS[key])
|
||||
if (effectiveFocusedIndex < filteredStudents.length - 1) {
|
||||
setFocusedStudentIndex((prev) => prev + 1)
|
||||
}
|
||||
@@ -181,8 +221,8 @@ export function AttendanceSheet({
|
||||
setFocusedStudentIndex((prev) => prev - 1)
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
container.addEventListener("keydown", handleKeyDown)
|
||||
return () => container.removeEventListener("keydown", handleKeyDown)
|
||||
}, [filteredStudents, effectiveFocusedIndex, handleStatusChange])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -195,12 +235,22 @@ export function AttendanceSheet({
|
||||
return
|
||||
}
|
||||
|
||||
const records = students.map((s) => ({
|
||||
studentId: s.id,
|
||||
classId,
|
||||
date,
|
||||
status: statuses[s.id] ?? "present",
|
||||
}))
|
||||
const records = students.map((s) => {
|
||||
const status = statuses[s.id] ?? "present"
|
||||
return {
|
||||
studentId: s.id,
|
||||
classId,
|
||||
date,
|
||||
status,
|
||||
// L-6:节次考勤,提交时携带当前选中的节次
|
||||
period,
|
||||
// 仅当状态需要原因且原因非空时携带(present 不需要原因)
|
||||
reason:
|
||||
STATUSES_REQUIRING_REASON.has(status) && reasons[s.id]
|
||||
? reasons[s.id].slice(0, 255)
|
||||
: undefined,
|
||||
}
|
||||
})
|
||||
|
||||
if (records.length === 0) {
|
||||
toast.error(t("sheet.noStudents"))
|
||||
@@ -217,7 +267,7 @@ export function AttendanceSheet({
|
||||
router.push("/teacher/attendance")
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(result.message || t("errors.unexpected"))
|
||||
toast.error(resolveActionError(result, t, t("errors.unexpected")))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t("errors.unexpected"))
|
||||
@@ -232,7 +282,7 @@ export function AttendanceSheet({
|
||||
<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")}...
|
||||
{t("sheet.saving")}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -244,7 +294,7 @@ export function AttendanceSheet({
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="class-select">{t("filters.class")}</Label>
|
||||
<Select value={classId} onValueChange={handleClassChange}>
|
||||
@@ -276,6 +326,23 @@ export function AttendanceSheet({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* L-6:节次选择器,允许按节次记录考勤 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="period-select">{t("period.label")}</Label>
|
||||
<Select value={period} onValueChange={(v) => setPeriod(v as AttendancePeriod)}>
|
||||
<SelectTrigger id="period-select">
|
||||
<SelectValue placeholder={t("period.label")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ATTENDANCE_PERIOD_OPTIONS.map((p) => (
|
||||
<SelectItem key={p} value={p}>
|
||||
{t(ATTENDANCE_PERIOD_LABEL_KEYS[p])}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{students.length === 0 ? (
|
||||
@@ -286,7 +353,7 @@ export function AttendanceSheet({
|
||||
<>
|
||||
<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) => {
|
||||
{ATTENDANCE_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">
|
||||
@@ -314,13 +381,13 @@ export function AttendanceSheet({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-md border">
|
||||
<div ref={containerRef} className="rounded-md border" tabIndex={-1}>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>{t("list.columns.student")}</TableHead>
|
||||
<TableHead className="hidden md:table-cell">{t("list.columns.remark")}</TableHead>
|
||||
<TableHead className="hidden md:table-cell">{t("list.columns.reason")}</TableHead>
|
||||
<TableHead>{t("list.columns.status")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -328,6 +395,7 @@ export function AttendanceSheet({
|
||||
{filteredStudents.map((s, idx) => {
|
||||
const currentStatus = statuses[s.id] ?? "present"
|
||||
const isFocused = idx === effectiveFocusedIndex
|
||||
const needsReason = STATUSES_REQUIRING_REASON.has(currentStatus)
|
||||
return (
|
||||
<TableRow
|
||||
key={s.id}
|
||||
@@ -339,11 +407,28 @@ export function AttendanceSheet({
|
||||
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 className="font-medium">
|
||||
<div className="flex flex-col">
|
||||
<span>{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground md:hidden">{s.email}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
<Input
|
||||
type="text"
|
||||
value={reasons[s.id] ?? ""}
|
||||
onChange={(e) => handleReasonChange(s.id, e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
disabled={!needsReason}
|
||||
placeholder={needsReason ? t("sheet.reasonPlaceholder") : ""}
|
||||
maxLength={255}
|
||||
className="h-8 text-sm"
|
||||
aria-label={t("list.columns.reason")}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{STATUS_OPTIONS.map((st) => {
|
||||
{ATTENDANCE_STATUS_OPTIONS.map((st) => {
|
||||
const Icon = STATUS_STYLES[st].icon
|
||||
const isActive = currentStatus === st
|
||||
return (
|
||||
@@ -392,9 +477,9 @@ export function AttendanceSheet({
|
||||
<AlertDialog open={showSwitchConfirm} onOpenChange={setShowSwitchConfirm}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("sheet.confirmDelete")}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("sheet.confirmClassSwitch")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("description.teacherRecords")}
|
||||
{t("sheet.confirmClassSwitch")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -408,7 +493,7 @@ export function AttendanceSheet({
|
||||
setShowSwitchConfirm(false)
|
||||
}}
|
||||
>
|
||||
{t("actions.save")}
|
||||
{t("sheet.confirmClassSwitchAction")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
Reference in New Issue
Block a user