"use client"; import { useCallback, useEffect, useState } from "react"; import { authFetch, getApiBase } from "../lib/auth"; import { FEATURES, type Feature, type FeatureAccess } from "../lib/features"; type Account = { username: string; role: string; features: FeatureAccess }; export default function FeatureControls({ username, onSaved }: { username?: string; onSaved: () => void }) { const [accounts, setAccounts] = useState(null); const [changes, setChanges] = useState>({}); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); const [error, setError] = useState(""); const load = useCallback(async () => { const response = await authFetch( `${getApiBase()}/admin/users/${username ? encodeURIComponent(username) : "summary"}`, ); if (!response.ok) throw new Error("Could not load feature permissions."); const data = await response.json(); setAccounts(username ? [data.user] : data.users.filter((user: Account) => user.role !== "admin")); }, [username]); useEffect(() => { void load().catch((err) => setError(err.message)); }, [load]); const save = async () => { setBusy(true); setError(""); setMessage(""); try { const response = await authFetch( `${getApiBase()}/admin/users/${username ? `${encodeURIComponent(username)}/features` : "features/bulk"}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(changes), }, ); if (!response.ok) throw new Error((await response.json()).detail || "Could not save permissions."); const result = await response.json(); setChanges({}); setMessage(username ? "Feature access saved." : `Feature access saved for ${result.updated} non-admin accounts.`); await load(); onSaved(); } catch (err) { setError(err instanceof Error ? err.message : "Could not save permissions."); } finally { setBusy(false); } }; const admin = accounts?.some((account) => account.role === "admin"); return (

Feature access

{username ? "Choose which features this person can use in Magent." : "Apply feature access to every existing non-admin account, including users outside the current search. Only the checkboxes you change will be applied."}

{admin ? "Administrators always have access to all features." : "Changes take effect on the next page or API request. These permissions control Magent access; linked services keep their own permissions."}

{!accounts && !error &&

Loading permissions...

} {FEATURES.map(({ key, label, description }) => { const enabled = accounts?.filter((account) => account.features?.[key]).length ?? 0; const mixed = !!accounts?.length && enabled > 0 && enabled < accounts.length; const changed = Object.hasOwn(changes, key); return ( ); })} {error && (

{error}

)} {message && (

{message}

)}
); }