完整性更新
现在已经实现了大部分基础功能
This commit is contained in:
291
src/modules/school/actions.ts
Normal file
291
src/modules/school/actions.ts
Normal file
@@ -0,0 +1,291 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { createId } from "@paralleldrive/cuid2"
|
||||
import { eq } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import { academicYears, departments, grades, schools } from "@/shared/db/schema"
|
||||
import type { ActionState } from "@/shared/types/action-state"
|
||||
import { UpsertAcademicYearSchema, UpsertDepartmentSchema, UpsertGradeSchema, UpsertSchoolSchema } from "./schema"
|
||||
|
||||
export async function createDepartmentAction(
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertDepartmentSchema.parse({
|
||||
name: formData.get("name"),
|
||||
description: formData.get("description"),
|
||||
})
|
||||
|
||||
await db.insert(departments).values({
|
||||
id: createId(),
|
||||
name: parsed.name,
|
||||
description: parsed.description ?? null,
|
||||
})
|
||||
|
||||
revalidatePath("/admin/school/departments")
|
||||
return { success: true, message: "Department created" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to create department" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateDepartmentAction(
|
||||
departmentId: string,
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertDepartmentSchema.parse({
|
||||
name: formData.get("name"),
|
||||
description: formData.get("description"),
|
||||
})
|
||||
|
||||
await db
|
||||
.update(departments)
|
||||
.set({
|
||||
name: parsed.name,
|
||||
description: parsed.description ?? null,
|
||||
})
|
||||
.where(eq(departments.id, departmentId))
|
||||
|
||||
revalidatePath("/admin/school/departments")
|
||||
return { success: true, message: "Department updated" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to update department" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteDepartmentAction(departmentId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
await db.delete(departments).where(eq(departments.id, departmentId))
|
||||
revalidatePath("/admin/school/departments")
|
||||
return { success: true, message: "Department deleted" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to delete department" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function createAcademicYearAction(
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertAcademicYearSchema.parse({
|
||||
name: formData.get("name"),
|
||||
startDate: formData.get("startDate"),
|
||||
endDate: formData.get("endDate"),
|
||||
isActive: formData.get("isActive") ?? "false",
|
||||
})
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
if (parsed.isActive) {
|
||||
await tx.update(academicYears).set({ isActive: false })
|
||||
}
|
||||
|
||||
await tx.insert(academicYears).values({
|
||||
id: createId(),
|
||||
name: parsed.name,
|
||||
startDate: new Date(parsed.startDate),
|
||||
endDate: new Date(parsed.endDate),
|
||||
isActive: parsed.isActive,
|
||||
})
|
||||
})
|
||||
|
||||
revalidatePath("/admin/school/academic-year")
|
||||
return { success: true, message: "Academic year created" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to create academic year" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAcademicYearAction(
|
||||
academicYearId: string,
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertAcademicYearSchema.parse({
|
||||
name: formData.get("name"),
|
||||
startDate: formData.get("startDate"),
|
||||
endDate: formData.get("endDate"),
|
||||
isActive: formData.get("isActive") ?? "false",
|
||||
})
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
if (parsed.isActive) {
|
||||
await tx.update(academicYears).set({ isActive: false })
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(academicYears)
|
||||
.set({
|
||||
name: parsed.name,
|
||||
startDate: new Date(parsed.startDate),
|
||||
endDate: new Date(parsed.endDate),
|
||||
isActive: parsed.isActive,
|
||||
})
|
||||
.where(eq(academicYears.id, academicYearId))
|
||||
})
|
||||
|
||||
revalidatePath("/admin/school/academic-year")
|
||||
return { success: true, message: "Academic year updated" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to update academic year" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteAcademicYearAction(academicYearId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
await db.delete(academicYears).where(eq(academicYears.id, academicYearId))
|
||||
revalidatePath("/admin/school/academic-year")
|
||||
return { success: true, message: "Academic year deleted" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to delete academic year" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSchoolAction(
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertSchoolSchema.parse({
|
||||
name: formData.get("name"),
|
||||
code: formData.get("code"),
|
||||
})
|
||||
|
||||
await db.insert(schools).values({
|
||||
id: createId(),
|
||||
name: parsed.name,
|
||||
code: parsed.code?.trim() ? parsed.code.trim() : null,
|
||||
})
|
||||
|
||||
revalidatePath("/admin/school/schools")
|
||||
return { success: true, message: "School created" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to create school" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateSchoolAction(
|
||||
schoolId: string,
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertSchoolSchema.parse({
|
||||
name: formData.get("name"),
|
||||
code: formData.get("code"),
|
||||
})
|
||||
|
||||
await db
|
||||
.update(schools)
|
||||
.set({
|
||||
name: parsed.name,
|
||||
code: parsed.code?.trim() ? parsed.code.trim() : null,
|
||||
})
|
||||
.where(eq(schools.id, schoolId))
|
||||
|
||||
revalidatePath("/admin/school/schools")
|
||||
return { success: true, message: "School updated" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to update school" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteSchoolAction(schoolId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
await db.delete(schools).where(eq(schools.id, schoolId))
|
||||
revalidatePath("/admin/school/schools")
|
||||
revalidatePath("/admin/school/grades")
|
||||
return { success: true, message: "School deleted" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to delete school" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function createGradeAction(
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertGradeSchema.parse({
|
||||
schoolId: formData.get("schoolId"),
|
||||
name: formData.get("name"),
|
||||
order: formData.get("order"),
|
||||
gradeHeadId: formData.get("gradeHeadId"),
|
||||
teachingHeadId: formData.get("teachingHeadId"),
|
||||
})
|
||||
|
||||
await db.insert(grades).values({
|
||||
id: createId(),
|
||||
schoolId: parsed.schoolId,
|
||||
name: parsed.name,
|
||||
order: parsed.order,
|
||||
gradeHeadId: parsed.gradeHeadId,
|
||||
teachingHeadId: parsed.teachingHeadId,
|
||||
})
|
||||
|
||||
revalidatePath("/admin/school/grades")
|
||||
return { success: true, message: "Grade created" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to create grade" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateGradeAction(
|
||||
gradeId: string,
|
||||
prevState: ActionState<string> | undefined,
|
||||
formData: FormData
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const parsed = UpsertGradeSchema.parse({
|
||||
schoolId: formData.get("schoolId"),
|
||||
name: formData.get("name"),
|
||||
order: formData.get("order"),
|
||||
gradeHeadId: formData.get("gradeHeadId"),
|
||||
teachingHeadId: formData.get("teachingHeadId"),
|
||||
})
|
||||
|
||||
await db
|
||||
.update(grades)
|
||||
.set({
|
||||
schoolId: parsed.schoolId,
|
||||
name: parsed.name,
|
||||
order: parsed.order,
|
||||
gradeHeadId: parsed.gradeHeadId,
|
||||
teachingHeadId: parsed.teachingHeadId,
|
||||
})
|
||||
.where(eq(grades.id, gradeId))
|
||||
|
||||
revalidatePath("/admin/school/grades")
|
||||
return { success: true, message: "Grade updated" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to update grade" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteGradeAction(gradeId: string): Promise<ActionState<string>> {
|
||||
try {
|
||||
await db.delete(grades).where(eq(grades.id, gradeId))
|
||||
revalidatePath("/admin/school/grades")
|
||||
return { success: true, message: "Grade deleted" }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return { success: false, message: error.message }
|
||||
return { success: false, message: "Failed to delete grade" }
|
||||
}
|
||||
}
|
||||
315
src/modules/school/components/academic-year-view.tsx
Normal file
315
src/modules/school/components/academic-year-view.tsx
Normal file
@@ -0,0 +1,315 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
import type { AcademicYearListItem } from "../types"
|
||||
import { createAcademicYearAction, deleteAcademicYearAction, updateAcademicYearAction } from "../actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Checkbox } from "@/shared/components/ui/checkbox"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
|
||||
const toDateInput = (iso: string) => iso.slice(0, 10)
|
||||
|
||||
export function AcademicYearClient({ years }: { years: AcademicYearListItem[] }) {
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [createActive, setCreateActive] = useState(true)
|
||||
const [editItem, setEditItem] = useState<AcademicYearListItem | null>(null)
|
||||
const [editActive, setEditActive] = useState(false)
|
||||
const [deleteItem, setDeleteItem] = useState<AcademicYearListItem | null>(null)
|
||||
|
||||
const activeYear = useMemo(() => years.find((y) => y.isActive) ?? null, [years])
|
||||
|
||||
const handleCreate = async (formData: FormData) => {
|
||||
setIsWorking(true)
|
||||
try {
|
||||
formData.set("isActive", createActive ? "true" : "false")
|
||||
const res = await createAcademicYearAction(undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setCreateOpen(false)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to create academic year")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to create academic year")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (formData: FormData) => {
|
||||
if (!editItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
formData.set("isActive", editActive ? "true" : "false")
|
||||
const res = await updateAcademicYearAction(editItem.id, undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setEditItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to update academic year")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to update academic year")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await deleteAcademicYearAction(deleteItem.id)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setDeleteItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to delete academic year")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to delete academic year")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setCreateActive(activeYear === null)
|
||||
setCreateOpen(true)
|
||||
}}
|
||||
disabled={isWorking}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New academic year
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<Card className="lg:col-span-1 shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Active year</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{activeYear ? (
|
||||
<div className="space-y-2">
|
||||
<div className="text-lg font-semibold">{activeYear.name}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{formatDate(activeYear.startDate)} – {formatDate(activeYear.endDate)}
|
||||
</div>
|
||||
<Badge variant="secondary">Active</Badge>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="No active year"
|
||||
description="Set one academic year as active."
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="lg:col-span-2 shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">All years</CardTitle>
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{years.length}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{years.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No academic years"
|
||||
description="Create an academic year to define school calendar."
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Range</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-[60px]" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{years.map((y) => (
|
||||
<TableRow key={y.id}>
|
||||
<TableCell className="font-medium">{y.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{formatDate(y.startDate)} – {formatDate(y.endDate)}
|
||||
</TableCell>
|
||||
<TableCell>{y.isActive ? <Badge variant="secondary">Active</Badge> : <Badge variant="outline">Inactive</Badge>}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditItem(y)
|
||||
setEditActive(y.isActive)
|
||||
}}
|
||||
>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteItem(y)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New academic year</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form action={handleCreate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input id="name" name="name" placeholder="e.g. 2025-2026" autoFocus />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="startDate">Start date</Label>
|
||||
<Input id="startDate" name="startDate" type="date" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="endDate">End date</Label>
|
||||
<Input id="endDate" name="endDate" type="date" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox checked={createActive} onCheckedChange={(v) => setCreateActive(Boolean(v))} />
|
||||
<Label className="cursor-pointer" onClick={() => setCreateActive((v) => !v)}>
|
||||
Set as active
|
||||
</Label>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={Boolean(editItem)} onOpenChange={(open) => {
|
||||
if (!open) setEditItem(null)
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit academic year</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editItem ? (
|
||||
<form action={handleUpdate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-name">Name</Label>
|
||||
<Input id="edit-name" name="name" defaultValue={editItem.name} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-startDate">Start date</Label>
|
||||
<Input id="edit-startDate" name="startDate" type="date" defaultValue={toDateInput(editItem.startDate)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-endDate">End date</Label>
|
||||
<Input id="edit-endDate" name="endDate" type="date" defaultValue={toDateInput(editItem.endDate)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox checked={editActive} onCheckedChange={(v) => setEditActive(Boolean(v))} />
|
||||
<Label className="cursor-pointer" onClick={() => setEditActive((v) => !v)}>
|
||||
Set as active
|
||||
</Label>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog open={Boolean(deleteItem)} onOpenChange={(open) => {
|
||||
if (!open) setDeleteItem(null)
|
||||
}}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete academic year</AlertDialogTitle>
|
||||
<AlertDialogDescription>This will permanently delete {deleteItem?.name || "this academic year"}.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} disabled={isWorking}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
247
src/modules/school/components/departments-view.tsx
Normal file
247
src/modules/school/components/departments-view.tsx
Normal file
@@ -0,0 +1,247 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
import type { DepartmentListItem } from "../types"
|
||||
import { createDepartmentAction, deleteDepartmentAction, updateDepartmentAction } from "../actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
|
||||
export function DepartmentsClient({ departments }: { departments: DepartmentListItem[] }) {
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<DepartmentListItem | null>(null)
|
||||
const [deleteItem, setDeleteItem] = useState<DepartmentListItem | null>(null)
|
||||
|
||||
const handleCreate = async (formData: FormData) => {
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await createDepartmentAction(undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setCreateOpen(false)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to create department")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to create department")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (formData: FormData) => {
|
||||
if (!editItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await updateDepartmentAction(editItem.id, undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setEditItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to update department")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to update department")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await deleteDepartmentAction(deleteItem.id)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setDeleteItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to delete department")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to delete department")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => setCreateOpen(true)} disabled={isWorking}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New department
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">All departments</CardTitle>
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{departments.length}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{departments.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No departments"
|
||||
description="Create your first department to get started."
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead className="w-[60px]" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{departments.map((d) => (
|
||||
<TableRow key={d.id}>
|
||||
<TableCell className="font-medium">{d.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{d.description || "-"}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatDate(d.updatedAt)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditItem(d)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteItem(d)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New department</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form action={handleCreate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input id="name" name="name" placeholder="e.g. Mathematics" autoFocus />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea id="description" name="description" placeholder="Optional" />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={Boolean(editItem)} onOpenChange={(open) => {
|
||||
if (!open) setEditItem(null)
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit department</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editItem ? (
|
||||
<form action={handleUpdate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-name">Name</Label>
|
||||
<Input id="edit-name" name="name" defaultValue={editItem.name} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-description">Description</Label>
|
||||
<Textarea id="edit-description" name="description" defaultValue={editItem.description || ""} />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog open={Boolean(deleteItem)} onOpenChange={(open) => {
|
||||
if (!open) setDeleteItem(null)
|
||||
}}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete department</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete {deleteItem?.name || "this department"}.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} disabled={isWorking}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
779
src/modules/school/components/grades-view.tsx
Normal file
779
src/modules/school/components/grades-view.tsx
Normal file
@@ -0,0 +1,779 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { parseAsString, useQueryState } from "nuqs"
|
||||
|
||||
import type { GradeListItem, SchoolListItem, StaffOption } from "../types"
|
||||
import { createGradeAction, deleteGradeAction, updateGradeAction } from "../actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
|
||||
type FormState = {
|
||||
schoolId: string
|
||||
name: string
|
||||
order: string
|
||||
gradeHeadId: string
|
||||
teachingHeadId: string
|
||||
}
|
||||
|
||||
const toFormState = (item: GradeListItem | null, fallbackSchoolId: string): FormState => ({
|
||||
schoolId: item?.school.id ?? fallbackSchoolId,
|
||||
name: item?.name ?? "",
|
||||
order: String(item?.order ?? 0),
|
||||
gradeHeadId: item?.gradeHead?.id ?? "",
|
||||
teachingHeadId: item?.teachingHead?.id ?? "",
|
||||
})
|
||||
|
||||
type FormErrors = Partial<Record<keyof FormState, string>>
|
||||
|
||||
const normalizeName = (v: string) => v.trim().replace(/\s+/g, " ")
|
||||
|
||||
const NONE_SELECT_VALUE = "__none__"
|
||||
|
||||
const parseOrder = (raw: string) => {
|
||||
const v = raw.trim()
|
||||
if (!v) return 0
|
||||
const n = Number(v)
|
||||
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) return null
|
||||
return n
|
||||
}
|
||||
|
||||
const validateForm = (
|
||||
state: FormState,
|
||||
params: { grades: GradeListItem[]; excludeGradeId?: string }
|
||||
): { ok: boolean; errors: FormErrors } => {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
const schoolId = state.schoolId.trim()
|
||||
if (!schoolId) errors.schoolId = "请选择学校"
|
||||
|
||||
const name = normalizeName(state.name)
|
||||
if (!name) errors.name = "请输入年级名称"
|
||||
if (name.length > 100) errors.name = "年级名称最多 100 个字符"
|
||||
|
||||
const order = parseOrder(state.order)
|
||||
if (order === null) errors.order = "Order 必须是非负整数"
|
||||
|
||||
if (schoolId && name) {
|
||||
const dup = params.grades.find((g) => {
|
||||
if (params.excludeGradeId && g.id === params.excludeGradeId) return false
|
||||
return g.school.id === schoolId && normalizeName(g.name).toLowerCase() === name.toLowerCase()
|
||||
})
|
||||
if (dup) errors.name = "该学校下已存在同名年级"
|
||||
}
|
||||
|
||||
return { ok: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
const formatStaffDetail = (u: StaffOption | null) => {
|
||||
if (!u) return <Badge variant="outline">未设置</Badge>
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<div className="truncate">{u.name}</div>
|
||||
<div className="truncate text-xs text-muted-foreground">{u.email}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GradesClient({
|
||||
grades,
|
||||
schools,
|
||||
staff,
|
||||
}: {
|
||||
grades: GradeListItem[]
|
||||
schools: SchoolListItem[]
|
||||
staff: StaffOption[]
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<GradeListItem | null>(null)
|
||||
const [deleteItem, setDeleteItem] = useState<GradeListItem | null>(null)
|
||||
|
||||
const [q, setQ] = useQueryState("q", parseAsString.withDefault(""))
|
||||
const [school, setSchool] = useQueryState("school", parseAsString.withDefault("all"))
|
||||
const [head, setHead] = useQueryState("head", parseAsString.withDefault("all"))
|
||||
const [sort, setSort] = useQueryState("sort", parseAsString.withDefault("default"))
|
||||
|
||||
const defaultSchoolId = useMemo(() => schools[0]?.id ?? "", [schools])
|
||||
const [createState, setCreateState] = useState<FormState>(() => toFormState(null, defaultSchoolId))
|
||||
const [editState, setEditState] = useState<FormState>(() => toFormState(null, defaultSchoolId))
|
||||
|
||||
useEffect(() => {
|
||||
if (!createOpen) return
|
||||
if (createState.schoolId.trim().length > 0) return
|
||||
if (!defaultSchoolId) return
|
||||
setCreateState((p) => ({ ...p, schoolId: defaultSchoolId }))
|
||||
}, [createOpen, createState.schoolId, defaultSchoolId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!editItem) return
|
||||
if (editState.schoolId.trim().length > 0) return
|
||||
if (!defaultSchoolId) return
|
||||
setEditState((p) => ({ ...p, schoolId: defaultSchoolId }))
|
||||
}, [editItem, editState.schoolId, defaultSchoolId])
|
||||
|
||||
const staffOptions = useMemo(() => {
|
||||
return [...staff].sort((a, b) => {
|
||||
const byName = a.name.localeCompare(b.name)
|
||||
if (byName !== 0) return byName
|
||||
return a.email.localeCompare(b.email)
|
||||
})
|
||||
}, [staff])
|
||||
|
||||
const filteredGrades = useMemo(() => {
|
||||
const needle = q.trim().toLowerCase()
|
||||
const bySchool = school === "all" ? "" : school
|
||||
|
||||
return grades
|
||||
.filter((g) => {
|
||||
if (bySchool && g.school.id !== bySchool) return false
|
||||
if (head === "missing") {
|
||||
if (g.gradeHead || g.teachingHead) return false
|
||||
}
|
||||
if (head === "missing_grade_head") {
|
||||
if (g.gradeHead) return false
|
||||
}
|
||||
if (head === "missing_teaching_head") {
|
||||
if (g.teachingHead) return false
|
||||
}
|
||||
|
||||
if (!needle) return true
|
||||
const hay = [
|
||||
g.name,
|
||||
g.school.name,
|
||||
g.gradeHead?.name ?? "",
|
||||
g.gradeHead?.email ?? "",
|
||||
g.teachingHead?.name ?? "",
|
||||
g.teachingHead?.email ?? "",
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return hay.includes(needle)
|
||||
})
|
||||
.sort((a, b) => {
|
||||
if (sort === "updated_desc") return b.updatedAt.localeCompare(a.updatedAt)
|
||||
if (sort === "updated_asc") return a.updatedAt.localeCompare(b.updatedAt)
|
||||
if (sort === "name_asc") return a.name.localeCompare(b.name)
|
||||
if (sort === "name_desc") return b.name.localeCompare(a.name)
|
||||
if (sort === "order_asc") return a.order - b.order
|
||||
if (sort === "order_desc") return b.order - a.order
|
||||
return 0
|
||||
})
|
||||
}, [grades, head, q, school, sort])
|
||||
|
||||
const hasFilters = q.length > 0 || school !== "all" || head !== "all" || sort !== "default"
|
||||
|
||||
const openEdit = (item: GradeListItem) => {
|
||||
setEditItem(item)
|
||||
setEditState(toFormState(item, defaultSchoolId))
|
||||
}
|
||||
|
||||
const openCreate = () => {
|
||||
setCreateState(toFormState(null, defaultSchoolId))
|
||||
setCreateOpen(true)
|
||||
}
|
||||
|
||||
const createValidation = useMemo(() => validateForm(createState, { grades }), [createState, grades])
|
||||
const editValidation = useMemo(
|
||||
() => validateForm(editState, { grades, excludeGradeId: editItem?.id }),
|
||||
[editItem?.id, editState, grades]
|
||||
)
|
||||
|
||||
const isEditDirty = useMemo(() => {
|
||||
if (!editItem) return false
|
||||
const next = {
|
||||
schoolId: editState.schoolId.trim(),
|
||||
name: normalizeName(editState.name),
|
||||
order: parseOrder(editState.order),
|
||||
gradeHeadId: editState.gradeHeadId || "",
|
||||
teachingHeadId: editState.teachingHeadId || "",
|
||||
}
|
||||
const prev = {
|
||||
schoolId: editItem.school.id,
|
||||
name: normalizeName(editItem.name),
|
||||
order: editItem.order,
|
||||
gradeHeadId: editItem.gradeHead?.id ?? "",
|
||||
teachingHeadId: editItem.teachingHead?.id ?? "",
|
||||
}
|
||||
return (
|
||||
next.schoolId !== prev.schoolId ||
|
||||
next.name !== prev.name ||
|
||||
(typeof next.order === "number" ? next.order : null) !== prev.order ||
|
||||
next.gradeHeadId !== prev.gradeHeadId ||
|
||||
next.teachingHeadId !== prev.teachingHeadId
|
||||
)
|
||||
}, [editItem, editState])
|
||||
|
||||
const handleCreate = async () => {
|
||||
const validation = validateForm(createState, { grades })
|
||||
if (!validation.ok) {
|
||||
toast.error(Object.values(validation.errors)[0] || "请完善表单信息")
|
||||
return
|
||||
}
|
||||
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.set("schoolId", createState.schoolId)
|
||||
fd.set("name", normalizeName(createState.name))
|
||||
fd.set("order", createState.order)
|
||||
fd.set("gradeHeadId", createState.gradeHeadId)
|
||||
fd.set("teachingHeadId", createState.teachingHeadId)
|
||||
|
||||
const res = await createGradeAction(undefined, fd)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setCreateOpen(false)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to create grade")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to create grade")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async () => {
|
||||
if (!editItem) return
|
||||
const validation = validateForm(editState, { grades, excludeGradeId: editItem.id })
|
||||
if (!validation.ok) {
|
||||
toast.error(Object.values(validation.errors)[0] || "请完善表单信息")
|
||||
return
|
||||
}
|
||||
if (!isEditDirty) {
|
||||
toast.message("没有可保存的变更")
|
||||
return
|
||||
}
|
||||
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.set("schoolId", editState.schoolId)
|
||||
fd.set("name", normalizeName(editState.name))
|
||||
fd.set("order", editState.order)
|
||||
fd.set("gradeHeadId", editState.gradeHeadId)
|
||||
fd.set("teachingHeadId", editState.teachingHeadId)
|
||||
|
||||
const res = await updateGradeAction(editItem.id, undefined, fd)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setEditItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to update grade")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to update grade")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await deleteGradeAction(deleteItem.id)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setDeleteItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to delete grade")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to delete grade")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<div className="flex flex-1 flex-col gap-2 md:flex-row md:items-center">
|
||||
<div className="flex-1 md:max-w-sm">
|
||||
<Input placeholder="搜索年级/学校/组长..." value={q} onChange={(e) => setQ(e.target.value || null)} />
|
||||
</div>
|
||||
|
||||
<Select value={school} onValueChange={(v) => setSchool(v === "all" ? null : v)}>
|
||||
<SelectTrigger className="w-full md:w-[220px]">
|
||||
<SelectValue placeholder="学校" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">全部学校</SelectItem>
|
||||
{schools.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={head} onValueChange={(v) => setHead(v === "all" ? null : v)}>
|
||||
<SelectTrigger className="w-full md:w-[220px]">
|
||||
<SelectValue placeholder="负责人" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">全部</SelectItem>
|
||||
<SelectItem value="missing">两者都未设置</SelectItem>
|
||||
<SelectItem value="missing_grade_head">未设置年级组长</SelectItem>
|
||||
<SelectItem value="missing_teaching_head">未设置教研组长</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={sort} onValueChange={(v) => setSort(v === "default" ? null : v)}>
|
||||
<SelectTrigger className="w-full md:w-[220px]">
|
||||
<SelectValue placeholder="排序" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">默认排序</SelectItem>
|
||||
<SelectItem value="updated_desc">更新时间(新→旧)</SelectItem>
|
||||
<SelectItem value="updated_asc">更新时间(旧→新)</SelectItem>
|
||||
<SelectItem value="name_asc">年级名称(A→Z)</SelectItem>
|
||||
<SelectItem value="name_desc">年级名称(Z→A)</SelectItem>
|
||||
<SelectItem value="order_asc">Order(小→大)</SelectItem>
|
||||
<SelectItem value="order_desc">Order(大→小)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{hasFilters ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setQ(null)
|
||||
setSchool(null)
|
||||
setHead(null)
|
||||
setSort(null)
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<Button onClick={openCreate} disabled={isWorking || schools.length === 0}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
新建年级
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">年级列表</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{filteredGrades.length}
|
||||
</Badge>
|
||||
{filteredGrades.length !== grades.length ? (
|
||||
<div className="text-xs text-muted-foreground tabular-nums">/ {grades.length}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{schools.length === 0 ? (
|
||||
<EmptyState
|
||||
title="暂无学校"
|
||||
description="请先创建学校,再在学校下创建年级。"
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : filteredGrades.length === 0 ? (
|
||||
<EmptyState
|
||||
title={grades.length === 0 ? "暂无年级" : "没有匹配结果"}
|
||||
description={grades.length === 0 ? "创建年级以便管理负责人和班级。" : "尝试修改筛选条件或清空搜索。"}
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>学校</TableHead>
|
||||
<TableHead>年级</TableHead>
|
||||
<TableHead>Order</TableHead>
|
||||
<TableHead>年级组长</TableHead>
|
||||
<TableHead>教研组长</TableHead>
|
||||
<TableHead>更新时间</TableHead>
|
||||
<TableHead className="w-[60px]" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filteredGrades.map((g) => (
|
||||
<TableRow key={g.id}>
|
||||
<TableCell className="text-muted-foreground">{g.school.name}</TableCell>
|
||||
<TableCell className="font-medium">{g.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground tabular-nums">{g.order}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatStaffDetail(g.gradeHead)}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatStaffDetail(g.teachingHead)}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatDate(g.updatedAt)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
router.push(`/admin/school/grades/insights?gradeId=${encodeURIComponent(g.id)}`)
|
||||
}
|
||||
>
|
||||
学情
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => openEdit(g)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
编辑
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteItem(g)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent className="sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建年级</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void handleCreate()
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">School</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={createState.schoolId}
|
||||
onValueChange={(v) => setCreateState((p) => ({ ...p, schoolId: v }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a school" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{schools.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{createValidation.errors.schoolId ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{createValidation.errors.schoolId}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="create-grade-name" className="text-right">
|
||||
Grade
|
||||
</Label>
|
||||
<Input
|
||||
id="create-grade-name"
|
||||
className="col-span-3"
|
||||
value={createState.name}
|
||||
onChange={(e) => setCreateState((p) => ({ ...p, name: e.target.value }))}
|
||||
placeholder="e.g. Grade 10"
|
||||
autoFocus
|
||||
/>
|
||||
{createValidation.errors.name ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{createValidation.errors.name}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="create-grade-order" className="text-right">
|
||||
Order
|
||||
</Label>
|
||||
<Input
|
||||
id="create-grade-order"
|
||||
className="col-span-3"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
step={1}
|
||||
value={createState.order}
|
||||
onChange={(e) => setCreateState((p) => ({ ...p, order: e.target.value }))}
|
||||
/>
|
||||
{createValidation.errors.order ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{createValidation.errors.order}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">年级组长</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={createState.gradeHeadId}
|
||||
onValueChange={(v) =>
|
||||
setCreateState((p) => ({ ...p, gradeHeadId: v === NONE_SELECT_VALUE ? "" : v }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Optional" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
|
||||
{staffOptions.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>
|
||||
{u.name} ({u.email})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">教研组长</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={createState.teachingHeadId}
|
||||
onValueChange={(v) =>
|
||||
setCreateState((p) => ({ ...p, teachingHeadId: v === NONE_SELECT_VALUE ? "" : v }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Optional" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
|
||||
{staffOptions.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>
|
||||
{u.name} ({u.email})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
创建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={Boolean(editItem)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑年级</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editItem ? (
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void handleUpdate()
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">School</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={editState.schoolId}
|
||||
onValueChange={(v) => setEditState((p) => ({ ...p, schoolId: v }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a school" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{schools.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{editValidation.errors.schoolId ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{editValidation.errors.schoolId}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-grade-name" className="text-right">
|
||||
Grade
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-grade-name"
|
||||
className="col-span-3"
|
||||
value={editState.name}
|
||||
onChange={(e) => setEditState((p) => ({ ...p, name: e.target.value }))}
|
||||
/>
|
||||
{editValidation.errors.name ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{editValidation.errors.name}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-grade-order" className="text-right">
|
||||
Order
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-grade-order"
|
||||
className="col-span-3"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
step={1}
|
||||
value={editState.order}
|
||||
onChange={(e) => setEditState((p) => ({ ...p, order: e.target.value }))}
|
||||
/>
|
||||
{editValidation.errors.order ? (
|
||||
<div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
|
||||
{editValidation.errors.order}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">年级组长</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={editState.gradeHeadId}
|
||||
onValueChange={(v) =>
|
||||
setEditState((p) => ({ ...p, gradeHeadId: v === NONE_SELECT_VALUE ? "" : v }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Optional" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
|
||||
{staffOptions.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>
|
||||
{u.name} ({u.email})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label className="text-right">教研组长</Label>
|
||||
<div className="col-span-3">
|
||||
<Select
|
||||
value={editState.teachingHeadId}
|
||||
onValueChange={(v) =>
|
||||
setEditState((p) => ({ ...p, teachingHeadId: v === NONE_SELECT_VALUE ? "" : v }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Optional" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
|
||||
{staffOptions.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>
|
||||
{u.name} ({u.email})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
保存
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog
|
||||
open={Boolean(deleteItem)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteItem(null)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>删除年级</AlertDialogTitle>
|
||||
<AlertDialogDescription>将永久删除 {deleteItem?.name || "该年级"}。</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isWorking}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} disabled={isWorking}>
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
253
src/modules/school/components/schools-view.tsx
Normal file
253
src/modules/school/components/schools-view.tsx
Normal file
@@ -0,0 +1,253 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
import type { SchoolListItem } from "../types"
|
||||
import { createSchoolAction, deleteSchoolAction, updateSchoolAction } from "../actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { EmptyState } from "@/shared/components/ui/empty-state"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/shared/components/ui/alert-dialog"
|
||||
import { formatDate } from "@/shared/lib/utils"
|
||||
|
||||
export function SchoolsClient({ schools }: { schools: SchoolListItem[] }) {
|
||||
const router = useRouter()
|
||||
const [isWorking, setIsWorking] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<SchoolListItem | null>(null)
|
||||
const [deleteItem, setDeleteItem] = useState<SchoolListItem | null>(null)
|
||||
|
||||
const handleCreate = async (formData: FormData) => {
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await createSchoolAction(undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setCreateOpen(false)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to create school")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to create school")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (formData: FormData) => {
|
||||
if (!editItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await updateSchoolAction(editItem.id, undefined, formData)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setEditItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to update school")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to update school")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteItem) return
|
||||
setIsWorking(true)
|
||||
try {
|
||||
const res = await deleteSchoolAction(deleteItem.id)
|
||||
if (res.success) {
|
||||
toast.success(res.message)
|
||||
setDeleteItem(null)
|
||||
router.refresh()
|
||||
} else {
|
||||
toast.error(res.message || "Failed to delete school")
|
||||
}
|
||||
} catch {
|
||||
toast.error("Failed to delete school")
|
||||
} finally {
|
||||
setIsWorking(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => setCreateOpen(true)} disabled={isWorking}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New school
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">All schools</CardTitle>
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{schools.length}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{schools.length === 0 ? (
|
||||
<EmptyState
|
||||
title="No schools"
|
||||
description="Create your first school to get started."
|
||||
className="h-auto border-none shadow-none"
|
||||
/>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead className="w-[60px]" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{schools.map((s) => (
|
||||
<TableRow key={s.id}>
|
||||
<TableCell className="font-medium">{s.name}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{s.code || "-"}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{formatDate(s.updatedAt)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditItem(s)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setDeleteItem(s)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New school</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form action={handleCreate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input id="name" name="name" placeholder="e.g. First Primary School" autoFocus />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code">Code</Label>
|
||||
<Input id="code" name="code" placeholder="Optional" />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={Boolean(editItem)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit school</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editItem ? (
|
||||
<form action={handleUpdate} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-name">Name</Label>
|
||||
<Input id="edit-name" name="name" defaultValue={editItem.name} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-code">Code</Label>
|
||||
<Input id="edit-code" name="code" defaultValue={editItem.code || ""} />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isWorking}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog
|
||||
open={Boolean(deleteItem)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteItem(null)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete school</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete {deleteItem?.name || "this school"} and its grades.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} disabled={isWorking}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
183
src/modules/school/data-access.ts
Normal file
183
src/modules/school/data-access.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import "server-only"
|
||||
|
||||
import { cache } from "react"
|
||||
import { asc, eq, inArray, or } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import { academicYears, departments, grades, schools, users } from "@/shared/db/schema"
|
||||
import type { AcademicYearListItem, DepartmentListItem, GradeListItem, SchoolListItem, StaffOption } from "./types"
|
||||
|
||||
const toIso = (d: Date) => d.toISOString()
|
||||
|
||||
export const getDepartments = cache(async (): Promise<DepartmentListItem[]> => {
|
||||
try {
|
||||
const rows = await db.select().from(departments).orderBy(asc(departments.name))
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
description: r.description ?? null,
|
||||
createdAt: toIso(r.createdAt),
|
||||
updatedAt: toIso(r.updatedAt),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
export const getAcademicYears = cache(async (): Promise<AcademicYearListItem[]> => {
|
||||
try {
|
||||
const rows = await db.select().from(academicYears).orderBy(asc(academicYears.startDate))
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
startDate: toIso(r.startDate),
|
||||
endDate: toIso(r.endDate),
|
||||
isActive: Boolean(r.isActive),
|
||||
createdAt: toIso(r.createdAt),
|
||||
updatedAt: toIso(r.updatedAt),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
export const getSchools = cache(async (): Promise<SchoolListItem[]> => {
|
||||
try {
|
||||
const rows = await db.select().from(schools).orderBy(asc(schools.name))
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
code: r.code ?? null,
|
||||
createdAt: toIso(r.createdAt),
|
||||
updatedAt: toIso(r.updatedAt),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
export const getGrades = cache(async (): Promise<GradeListItem[]> => {
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: grades.id,
|
||||
name: grades.name,
|
||||
order: grades.order,
|
||||
schoolId: schools.id,
|
||||
schoolName: schools.name,
|
||||
gradeHeadId: grades.gradeHeadId,
|
||||
teachingHeadId: grades.teachingHeadId,
|
||||
createdAt: grades.createdAt,
|
||||
updatedAt: grades.updatedAt,
|
||||
})
|
||||
.from(grades)
|
||||
.innerJoin(schools, eq(schools.id, grades.schoolId))
|
||||
.orderBy(asc(schools.name), asc(grades.order), asc(grades.name))
|
||||
|
||||
const headIds = Array.from(
|
||||
new Set(
|
||||
rows
|
||||
.flatMap((r) => [r.gradeHeadId, r.teachingHeadId])
|
||||
.filter((v): v is string => typeof v === "string" && v.length > 0)
|
||||
)
|
||||
)
|
||||
|
||||
const heads = headIds.length
|
||||
? await db
|
||||
.select({ id: users.id, name: users.name, email: users.email })
|
||||
.from(users)
|
||||
.where(inArray(users.id, headIds))
|
||||
: []
|
||||
|
||||
const headById = new Map<string, StaffOption>()
|
||||
for (const u of heads) {
|
||||
headById.set(u.id, { id: u.id, name: u.name ?? "Unnamed", email: u.email })
|
||||
}
|
||||
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
school: { id: r.schoolId, name: r.schoolName },
|
||||
name: r.name,
|
||||
order: Number(r.order ?? 0),
|
||||
gradeHead: r.gradeHeadId ? headById.get(r.gradeHeadId) ?? null : null,
|
||||
teachingHead: r.teachingHeadId ? headById.get(r.teachingHeadId) ?? null : null,
|
||||
createdAt: toIso(r.createdAt),
|
||||
updatedAt: toIso(r.updatedAt),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
export const getStaffOptions = cache(async (): Promise<StaffOption[]> => {
|
||||
try {
|
||||
const rows = await db
|
||||
.select({ id: users.id, name: users.name, email: users.email })
|
||||
.from(users)
|
||||
.where(inArray(users.role, ["teacher", "admin"]))
|
||||
.orderBy(asc(users.name), asc(users.email))
|
||||
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name ?? "Unnamed",
|
||||
email: r.email,
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
export const getGradesForStaff = cache(async (staffId: string): Promise<GradeListItem[]> => {
|
||||
const id = staffId.trim()
|
||||
if (!id) return []
|
||||
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: grades.id,
|
||||
name: grades.name,
|
||||
order: grades.order,
|
||||
schoolId: schools.id,
|
||||
schoolName: schools.name,
|
||||
gradeHeadId: grades.gradeHeadId,
|
||||
teachingHeadId: grades.teachingHeadId,
|
||||
createdAt: grades.createdAt,
|
||||
updatedAt: grades.updatedAt,
|
||||
})
|
||||
.from(grades)
|
||||
.innerJoin(schools, eq(schools.id, grades.schoolId))
|
||||
.where(or(eq(grades.gradeHeadId, id), eq(grades.teachingHeadId, id)))
|
||||
.orderBy(asc(schools.name), asc(grades.order), asc(grades.name))
|
||||
|
||||
const headIds = Array.from(
|
||||
new Set(
|
||||
rows
|
||||
.flatMap((r) => [r.gradeHeadId, r.teachingHeadId])
|
||||
.filter((v): v is string => typeof v === "string" && v.length > 0)
|
||||
)
|
||||
)
|
||||
|
||||
const heads = headIds.length
|
||||
? await db
|
||||
.select({ id: users.id, name: users.name, email: users.email })
|
||||
.from(users)
|
||||
.where(inArray(users.id, headIds))
|
||||
: []
|
||||
|
||||
const headById = new Map<string, StaffOption>()
|
||||
for (const u of heads) headById.set(u.id, { id: u.id, name: u.name ?? "Unnamed", email: u.email })
|
||||
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
school: { id: r.schoolId, name: r.schoolName },
|
||||
name: r.name,
|
||||
order: Number(r.order ?? 0),
|
||||
gradeHead: r.gradeHeadId ? headById.get(r.gradeHeadId) ?? null : null,
|
||||
teachingHead: r.teachingHeadId ? headById.get(r.teachingHeadId) ?? null : null,
|
||||
createdAt: toIso(r.createdAt),
|
||||
updatedAt: toIso(r.updatedAt),
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
})
|
||||
52
src/modules/school/schema.ts
Normal file
52
src/modules/school/schema.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const UpsertDepartmentSchema = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
description: z.string().trim().max(5000).optional().nullable(),
|
||||
})
|
||||
|
||||
export const UpsertAcademicYearSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
startDate: z.string().min(1),
|
||||
endDate: z.string().min(1),
|
||||
isActive: z.union([z.literal("on"), z.literal("true"), z.literal("false"), z.string()]).optional(),
|
||||
})
|
||||
.transform((v) => ({
|
||||
name: v.name,
|
||||
startDate: v.startDate,
|
||||
endDate: v.endDate,
|
||||
isActive: v.isActive === "on" || v.isActive === "true",
|
||||
}))
|
||||
.refine((v) => new Date(v.startDate).getTime() <= new Date(v.endDate).getTime(), {
|
||||
message: "startDate must be before endDate",
|
||||
})
|
||||
|
||||
export const UpsertSchoolSchema = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
code: z.string().trim().max(50).optional().nullable(),
|
||||
})
|
||||
|
||||
export const UpsertGradeSchema = z
|
||||
.object({
|
||||
schoolId: z.string().trim().min(1),
|
||||
name: z.string().trim().min(1).max(100),
|
||||
order: z.union([z.string(), z.number()]).optional().nullable(),
|
||||
gradeHeadId: z.string().trim().optional().nullable(),
|
||||
teachingHeadId: z.string().trim().optional().nullable(),
|
||||
})
|
||||
.transform((v) => ({
|
||||
schoolId: v.schoolId,
|
||||
name: v.name,
|
||||
order:
|
||||
typeof v.order === "number"
|
||||
? v.order
|
||||
: typeof v.order === "string" && v.order.trim().length > 0
|
||||
? Number(v.order)
|
||||
: 0,
|
||||
gradeHeadId: v.gradeHeadId && v.gradeHeadId.length > 0 ? v.gradeHeadId : null,
|
||||
teachingHeadId: v.teachingHeadId && v.teachingHeadId.length > 0 ? v.teachingHeadId : null,
|
||||
}))
|
||||
.refine((v) => Number.isFinite(v.order) && Number.isInteger(v.order) && v.order >= 0, {
|
||||
message: "order must be a non-negative integer",
|
||||
})
|
||||
42
src/modules/school/types.ts
Normal file
42
src/modules/school/types.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export type DepartmentListItem = {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type AcademicYearListItem = {
|
||||
id: string
|
||||
name: string
|
||||
startDate: string
|
||||
endDate: string
|
||||
isActive: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type SchoolListItem = {
|
||||
id: string
|
||||
name: string
|
||||
code: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type StaffOption = {
|
||||
id: string
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export type GradeListItem = {
|
||||
id: string
|
||||
school: { id: string; name: string }
|
||||
name: string
|
||||
order: number
|
||||
gradeHead: StaffOption | null
|
||||
teachingHead: StaffOption | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
Reference in New Issue
Block a user