"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { beginImpersonation, type ImpersonationStart } from "@/lib/impersonation"; import { Users as UsersIcon } from "lucide-react"; import { RoleBadge, type Role as RoleBadgeRole } from "@/components/shared/RoleBadge"; import { errorMessage } from "@/lib/utils"; import type { Paginated } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { useCampuses } from "@/hooks/useCampuses"; import { SavedFilters } from "@/components/shared/SavedFilters"; interface UserItem { id: string; name: string; email: string; role: string; phoneNumber?: string | null; notificationPreference?: string; twoFactorEnabled?: boolean; isActive: boolean; createdAt: string; updatedAt: string; } const roleOptions = ["user", "staff", "supervisor", "admin"] as const; type Role = typeof roleOptions[number]; const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const; export default function AdminUsersPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const isAdmin = useMemo(() => user?.role === "admin", [user]); useEffect(() => { if (loading) return; if (!user) router.replace("/login"); }, [user, loading, router]); // Data state const [users, setUsers] = useState([]); const [fetching, setFetching] = useState(false); const [error, setError] = useDismissingState(null); const [page, setPage] = useState(1); const [totalPages, setTotalPages] = useState(1); const [total, setTotal] = useState(0); const [pageSize, setPageSize] = useState(50); // Search and filter state (server-side) const [query, setQuery] = useState(""); const [debouncedQuery, setDebouncedQuery] = useState(""); const [roleFilter, setRoleFilter] = useState(""); const [activeFilter, setActiveFilter] = useState<"" | "true" | "false">(""); // ?q= (the Ctrl+K palette links here with a person's email). useEffect(() => { const q = new URLSearchParams(window.location.search).get("q"); if (q) { setQuery(q); setDebouncedQuery(q); } }, []); // Debounce search useEffect(() => { const t = setTimeout(() => setDebouncedQuery(query), 350); return () => clearTimeout(t); }, [query]); // Create form state const [createOpen, setCreateOpen] = useState(false); const [cName, setCName] = useState(""); const [cEmail, setCEmail] = useState(""); const [cPassword, setCPassword] = useState(""); const [cPhone, setCPhone] = useState(""); const [cRole, setCRole] = useState("user"); const [creating, setCreating] = useState(false); // Edit modal state const [editingId, setEditingId] = useState(null); const [editData, setEditData] = useState & { password?: string }>({}); const [saving, setSaving] = useState(false); const editingUser = useMemo(() => users.find(u => u.id === editingId) || null, [users, editingId]); const buildQuery = useCallback((p: number, ps = pageSize) => { const qs = new URLSearchParams({ page: String(p), limit: String(ps) }); if (debouncedQuery.trim()) qs.set("search", debouncedQuery.trim()); if (roleFilter) qs.set("role", roleFilter); if (activeFilter !== "") qs.set("isActive", activeFilter); return `/api/users?${qs.toString()}`; }, [debouncedQuery, roleFilter, activeFilter, pageSize]); const loadUsers = useCallback(async (p = 1, ps = pageSize) => { if (!token) return; setError(null); setFetching(true); try { const url = buildQuery(p, ps); const res = await apiFetch>(url, { authToken: token }); setUsers(Array.isArray(res?.data) ? res.data : []); setTotal(res?.total ?? 0); setTotalPages(res?.pages ?? 1); setPage(p); } catch (e) { setError(errorMessage(e) || "Failed to load users"); } finally { setFetching(false); } }, [token, buildQuery, pageSize, setError]); // Initial load, and back to page 1 whenever a filter or the page size changes // (loadUsers is recreated when any of them do). useEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]); const goToPage = (p: number) => loadUsers(p); const handlePageSizeChange = (newSize: number) => { setPageSize(newSize); }; const resetCreateForm = () => { setCName(""); setCEmail(""); setCPassword(""); setCPhone(""); setCRole("user"); }; const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); if (!cEmail || !cPassword) { setError("Email and password are required"); return; } try { setCreating(true); const created = await apiFetch<{ id?: string }>("/api/users", { method: "POST", body: { name: cName || cEmail.split("@")[0], email: cEmail, password: cPassword, phoneNumber: cPhone || undefined }, }); if (cRole && cRole !== "user" && created?.id) { await apiFetch(`/api/users/${encodeURIComponent(created.id)}`, { method: "PUT", authToken: token!, body: { role: cRole }, }); } resetCreateForm(); setCreateOpen(false); await loadUsers(page); } catch (e) { setError(errorMessage(e) || "Failed to create user"); } finally { setCreating(false); } }; // Campus-scoped staff: the campuses a supervisor/staff member is limited to (loaded per user; // null until loaded, so an unloaded list is never saved over the real one). const campusInfo = useCampuses(); const [scope, setScope] = useState<{ id: string; name: string }[] | null>(null); const startEdit = (u: UserItem) => { setEditingId(u.id); setEditData({ ...u, password: "" }); setScope(null); apiFetch<{ scopedCampuses?: { id: string; name: string }[] }>(`/api/users/${encodeURIComponent(u.id)}`, { authToken: token! }) .then(full => setScope(full.scopedCampuses || [])) .catch(() => setScope(null)); }; const cancelEdit = () => { setEditingId(null); setEditData({}); setScope(null); }; const canBeScoped = editData.role === "staff" || editData.role === "supervisor"; // Active campuses, plus any archived one this person is still limited to. const scopeChoices = [...campusInfo.campuses.map(c => ({ id: c.id, name: c.name })), ...(scope || []).filter(s => !campusInfo.campuses.some(c => c.id === s.id)).map(s => ({ ...s, name: `${s.name} (archived)` }))]; const saveEdit = async () => { if (!editingId) return; try { setSaving(true); const payload: Partial & { password?: string; scopedCampusIds?: string[] } = { name: editData.name, email: editData.email, role: editData.role, phoneNumber: editData.phoneNumber || null, notificationPreference: editData.notificationPreference, isActive: editData.isActive, }; if (editData.password && editData.password.trim().length > 0) { payload.password = editData.password.trim(); } if (campusInfo.enabled && canBeScoped && scope) payload.scopedCampusIds = scope.map(c => c.id); await apiFetch(`/api/users/${encodeURIComponent(editingId)}`, { method: "PUT", authToken: token!, body: payload, }); setEditingId(null); setEditData({}); await loadUsers(page); } catch (e) { setError(errorMessage(e) || "Failed to save user"); } finally { setSaving(false); } }; const revokeUserSessions = async (id: string, name: string) => { if (!confirm(`Revoke all active sessions for ${name}? They will be signed out on all devices.`)) return; try { await apiFetch(`/api/users/${encodeURIComponent(id)}/revoke-sessions`, { method: "POST", authToken: token! }); } catch (e) { setError(errorMessage(e) || "Failed to revoke sessions"); } }; const [impTarget, setImpTarget] = useState<{ id: string; name: string } | null>(null); const [impReason, setImpReason] = useState(""); const [impBusy, setImpBusy] = useState(false); const [impError, setImpError] = useState(null); const startImpersonation = async () => { if (!impTarget || !token) return; setImpBusy(true); setImpError(null); try { const res = await apiFetch(`/api/admin/impersonate/${encodeURIComponent(impTarget.id)}`, { method: "POST", authToken: token, body: { reason: impReason } }); beginImpersonation(res); } catch (e) { setImpError(errorMessage(e) || "Couldn't start impersonation"); setImpBusy(false); } }; const resetTwoFactor = async (id: string, name: string, role: string) => { // Admins and supervisors can't go without 2FA: a reset just makes them set it up // again (on a channel that works) at their next login. const message = role === "admin" || role === "supervisor" ? `Reset two-factor authentication for ${name}? Their sessions end, and they'll set it up again with a new code at their next login.` : `Turn off two-factor authentication for ${name}? They will be able to log in with just their password until they turn it back on.`; if (!confirm(message)) return; try { await apiFetch(`/api/users/${encodeURIComponent(id)}`, { method: "PUT", authToken: token!, body: { twoFactorEnabled: false } }); await loadUsers(page); } catch (e) { setError(errorMessage(e) || "Failed to reset two-factor authentication"); } }; const deactivate = async (id: string) => { if (!confirm("Deactivate this user? Their account will be disabled.")) return; try { await apiFetch(`/api/users/${encodeURIComponent(id)}`, { method: "DELETE", authToken: token! }); await loadUsers(page); } catch (e) { setError(errorMessage(e) || "Failed to deactivate user"); } }; const deleteUserData = async (id: string, name: string) => { if (!confirm(`Delete personal data for "${name}"?\n\nThis will set their name to "Deleted User", clear their email and phone number, and deactivate the account. This action cannot be undone.`)) return; try { await apiFetch(`/api/users/${encodeURIComponent(id)}/anonymize`, { method: "POST", authToken: token! }); await loadUsers(page); } catch (e) { setError(errorMessage(e) || "Failed to delete user data"); } }; const impersonateModal = impTarget && (
!impBusy && setImpTarget(null)}>
e.stopPropagation()}>

View as {impTarget.name}

You'll see the site exactly as they do, for up to 30 minutes. It's strictly read-only: nothing can be registered, paid, changed or sent. The session, your reason and every page you open are recorded in the audit log.