259 lines
16 KiB
TypeScript
259 lines
16 KiB
TypeScript
import React, { useEffect, useMemo, useState } from 'react';
|
|
import { Download, Loader2, RefreshCw, ScrollText, ShieldCheck, UserCheck, UserX, Users } from 'lucide-react';
|
|
import { adminApi, AuditEntry, ManagedUser, ManagedUserDetail, PlatformAnalytics } from '../services/api';
|
|
import { useAuth } from '../context/AuthContext';
|
|
import { useToast } from '../context/ToastContext';
|
|
import { useNavigate } from 'react-router-dom';
|
|
|
|
const roleLabel: Record<ManagedUser['role'], string> = {
|
|
admin: 'Superadmin',
|
|
instructor: 'Instrutor',
|
|
student: 'Aluno',
|
|
};
|
|
|
|
export const SuperAdmin: React.FC = () => {
|
|
const { user } = useAuth();
|
|
const { showToast } = useToast();
|
|
const navigate = useNavigate();
|
|
const [users, setUsers] = useState<ManagedUser[]>([]);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const [updatingUserId, setUpdatingUserId] = useState<string | null>(null);
|
|
const [query, setQuery] = useState('');
|
|
const [analytics, setAnalytics] = useState<PlatformAnalytics | null>(null);
|
|
const [inviteEmail, setInviteEmail] = useState('');
|
|
const [inviteRole, setInviteRole] = useState<'student' | 'instructor'>('student');
|
|
const [accessLink, setAccessLink] = useState('');
|
|
const [selectedUser, setSelectedUser] = useState<ManagedUserDetail | null>(null);
|
|
const [loadingDetailId, setLoadingDetailId] = useState<string | null>(null);
|
|
const [auditEntries, setAuditEntries] = useState<AuditEntry[]>([]);
|
|
|
|
const loadUsers = async () => {
|
|
setIsLoading(true);
|
|
try {
|
|
const [response, dashboard, auditLog] = await Promise.all([adminApi.listUsers(), adminApi.dashboard(), adminApi.auditLog()]);
|
|
setUsers(response.data);
|
|
setAnalytics(dashboard.data);
|
|
setAuditEntries(auditLog.data);
|
|
} catch {
|
|
showToast('Não foi possível carregar os usuários.', 'error');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
void loadUsers();
|
|
}, []);
|
|
|
|
const filteredUsers = useMemo(() => {
|
|
const normalized = query.trim().toLowerCase();
|
|
if (!normalized) return users;
|
|
return users.filter((account) =>
|
|
account.name.toLowerCase().includes(normalized) || account.email.toLowerCase().includes(normalized),
|
|
);
|
|
}, [query, users]);
|
|
|
|
const updateUser = async (account: ManagedUser, update: Partial<Pick<ManagedUser, 'role' | 'isActive'>>) => {
|
|
setUpdatingUserId(account.id);
|
|
try {
|
|
const response = await adminApi.updateUser(account.id, update);
|
|
setUsers((current) => current.map((item) => item.id === account.id ? response.data : item));
|
|
showToast('Usuário atualizado.', 'success');
|
|
} catch {
|
|
showToast('Não foi possível atualizar este usuário.', 'error');
|
|
} finally {
|
|
setUpdatingUserId(null);
|
|
}
|
|
};
|
|
|
|
const activeUsers = users.filter((account) => account.isActive).length;
|
|
const instructorUsers = users.filter((account) => account.role === 'instructor' && account.isActive).length;
|
|
const createInvite = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
try {
|
|
const response = await adminApi.invite(inviteEmail, inviteRole);
|
|
setAccessLink(response.data.inviteUrl); setInviteEmail(''); showToast('Link de convite criado.', 'success');
|
|
} catch { showToast('Não foi possível criar o convite.', 'error'); }
|
|
};
|
|
const resetPassword = async (account: ManagedUser) => {
|
|
try { const response = await adminApi.passwordReset(account.id); setAccessLink(response.data.resetUrl); showToast('Link de redefinição criado.', 'success'); }
|
|
catch { showToast('Não foi possível criar o link.', 'error'); }
|
|
};
|
|
const showUserDetail = async (account: ManagedUser) => {
|
|
setLoadingDetailId(account.id);
|
|
try {
|
|
const response = await adminApi.userDetail(account.id);
|
|
setSelectedUser(response.data);
|
|
} catch {
|
|
showToast('Não foi possível carregar os detalhes do usuário.', 'error');
|
|
} finally {
|
|
setLoadingDetailId(null);
|
|
}
|
|
};
|
|
const exportUsers = () => {
|
|
const csv = ['Nome,E-mail,Perfil,Status,Cadastro', ...filteredUsers.map((account) => [account.name, account.email, roleLabel[account.role], account.isActive ? 'Ativo' : 'Desativado', new Intl.DateTimeFormat('pt-BR').format(new Date(account.createdAt))].map((value) => `"${value.replaceAll('"', '""')}"`).join(','))].join('\n');
|
|
const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
|
|
const link = document.createElement('a'); link.href = url; link.download = 'usuarios-compor-hub.csv'; link.click(); URL.revokeObjectURL(url);
|
|
};
|
|
const auditLabel: Record<string, string> = { 'invitation.created': 'Convite criado', 'password_reset.created': 'Redefinição de senha criada', 'user.updated': 'Usuário atualizado', 'course.published': 'Curso publicado', 'course.drafted': 'Rascunho salvo', 'course.archived': 'Curso arquivado', 'comment.replied': 'Comentário respondido', 'comment.deleted': 'Comentário removido' };
|
|
|
|
return (
|
|
<main className="min-h-screen pt-28 pb-20 px-6 md:px-12 max-w-[1440px] mx-auto">
|
|
<div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-10">
|
|
<div>
|
|
<div className="flex items-center gap-2 text-orange-400 text-xs font-bold uppercase tracking-wider mb-3">
|
|
<ShieldCheck className="w-4 h-4" /> Superadmin
|
|
</div>
|
|
<h1 className="text-3xl md:text-4xl font-bold text-white">Painel Administrativo</h1>
|
|
<p className="text-gray-400 mt-2">Gerencie os acessos da plataforma. Cursos e aulas continuam no Painel do Instrutor.</p>
|
|
</div>
|
|
<div className="flex flex-wrap gap-3">
|
|
<button
|
|
onClick={() => navigate('/gerenciar')}
|
|
className="inline-flex items-center justify-center gap-2 rounded-full px-5 py-3 text-sm font-semibold bg-orange-500 hover:bg-orange-600 text-white transition-colors"
|
|
>
|
|
Gerenciar cursos
|
|
</button>
|
|
<button
|
|
onClick={() => void loadUsers()}
|
|
className="inline-flex items-center justify-center gap-2 rounded-full px-5 py-3 text-sm font-semibold bg-white/10 hover:bg-white/15 text-white transition-colors"
|
|
>
|
|
<RefreshCw className="w-4 h-4" /> Atualizar
|
|
</button>
|
|
<button onClick={exportUsers} className="inline-flex items-center justify-center gap-2 rounded-full px-5 py-3 text-sm font-semibold bg-white/10 hover:bg-white/15 text-white transition-colors"><Download className="w-4 h-4" /> Exportar CSV</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-5 gap-4 mb-8">
|
|
<StatCard icon={<Users className="w-5 h-5" />} label="Usuários cadastrados" value={analytics?.totalUsers ?? users.length} />
|
|
<StatCard icon={<UserCheck className="w-5 h-5" />} label="Contas ativas" value={analytics?.activeUsers ?? activeUsers} />
|
|
<StatCard icon={<ShieldCheck className="w-5 h-5" />} label="Instrutores ativos" value={instructorUsers} />
|
|
<StatCard icon={<Users className="w-5 h-5" />} label="Cursos publicados" value={analytics?.publishedCourses ?? 0} />
|
|
<StatCard icon={<UserCheck className="w-5 h-5" />} label="Aulas concluídas" value={analytics?.completedLessons ?? 0} />
|
|
</div>
|
|
|
|
<section className="rounded-2xl border border-white/10 bg-zinc-950/80 p-5 mb-8">
|
|
<h2 className="text-lg font-bold text-white mb-4">Convidar usuário</h2>
|
|
<form onSubmit={createInvite} className="flex flex-col md:flex-row gap-3">
|
|
<input required type="email" value={inviteEmail} onChange={(event) => setInviteEmail(event.target.value)} placeholder="E-mail do convidado" className="flex-1 rounded-xl bg-zinc-900 border border-white/10 px-4 py-2.5 text-sm text-white" />
|
|
<select value={inviteRole} onChange={(event) => setInviteRole(event.target.value as 'student' | 'instructor')} className="rounded-xl bg-zinc-900 border border-white/10 px-4 py-2.5 text-sm text-white"><option value="student">Aluno</option><option value="instructor">Instrutor</option></select>
|
|
<button className="rounded-xl bg-orange-500 hover:bg-orange-600 px-5 py-2.5 text-sm font-semibold text-white">Gerar convite</button>
|
|
</form>
|
|
{accessLink && <div className="mt-4 flex gap-2"><input readOnly value={accessLink} className="flex-1 rounded-xl bg-black border border-white/10 px-3 py-2 text-xs text-gray-300" /><button onClick={() => navigator.clipboard.writeText(accessLink)} className="rounded-xl bg-white/10 px-4 text-xs font-semibold">Copiar</button></div>}
|
|
</section>
|
|
|
|
{selectedUser && (
|
|
<section className="rounded-2xl border border-orange-500/30 bg-zinc-950/80 p-5 mb-8">
|
|
<div className="flex items-start justify-between gap-4">
|
|
<div>
|
|
<p className="text-xs uppercase tracking-wider text-orange-400 font-semibold">Detalhes do usuário</p>
|
|
<h2 className="text-lg font-bold text-white mt-1">{selectedUser.name}</h2>
|
|
<p className="text-sm text-gray-400">{selectedUser.email} · {roleLabel[selectedUser.role]}</p>
|
|
</div>
|
|
<button onClick={() => setSelectedUser(null)} className="text-xs text-gray-400 hover:text-white">Fechar</button>
|
|
</div>
|
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-5 text-sm">
|
|
<DetailMetric label="Aulas concluídas" value={selectedUser.completedLessons.toString()} />
|
|
<DetailMetric label="Última atividade" value={selectedUser.lastLearningAt ? new Intl.DateTimeFormat('pt-BR', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(selectedUser.lastLearningAt)) : 'Sem atividade'} />
|
|
<DetailMetric label="Status" value={selectedUser.isActive ? 'Ativo' : 'Desativado'} />
|
|
</div>
|
|
</section>
|
|
)}
|
|
|
|
<section className="rounded-2xl border border-white/10 bg-zinc-950/80 overflow-hidden">
|
|
<div className="p-5 border-b border-white/10 flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between">
|
|
<h2 className="text-lg font-bold text-white">Usuários</h2>
|
|
<input
|
|
value={query}
|
|
onChange={(event) => setQuery(event.target.value)}
|
|
placeholder="Buscar por nome ou e-mail"
|
|
className="w-full sm:w-80 rounded-xl bg-zinc-900 border border-white/10 px-4 py-2.5 text-sm text-white placeholder:text-gray-500 focus:outline-none focus:border-orange-500"
|
|
/>
|
|
</div>
|
|
|
|
{isLoading ? (
|
|
<div className="h-64 flex items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-orange-400" /></div>
|
|
) : filteredUsers.length === 0 ? (
|
|
<div className="h-48 flex items-center justify-center text-sm text-gray-500">Nenhum usuário encontrado.</div>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full min-w-[760px] text-left text-sm">
|
|
<thead className="bg-white/[0.03] text-xs uppercase tracking-wider text-gray-500">
|
|
<tr>
|
|
<th className="px-5 py-4">Usuário</th>
|
|
<th className="px-5 py-4">Perfil</th>
|
|
<th className="px-5 py-4">Status</th>
|
|
<th className="px-5 py-4">Cadastro</th>
|
|
<th className="px-5 py-4">Ações</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-white/5">
|
|
{filteredUsers.map((account) => {
|
|
const isCurrentUser = account.id === user?.id;
|
|
const isUpdating = updatingUserId === account.id;
|
|
return (
|
|
<tr key={account.id} className="text-gray-300">
|
|
<td className="px-5 py-4">
|
|
<div className="font-semibold text-white">{account.name}</div>
|
|
<div className="text-xs text-gray-500 mt-1">{account.email}</div>
|
|
</td>
|
|
<td className="px-5 py-4">
|
|
<select
|
|
value={account.role}
|
|
disabled={isCurrentUser || isUpdating}
|
|
onChange={(event) => void updateUser(account, { role: event.target.value as ManagedUser['role'] })}
|
|
className="rounded-lg bg-zinc-900 border border-white/10 px-3 py-2 text-xs text-white disabled:opacity-50"
|
|
>
|
|
{Object.entries(roleLabel).map(([role, label]) => <option key={role} value={role}>{label}</option>)}
|
|
</select>
|
|
</td>
|
|
<td className="px-5 py-4">
|
|
<button
|
|
disabled={isCurrentUser || isUpdating}
|
|
onClick={() => void updateUser(account, { isActive: !account.isActive })}
|
|
className={`inline-flex items-center gap-2 rounded-full px-3 py-2 text-xs font-semibold disabled:opacity-50 ${
|
|
account.isActive ? 'bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25' : 'bg-red-500/15 text-red-400 hover:bg-red-500/25'
|
|
}`}
|
|
>
|
|
{account.isActive ? <UserCheck className="w-3.5 h-3.5" /> : <UserX className="w-3.5 h-3.5" />}
|
|
{account.isActive ? 'Ativo' : 'Desativado'}
|
|
</button>
|
|
</td>
|
|
<td className="px-5 py-4 text-xs text-gray-500">{new Intl.DateTimeFormat('pt-BR').format(new Date(account.createdAt))}</td>
|
|
<td className="px-5 py-4">
|
|
<div className="flex items-center gap-3">
|
|
<button disabled={loadingDetailId === account.id} onClick={() => void showUserDetail(account)} className="text-xs font-semibold text-gray-300 hover:text-white disabled:opacity-50">{loadingDetailId === account.id ? 'Carregando...' : 'Detalhes'}</button>
|
|
<button disabled={isUpdating} onClick={() => void resetPassword(account)} className="text-xs font-semibold text-orange-400 hover:text-orange-300">Redefinir senha</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</section>
|
|
|
|
<section className="rounded-2xl border border-white/10 bg-zinc-950/80 overflow-hidden mt-8">
|
|
<div className="p-5 border-b border-white/10 flex items-center gap-2"><ScrollText className="w-5 h-5 text-orange-400" /><h2 className="text-lg font-bold text-white">Registro de atividades</h2></div>
|
|
{auditEntries.length === 0 ? <p className="px-5 py-10 text-sm text-gray-500">Nenhuma atividade administrativa registrada ainda.</p> : <div className="divide-y divide-white/5">{auditEntries.map((entry) => <div key={entry.id} className="p-4 flex flex-col sm:flex-row sm:items-center gap-1 sm:justify-between text-sm"><div><span className="font-semibold text-white">{auditLabel[entry.action] || entry.action}</span><span className="text-gray-500"> · {entry.actorName}</span></div><time className="text-xs text-gray-500">{new Intl.DateTimeFormat('pt-BR', { dateStyle: 'short', timeStyle: 'short' }).format(new Date(entry.createdAt))}</time></div>)}</div>}
|
|
</section>
|
|
</main>
|
|
);
|
|
};
|
|
|
|
const StatCard: React.FC<{ icon: React.ReactNode; label: string; value: number }> = ({ icon, label, value }) => (
|
|
<div className="rounded-2xl border border-white/10 bg-zinc-950/80 p-5">
|
|
<div className="flex items-center gap-2 text-orange-400 mb-3">{icon}<span className="text-xs font-semibold uppercase tracking-wider">{label}</span></div>
|
|
<div className="text-3xl font-bold text-white">{value}</div>
|
|
</div>
|
|
);
|
|
|
|
const DetailMetric: React.FC<{ label: string; value: string }> = ({ label, value }) => (
|
|
<div className="rounded-xl bg-white/[0.03] px-4 py-3">
|
|
<div className="text-xs text-gray-500">{label}</div>
|
|
<div className="text-sm font-semibold text-white mt-1">{value}</div>
|
|
</div>
|
|
);
|