changes after second dev test

fixed full name issue, refresh issue on reservation and user/admin login issue
This commit is contained in:
belviskhoremk
2026-05-27 23:04:32 +00:00
parent 209ac114b0
commit 53365b9dbf
7 changed files with 60 additions and 27 deletions

View File

@@ -12,7 +12,7 @@ import { toast } from "sonner";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
export default function AdminLogin() { export default function AdminLogin() {
const { login } = useAuth(); const { login, logout } = useAuth();
const router = useRouter(); const router = useRouter();
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -24,6 +24,7 @@ export default function AdminLogin() {
try { try {
const profile = await login(email, password); const profile = await login(email, password);
if (profile.role !== "admin") { if (profile.role !== "admin") {
logout();
toast.error("Accès refusé : rôle administrateur requis"); toast.error("Accès refusé : rôle administrateur requis");
return; return;
} }

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { Check, X, Trash2, Mail, Phone } from "lucide-react"; import { Check, X, Trash2, Mail, Phone, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -23,6 +23,7 @@ export default function AdminReservations() {
const { t, locale } = useLanguage(); const { t, locale } = useLanguage();
const [filter, setFilter] = useState<"all" | Reservation["status"]>("all"); const [filter, setFilter] = useState<"all" | Reservation["status"]>("all");
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
const [updatingId, setUpdatingId] = useState<string | null>(null);
const statusConfig: Record<Reservation["status"], { label: string; variant: "default" | "secondary" | "destructive" }> = { const statusConfig: Record<Reservation["status"], { label: string; variant: "default" | "secondary" | "destructive" }> = {
pending: { label: t("admin.status.pending"), variant: "secondary" }, pending: { label: t("admin.status.pending"), variant: "secondary" },
@@ -35,20 +36,26 @@ export default function AdminReservations() {
.sort((a, b) => `${b.date}${b.time}`.localeCompare(`${a.date}${a.time}`)); .sort((a, b) => `${b.date}${b.time}`.localeCompare(`${a.date}${a.time}`));
const handleConfirm = async (id: string) => { const handleConfirm = async (id: string) => {
setUpdatingId(id);
try { try {
await updateReservationStatus(id, "confirmed"); await updateReservationStatus(id, "confirmed");
toast.success(t("admin.bookings.confirmed_toast")); toast.success(t("admin.bookings.confirmed_toast"));
} catch (err) { } catch (err) {
toast.error(err instanceof ApiError ? err.message : t("admin.error")); toast.error(err instanceof ApiError ? err.message : t("admin.error"));
} finally {
setUpdatingId(null);
} }
}; };
const handleCancel = async (id: string) => { const handleCancel = async (id: string) => {
setUpdatingId(id);
try { try {
await updateReservationStatus(id, "cancelled"); await updateReservationStatus(id, "cancelled");
toast.success(t("admin.bookings.cancelled_toast")); toast.success(t("admin.bookings.cancelled_toast"));
} catch (err) { } catch (err) {
toast.error(err instanceof ApiError ? err.message : t("admin.error")); toast.error(err instanceof ApiError ? err.message : t("admin.error"));
} finally {
setUpdatingId(null);
} }
}; };
@@ -135,6 +142,12 @@ export default function AdminReservations() {
</Badge> </Badge>
</TableCell> </TableCell>
<TableCell className="text-right space-x-1"> <TableCell className="text-right space-x-1">
{updatingId === r.id ? (
<Button variant="ghost" size="icon" disabled>
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</Button>
) : (
<>
{r.status !== "confirmed" && ( {r.status !== "confirmed" && (
<Button variant="ghost" size="icon" onClick={() => handleConfirm(r.id)} title={t("admin.status.confirmed")}> <Button variant="ghost" size="icon" onClick={() => handleConfirm(r.id)} title={t("admin.status.confirmed")}>
<Check className="h-4 w-4 text-primary" /> <Check className="h-4 w-4 text-primary" />
@@ -148,6 +161,8 @@ export default function AdminReservations() {
<Button variant="ghost" size="icon" onClick={() => setDeleteId(r.id)} title={t("admin.delete")}> <Button variant="ghost" size="icon" onClick={() => setDeleteId(r.id)} title={t("admin.delete")}>
<Trash2 className="h-4 w-4 text-destructive" /> <Trash2 className="h-4 w-4 text-destructive" />
</Button> </Button>
</>
)}
</TableCell> </TableCell>
</TableRow> </TableRow>
)) ))

View File

@@ -15,7 +15,7 @@ type Mode = "login" | "register" | "forgot";
export default function Auth() { export default function Auth() {
const { t } = useLanguage(); const { t } = useLanguage();
const { login, register, user } = useAuth(); const { login, register, logout, user } = useAuth();
const router = useRouter(); const router = useRouter();
const [mode, setMode] = useState<Mode>("login"); const [mode, setMode] = useState<Mode>("login");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@@ -24,9 +24,7 @@ export default function Auth() {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
useEffect(() => { useEffect(() => {
if (user) { if (user) router.replace("/");
router.replace(user.role === "admin" ? "/admin" : "/");
}
}, [user, router]); }, [user, router]);
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
@@ -35,13 +33,18 @@ export default function Auth() {
try { try {
if (mode === "login") { if (mode === "login") {
const profile = await login(email, password); const profile = await login(email, password);
if (profile.role === "admin") {
logout();
toast.error(t("auth.admin_not_allowed"));
return;
}
toast.success(t("auth.login_success")); toast.success(t("auth.login_success"));
router.push(profile.role === "admin" ? "/admin" : "/"); router.push("/");
} else if (mode === "register") { } else if (mode === "register") {
const profile = await register(email, password, name); const profile = await register(email, password, name);
if (profile) { if (profile) {
toast.success(t("auth.register_success")); toast.success(t("auth.register_success"));
router.push(profile.role === "admin" ? "/admin" : "/"); router.push("/");
} else { } else {
toast.success(t("auth.confirm_email")); toast.success(t("auth.confirm_email"));
router.push("/connexion"); router.push("/connexion");

View File

@@ -18,7 +18,7 @@ import { toast } from "sonner";
import { User, CalendarDays, ShoppingBag, X } from "lucide-react"; import { User, CalendarDays, ShoppingBag, X } from "lucide-react";
export default function MonCompte() { export default function MonCompte() {
const { user, isLoading } = useAuth(); const { user, isLoading, refreshUser } = useAuth();
const { t, locale } = useLanguage(); const { t, locale } = useLanguage();
const router = useRouter(); const router = useRouter();
@@ -39,6 +39,12 @@ export default function MonCompte() {
if (!isLoading && user?.role === "admin") router.replace("/admin"); if (!isLoading && user?.role === "admin") router.replace("/admin");
}, [user, isLoading, router]); }, [user, isLoading, router]);
// Refresh profile from server on mount to get the latest full_name
useEffect(() => {
if (user) refreshUser().catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => { useEffect(() => {
if (user) { if (user) {
startTransition(() => { startTransition(() => {
@@ -65,6 +71,7 @@ export default function MonCompte() {
setSavingProfile(true); setSavingProfile(true);
try { try {
await updateProfile(name, phone || null); await updateProfile(name, phone || null);
await refreshUser();
toast.success(t("account.profile_saved")); toast.success(t("account.profile_saved"));
} catch (err) { } catch (err) {
toast.error(err instanceof ApiError ? err.message : t("auth.error")); toast.error(err instanceof ApiError ? err.message : t("auth.error"));

View File

@@ -44,7 +44,7 @@ interface AdminContextType {
deleteProduct: (id: string) => Promise<void>; deleteProduct: (id: string) => Promise<void>;
reservations: Reservation[]; reservations: Reservation[];
reservationsLoading: boolean; reservationsLoading: boolean;
refreshReservations: () => Promise<void>; refreshReservations: (silent?: boolean) => Promise<void>;
updateReservationStatus: (id: string, status: "confirmed" | "cancelled") => Promise<void>; updateReservationStatus: (id: string, status: "confirmed" | "cancelled") => Promise<void>;
deleteReservation: (id: string) => Promise<void>; deleteReservation: (id: string) => Promise<void>;
} }
@@ -69,14 +69,14 @@ export const AdminProvider = ({ children }: { children: ReactNode }) => {
} }
}; };
const refreshReservations = async () => { const refreshReservations = async (silent = false) => {
if (!isAdmin) return; if (!isAdmin) return;
setReservationsLoading(true); if (!silent) setReservationsLoading(true);
try { try {
const res = await bookingsApi.adminListBookings(); const res = await bookingsApi.adminListBookings();
setReservations(res.data.map(toReservation)); setReservations(res.data.map(toReservation));
} finally { } finally {
setReservationsLoading(false); if (!silent) setReservationsLoading(false);
} }
}; };
@@ -108,12 +108,11 @@ export const AdminProvider = ({ children }: { children: ReactNode }) => {
const updateReservationStatus = async (id: string, status: "confirmed" | "cancelled") => { const updateReservationStatus = async (id: string, status: "confirmed" | "cancelled") => {
await bookingsApi.adminUpdateBookingStatus(id, status); await bookingsApi.adminUpdateBookingStatus(id, status);
// Optimistic update for immediate feedback
setReservations((prev) => setReservations((prev) =>
prev.map((r) => (r.id === id ? { ...r, status } : r)) prev.map((r) => (r.id === id ? { ...r, status } : r))
); );
// Refresh from server to ensure consistency // Sync with server silently — no loading flash
refreshReservations(); refreshReservations(true);
}; };
const deleteReservation = async (id: string) => { const deleteReservation = async (id: string) => {

View File

@@ -13,6 +13,7 @@ interface AuthContextType {
login: (email: string, password: string) => Promise<UserProfile>; login: (email: string, password: string) => Promise<UserProfile>;
register: (email: string, password: string, name: string) => Promise<UserProfile | null>; register: (email: string, password: string, name: string) => Promise<UserProfile | null>;
logout: () => void; logout: () => void;
refreshUser: () => Promise<void>;
} }
const AuthContext = createContext<AuthContextType | undefined>(undefined); const AuthContext = createContext<AuthContextType | undefined>(undefined);
@@ -50,6 +51,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
setUser(null); setUser(null);
}; };
const refreshUser = async () => {
const profile = await authApi.getMe();
setUser(profile);
};
return ( return (
<AuthContext.Provider <AuthContext.Provider
value={{ value={{
@@ -59,6 +65,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
login, login,
register, register,
logout, logout,
refreshUser,
}} }}
> >
{children} {children}

View File

@@ -89,6 +89,7 @@ const translations: Record<string, Record<Language, string>> = {
"auth.forgot_send": { fr: "Envoyer le lien", de: "Link senden", en: "Send link" }, "auth.forgot_send": { fr: "Envoyer le lien", de: "Link senden", en: "Send link" },
"auth.forgot_sent": { fr: "Email envoyé ! Vérifiez votre boîte mail.", de: "E-Mail gesendet! Prüfen Sie Ihren Posteingang.", en: "Email sent! Check your inbox." }, "auth.forgot_sent": { fr: "Email envoyé ! Vérifiez votre boîte mail.", de: "E-Mail gesendet! Prüfen Sie Ihren Posteingang.", en: "Email sent! Check your inbox." },
"auth.back_to_login": { fr: "Retour à la connexion", de: "Zurück zur Anmeldung", en: "Back to login" }, "auth.back_to_login": { fr: "Retour à la connexion", de: "Zurück zur Anmeldung", en: "Back to login" },
"auth.admin_not_allowed": { fr: "Les administrateurs doivent utiliser l'espace admin", de: "Administratoren müssen den Admin-Bereich verwenden", en: "Administrators must use the admin login" },
// ── Booking (public page) ──────────────────────────────────────────────────── // ── Booking (public page) ────────────────────────────────────────────────────
"booking.select_service": { fr: "Choisir un service", de: "Service wählen", en: "Select service" }, "booking.select_service": { fr: "Choisir un service", de: "Service wählen", en: "Select service" },