Files
ToBePlayed-Frontend/src/pages/AdminUsersPage.jsx
T

221 lines
11 KiB
React

import {useCallback, useEffect, useRef, useState} from 'react';
import {useTranslation} from 'react-i18next';
import {Ban, ChevronLeft, ChevronRight, Loader2, Search, ShieldCheck, Trash2} from 'lucide-react';
import {toast} from 'sonner';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import PageContainer from '../components/PageContainer.jsx';
import {deleteUser, fetchUsers, setUserBlocked} from '../utils/admin.js';
const PAGE_SIZE = 20;
const REFUSAL_KEY = {
SELF_ACTION: 'ADMIN.ERROR_SELF_ACTION',
TARGET_IS_ADMIN: 'ADMIN.ERROR_TARGET_IS_ADMIN',
ALREADY_DELETED: 'ADMIN.ERROR_ALREADY_DELETED',
};
const formatDate = (value, locale) => (value ? new Date(value).toLocaleDateString(locale) : null);
/**
* PLATFORM_ADMIN only: list, block and delete users. Auth checks the role; a 403 shows "no access".
*/
export default function AdminUsersPage() {
const {t, i18n} = useTranslation();
const [query, setQuery] = useState('');
const [search, setSearch] = useState('');
const [page, setPage] = useState(0);
const [result, setResult] = useState(null);
const [status, setStatus] = useState('loading');
// {kind: 'block' | 'delete', user}
const [pending, setPending] = useState(null);
const [typedEmail, setTypedEmail] = useState('');
const [busy, setBusy] = useState(false);
// Only the newest load may show its answer: a slow answer to an older search must not replace the list.
const loadCount = useRef(0);
const load = useCallback(async () => {
const current = ++loadCount.current;
try {
const response = await fetchUsers(search, page, PAGE_SIZE);
if (current !== loadCount.current) return;
if (response.status === 401) return;
if (response.status === 403) {
setStatus('forbidden');
return;
}
if (!response.ok) {
setStatus('error');
return;
}
const data = await response.json();
if (current !== loadCount.current) return;
setResult(data);
setStatus('ready');
} catch (err) {
console.error('Admin users error:', err);
setStatus('error');
}
}, [search, page]);
useEffect(() => {
load();
}, [load]);
const closeDialog = () => {
setPending(null);
setTypedEmail('');
};
const confirm = async () => {
const {kind, user} = pending;
setBusy(true);
try {
const response = kind === 'delete' ? await deleteUser(user.id) : await setUserBlocked(user.id, !user.blocked);
if (response.status === 401) return;
if (response.ok) {
toast.success(t(kind === 'delete' ? 'ADMIN.DONE_DELETE' : user.blocked ? 'ADMIN.DONE_UNBLOCK' : 'ADMIN.DONE_BLOCK'));
closeDialog();
await load();
} else {
const data = await response.json().catch(() => ({}));
toast.error(t(REFUSAL_KEY[data.code] ?? 'ADMIN.ERROR'));
}
} catch (err) {
console.error('Admin action error:', err);
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
} finally {
setBusy(false);
}
};
const submitSearch = (event) => {
event.preventDefault();
setPage(0);
setSearch(query.trim());
};
const confirmDisabled = busy || (pending?.kind === 'delete'
&& typedEmail.trim().toLowerCase() !== pending.user.email.toLowerCase());
return (
<PageContainer className="space-y-4 px-4 py-6 md:px-8">
<Card>
<CardHeader>
<CardTitle>{t('ADMIN.TITLE')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{status === 'forbidden' && <p className="text-sm text-muted-foreground">{t('ADMIN.NO_ACCESS')}</p>}
{status === 'error' && <p className="text-sm text-destructive">{t('ADMIN.LOAD_ERROR')}</p>}
{status !== 'forbidden' && (
<form onSubmit={submitSearch} className="flex gap-2">
<Input aria-label={t('ADMIN.SEARCH')} placeholder={t('ADMIN.SEARCH')} value={query}
onChange={(event) => setQuery(event.target.value)}/>
<Button type="submit" variant="outline" size="icon" aria-label={t('ADMIN.SEARCH')}><Search/></Button>
</form>
)}
{status === 'loading' && <Loader2 className="size-5 animate-spin text-muted-foreground"/>}
{status === 'ready' && result.content.length === 0 && (
<p className="text-sm text-muted-foreground">{t('ADMIN.EMPTY')}</p>
)}
{status === 'ready' && result.content.length > 0 && (
<ul className="divide-y">
{result.content.map((user) => (
<li key={user.id} className="flex flex-wrap items-center gap-3 py-3">
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{user.email}</p>
<p className="truncate text-xs text-muted-foreground">
{[user.displayName,
t('ADMIN.REGISTERED', {date: formatDate(user.registrationDate, i18n.language)}),
t('ADMIN.LAST_LOGIN', {date: formatDate(user.lastLoginDate, i18n.language) ?? t('ADMIN.NEVER')}),
].filter(Boolean).join(' · ')}
</p>
</div>
<div className="flex flex-wrap items-center gap-1">
{user.role !== 'USER' && <Badge variant="outline">{t(`ROLES.${user.role}`)}</Badge>}
{user.steamLinked && <Badge variant="secondary">{t('ADMIN.STEAM')}</Badge>}
{user.blocked && <Badge variant="destructive">{t('ADMIN.BLOCKED')}</Badge>}
{user.deletedAt && <Badge variant="destructive">{t('ADMIN.DELETED')}</Badge>}
</div>
{user.role !== 'PLATFORM_ADMIN' && !user.deletedAt && (
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm"
onClick={() => setPending({kind: 'block', user})}>
{user.blocked ? <ShieldCheck/> : <Ban/>}
{t(user.blocked ? 'ADMIN.UNBLOCK' : 'ADMIN.BLOCK')}
</Button>
<Button type="button" variant="outline" size="sm" className="border-destructive text-destructive"
onClick={() => setPending({kind: 'delete', user})}>
<Trash2/>{t('ADMIN.DELETE')}
</Button>
</div>
)}
</li>
))}
</ul>
)}
{status === 'ready' && result.totalPages > 1 && (
<div className="flex items-center justify-between gap-2 text-sm">
<Button type="button" variant="outline" size="sm" disabled={page === 0}
onClick={() => setPage(page - 1)}>
<ChevronLeft/>{t('ADMIN.PREVIOUS')}
</Button>
<span>{t('ADMIN.PAGE_OF', {current: page + 1, total: result.totalPages})}</span>
<Button type="button" variant="outline" size="sm" disabled={page + 1 >= result.totalPages}
onClick={() => setPage(page + 1)}>
{t('ADMIN.NEXT')}<ChevronRight/>
</Button>
</div>
)}
</CardContent>
</Card>
<Dialog open={!!pending} onOpenChange={(open) => { if (!open) closeDialog(); }}>
{pending && (
<DialogContent>
<DialogHeader>
<DialogTitle>
{pending.kind === 'delete'
? t('ADMIN.DELETE_TITLE', {email: pending.user.email})
: pending.user.blocked ? t('ADMIN.UNBLOCK') : t('ADMIN.BLOCK_TITLE', {email: pending.user.email})}
</DialogTitle>
<DialogDescription>
{pending.kind === 'delete' ? t('ADMIN.DELETE_TEXT') : pending.user.blocked ? pending.user.email : t('ADMIN.BLOCK_TEXT')}
</DialogDescription>
</DialogHeader>
{pending.kind === 'delete' && (
<div className="space-y-2">
<Label htmlFor="adminDeleteEmail">{t('ADMIN.TYPE_EMAIL')}</Label>
<Input id="adminDeleteEmail" autoComplete="off" value={typedEmail}
onChange={(event) => setTypedEmail(event.target.value)}/>
</div>
)}
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">{t('ADMIN.CANCEL')}</Button>
</DialogClose>
<Button type="button" variant={pending.kind === 'delete' ? 'destructive' : 'default'}
disabled={confirmDisabled} onClick={confirm}>
{busy && <Loader2 className="animate-spin"/>}
{t(pending.kind === 'delete' ? 'ADMIN.DELETE' : pending.user.blocked ? 'ADMIN.UNBLOCK' : 'ADMIN.BLOCK')}
</Button>
</DialogFooter>
</DialogContent>
)}
</Dialog>
</PageContainer>
);
}