feat: add CRUD forms with Server Actions for establishments, users, classes, students
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { deleteUser } from "../actions";
|
||||
|
||||
export default function DeleteUserButton({
|
||||
userId,
|
||||
currentUserId,
|
||||
}: {
|
||||
userId: string;
|
||||
currentUserId: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (userId === currentUserId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await deleteUser(userId);
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Une erreur est survenue");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="destructive" onClick={() => setOpen(true)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirmer la suppression</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Êtes-vous sûr de vouloir supprimer cet utilisateur ? Cette action est irréversible.
|
||||
</p>
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setOpen(false)} disabled={loading}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleDelete} disabled={loading}>
|
||||
{loading ? "Suppression..." : "Supprimer"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect, notFound } from "next/navigation";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import DeleteUserButton from "./DeleteUserButton";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function UserDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
if (!isSuperadmin && session.user.role !== "admin") redirect("/dashboard");
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
include: { establishment: true },
|
||||
});
|
||||
|
||||
if (!user) notFound();
|
||||
|
||||
if (!isSuperadmin && user.establishmentId !== session.user.establishmentId) {
|
||||
redirect("/dashboard/users");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-xl">
|
||||
<h1 className="text-3xl font-bold">Détail de l'utilisateur</h1>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{user.email}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">Rôle :</span>
|
||||
<Badge
|
||||
variant={
|
||||
user.role === "superadmin"
|
||||
? "default"
|
||||
: user.role === "admin"
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
>
|
||||
{user.role}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">Établissement :</span>
|
||||
<span>{user.establishment?.name || "-"}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">Créé le :</span>
|
||||
<span>{new Date(user.createdAt).toLocaleDateString("fr-FR")}</span>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Link href="/dashboard/users">
|
||||
<Button variant="outline">Retour</Button>
|
||||
</Link>
|
||||
<DeleteUserButton userId={user.id} currentUserId={session.user.id as string} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
'use server';
|
||||
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashPassword } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
const createUserSchema = z.object({
|
||||
email: z.string().email("Email invalide"),
|
||||
password: z.string().min(8, "Le mot de passe doit faire au moins 8 caractères"),
|
||||
role: z.enum(["admin", "teacher"], { message: "Rôle invalide" }),
|
||||
establishmentId: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
export async function createUser(formData: FormData) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) throw new Error("Non authentifié");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
if (!isSuperadmin && session.user.role !== "admin") throw new Error("Accès interdit");
|
||||
|
||||
const raw = Object.fromEntries(formData);
|
||||
const parsed = createUserSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.issues.map((e: any) => e.message).join(", "));
|
||||
}
|
||||
|
||||
const { email, password, role, establishmentId } = parsed.data;
|
||||
|
||||
const finalEstablishmentId = isSuperadmin
|
||||
? (establishmentId || null)
|
||||
: session.user.establishmentId;
|
||||
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
if (existing) throw new Error("Cet email est déjà utilisé");
|
||||
|
||||
const hashed = await hashPassword(password);
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
password: hashed,
|
||||
role,
|
||||
establishmentId: finalEstablishmentId,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/users");
|
||||
redirect("/dashboard/users");
|
||||
}
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) throw new Error("Non authentifié");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
if (!isSuperadmin && session.user.role !== "admin") throw new Error("Accès interdit");
|
||||
|
||||
if (userId === session.user.id) throw new Error("Vous ne pouvez pas supprimer votre propre compte");
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) throw new Error("Utilisateur introuvable");
|
||||
|
||||
if (!isSuperadmin && user.establishmentId !== session.user.establishmentId) {
|
||||
throw new Error("Accès interdit");
|
||||
}
|
||||
|
||||
await prisma.user.delete({ where: { id: userId } });
|
||||
|
||||
revalidatePath("/dashboard/users");
|
||||
redirect("/dashboard/users");
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { createUser } from "../actions";
|
||||
|
||||
export default function NewUserForm({
|
||||
establishments,
|
||||
isSuperadmin,
|
||||
}: {
|
||||
establishments: any[];
|
||||
isSuperadmin: boolean;
|
||||
}) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
async function handleSubmit(formData: FormData) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await createUser(formData);
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Une erreur est survenue");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<form action={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Email</label>
|
||||
<Input type="email" name="email" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Mot de passe</label>
|
||||
<Input type="password" name="password" minLength={8} required />
|
||||
<p className="text-xs text-muted-foreground mt-1">Minimum 8 caractères</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Rôle</label>
|
||||
<Select name="role" required>
|
||||
<option value="">Choisir un rôle</option>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="teacher">Teacher</option>
|
||||
</Select>
|
||||
</div>
|
||||
{isSuperadmin && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Établissement</label>
|
||||
<Select name="establishmentId">
|
||||
<option value="">Aucun</option>
|
||||
{establishments.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Création..." : "Créer"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => router.push("/dashboard/users")}
|
||||
disabled={loading}
|
||||
>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import NewUserForm from "./NewUserForm";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function NewUserPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
if (!isSuperadmin && session.user.role !== "admin") redirect("/dashboard");
|
||||
|
||||
const establishments = isSuperadmin
|
||||
? await prisma.establishment.findMany({ orderBy: { name: "asc" } })
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-xl">
|
||||
<h1 className="text-3xl font-bold">Nouvel utilisateur</h1>
|
||||
<NewUserForm establishments={establishments} isSuperadmin={isSuperadmin} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function UsersPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
const establishmentId = session.user.establishmentId;
|
||||
|
||||
if (!isSuperadmin && session.user.role !== "admin") redirect("/dashboard");
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where: isSuperadmin ? {} : { establishmentId },
|
||||
include: { establishment: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold">Utilisateurs</h1>
|
||||
<Link href="/dashboard/users/new">
|
||||
<Button>Ajouter</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Liste des utilisateurs</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Rôle</TableHead>
|
||||
<TableHead>Établissement</TableHead>
|
||||
<TableHead>Créé le</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/dashboard/users/${user.id}`} className="hover:underline">
|
||||
{user.email}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={
|
||||
user.role === "superadmin"
|
||||
? "default"
|
||||
: user.role === "admin"
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
>
|
||||
{user.role}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{user.establishment?.name || "-"}</TableCell>
|
||||
<TableCell>{new Date(user.createdAt).toLocaleDateString("fr-FR")}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{users.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center text-muted-foreground">
|
||||
Aucun utilisateur
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user