import { useEffect, useRef, useState, type FormEvent } from "react";
import { Button, Input, Spinner } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
type AdminStats,
type AdminUser,
type AuditEntry,
type StorageLocation,
} from "../lib/api.js";
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
import {
ActivityIcon,
HardDriveIcon,
PlusIcon,
TrashIcon,
UsersIcon,
} from "../components/icons.js";
const GB = 1024 ** 3;
const MB = 1024 ** 2;
const messageOf = (caught: unknown, fallback: string): string =>
caught instanceof ApiError ? caught.message : fallback;
const toGb = (bytes: number): string =>
(bytes / GB).toLocaleString("fr-FR", { maximumFractionDigits: 1 });
const StatCard = ({ label, value }: { label: string; value: string }) => (
);
export const AdminUsers = () => {
const confirm = useConfirm();
const [users, setUsers] = useState(null);
const [stats, setStats] = useState(null);
const [q, setQ] = useState("");
const [error, setError] = useState(null);
const [busy, setBusy] = useState(null);
const [createOpen, setCreateOpen] = useState(false);
const [edit, setEdit] = useState(null);
const [credentials, setCredentials] = useState<{ email: string; password: string } | null>(null);
const termRef = useRef("");
const load = async (term: string) => {
termRef.current = term;
setError(null);
try {
const { users: list } = await api.adminUsers(term || undefined);
setUsers(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setUsers([]);
}
};
useEffect(() => {
void load("");
api
.adminStats()
.then(setStats)
.catch(() => undefined);
}, []);
const toggleActive = async (user: AdminUser) => {
setBusy(user.id);
setError(null);
try {
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, "Mise à jour impossible."));
} finally {
setBusy(null);
}
};
const resetPassword = async (user: AdminUser) => {
setBusy(user.id);
setError(null);
try {
const { password } = await api.adminResetPassword(user.id);
setCredentials({ email: user.email, password });
} catch (caught) {
setError(messageOf(caught, "Réinitialisation impossible."));
} finally {
setBusy(null);
}
};
const removeUser = async (user: AdminUser) => {
const ok = await confirm({
title: "Supprimer le membre",
message: (
<>
Supprimer définitivement {user.email}{" "}
ainsi que ses fichiers ? Cette action est irréversible.
>
),
confirmLabel: "Supprimer",
tone: "danger",
});
if (!ok) return;
setBusy(user.id);
setError(null);
try {
await api.adminDeleteUser(user.id);
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, "Suppression impossible."));
} finally {
setBusy(null);
}
};
return (
}
onClick={() => setCreateOpen(true)}
>
Nouveau membre
}
/>
{stats ? (
) : null}
{error ?
{error} : null}
{users === null ? (
) : users.length === 0 ? (
} title="Aucun membre" />
) : (
)}
{createOpen ? (
setCreateOpen(false)}
onCreated={(email, password) => {
setCreateOpen(false);
setCredentials({ email, password });
void load(termRef.current);
}}
/>
) : null}
{edit ? (
setEdit(null)}
onSaved={() => {
setEdit(null);
void load(termRef.current);
}}
/>
) : null}
setCredentials(null)} />
);
};
const CredentialsModal = ({
credentials,
onClose,
}: {
credentials: { email: string; password: string } | null;
onClose: () => void;
}) => {
if (!credentials) return null;
return (
Transmettez ces informations par un canal sûr : le mot de passe ne sera plus affiché.
- Adresse
- {credentials.email}
- Mot de passe
- {credentials.password}
);
};
const CreateUserDialog = ({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: (email: string, password: string) => void;
}) => {
const [email, setEmail] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [role, setRole] = useState("user");
const [quotaGb, setQuotaGb] = useState("");
const [maxFileMb, setMaxFileMb] = useState("");
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
const { user, password } = await api.adminCreateUser({
email: email.trim(),
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
max_file_bytes: maxFileMb ? Math.round(Number(maxFileMb) * MB) : null,
});
onCreated(user.email, password);
} catch (caught) {
setError(messageOf(caught, "Création impossible."));
} finally {
setBusy(false);
}
};
return (
);
};
const EditUserDialog = ({
user,
onClose,
onSaved,
}: {
user: AdminUser;
onClose: () => void;
onSaved: () => void;
}) => {
const [firstName, setFirstName] = useState(user.first_name);
const [lastName, setLastName] = useState(user.last_name);
const [role, setRole] = useState(user.role_slug);
const [quotaGb, setQuotaGb] = useState(String(Math.round(user.quota_bytes / GB)));
const [maxFileMb, setMaxFileMb] = useState(String(Math.round(user.max_file_bytes / MB)));
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
await api.adminUpdateUser(user.id, {
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
quota_bytes: Math.round(Number(quotaGb) * GB),
max_file_bytes: Math.round(Number(maxFileMb) * MB),
});
onSaved();
} catch (caught) {
setError(messageOf(caught, "Enregistrement impossible."));
} finally {
setBusy(false);
}
};
return (
);
};
export const AdminStorage = () => {
const [locations, setLocations] = useState(null);
const [error, setError] = useState(null);
const [createOpen, setCreateOpen] = useState(false);
const load = async () => {
setError(null);
try {
const { locations: list } = await api.adminStorageLocations();
setLocations(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setLocations([]);
}
};
useEffect(() => {
void load();
}, []);
const toggle = async (location: StorageLocation) => {
setError(null);
try {
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await load();
} catch (caught) {
setError(messageOf(caught, "Mise à jour impossible."));
}
};
return (
}
onClick={() => setCreateOpen(true)}
>
Nouvel emplacement
}
/>
{error ?
{error} : null}
{locations === null ? (
) : locations.length === 0 ? (
} title="Aucun emplacement" />
) : (
{locations.map((location) => (
-
{location.name}
{!location.is_active ? Inactif : null}
{location.slug} · {location.mount_path} ·{" "}
{location.quota_bytes
? `${toGb(location.used_bytes)} / ${toGb(location.quota_bytes)} Go`
: `${toGb(location.used_bytes)} Go utilisés`}
))}
)}
{createOpen ? (
setCreateOpen(false)}
onCreated={() => {
setCreateOpen(false);
void load();
}}
/>
) : null}
);
};
const CreateLocationDialog = ({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: () => void;
}) => {
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
const [mountPath, setMountPath] = useState("");
const [quotaGb, setQuotaGb] = useState("");
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
await api.adminCreateStorageLocation({
name: name.trim(),
slug: slug.trim(),
mount_path: mountPath.trim(),
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
});
onCreated();
} catch (caught) {
setError(messageOf(caught, "Création impossible."));
} finally {
setBusy(false);
}
};
return (
);
};
export const AdminAudit = () => {
const [entries, setEntries] = useState(null);
const [action, setAction] = useState("");
const [error, setError] = useState(null);
const [loadingMore, setLoadingMore] = useState(false);
const load = async (term: string) => {
setError(null);
try {
const { entries: list } = await api.adminAudit(100, 0, term || undefined);
setEntries(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setEntries([]);
}
};
useEffect(() => {
void load("");
}, []);
const loadMore = async () => {
if (!entries) return;
setLoadingMore(true);
setError(null);
try {
const { entries: more } = await api.adminAudit(100, entries.length, action || undefined);
setEntries((previous) => [...(previous ?? []), ...more]);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
} finally {
setLoadingMore(false);
}
};
return (
{error ?
{error} : null}
{entries === null ? (
) : entries.length === 0 ? (
} title="Aucune entrée" />
) : (
<>
{entries.map((entry) => (
-
{entry.action}
{entry.resource}
{entry.resource_id ? ` · ${entry.resource_id}` : ""}
{entry.user_email ?? "système"} · {formatDate(entry.created_at)}
{entry.ip_address ? ` · ${entry.ip_address}` : ""}
))}
{entries.length >= 100 ? (
) : null}
>
)}
);
};