Files
compor-academy/pages/SuperAdmin.tsx
Cauê Faleiros 9b6fea4b81
All checks were successful
CI / Validate frontend and API (push) Successful in 1m58s
CI / Build and publish Docker images (push) Successful in 22s
feat: complete platform operations roadmap
2026-09-04 10:07:07 -03:00

343 lines
24 KiB
TypeScript

import React, { useEffect, useMemo, useState } from 'react';
import { ChevronDown, ChevronUp, 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 [auditQuery, setAuditQuery] = useState('');
const [categories, setCategories] = useState<Array<{ id: string; name: string; position: number; isActive: boolean }>>([]);
const [newCategory, setNewCategory] = useState('');
const [homeConfiguration, setHomeConfiguration] = useState<{ featuredCourseId: string | null; courseOrder: string[]; defaultCoverImageUrl: string | null; courses: Array<{ id: string; title: string; status: string }> } | null>(null);
const loadUsers = async () => {
setIsLoading(true);
try {
const [response, dashboard, auditLog, categoryResponse, homeResponse] = await Promise.all([adminApi.listUsers(), adminApi.dashboard(), adminApi.auditLog(), adminApi.categories(), adminApi.homeConfiguration()]);
setUsers(response.data);
setAnalytics(dashboard.data);
setAuditEntries(auditLog.data);
setCategories(categoryResponse.data);
setHomeConfiguration(homeResponse.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 filteredAuditEntries = useMemo(() => {
const normalized = auditQuery.trim().toLowerCase();
if (!normalized) return auditEntries;
return auditEntries.filter((entry) => `${entry.action} ${entry.actorName} ${entry.subjectType}`.toLowerCase().includes(normalized));
}, [auditEntries, auditQuery]);
const homeCourses = useMemo(() => {
if (!homeConfiguration) return [];
const order = new Map<string, number>(homeConfiguration.courseOrder.map((id, index) => [id, index]));
return homeConfiguration.courses.filter((course) => course.status === 'published').sort((a, b) => (order.get(a.id) ?? 999_999) - (order.get(b.id) ?? 999_999) || a.title.localeCompare(b.title));
}, [homeConfiguration]);
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 createCategory = async (event: React.FormEvent) => {
event.preventDefault();
if (!newCategory.trim()) return;
try {
const response = await adminApi.createCategory(newCategory.trim());
setCategories((current) => [...current, response.data].sort((a, b) => a.position - b.position || a.name.localeCompare(b.name)));
setNewCategory('');
showToast('Categoria criada.', 'success');
} catch { showToast('Não foi possível criar esta categoria. Ela pode já existir.', 'error'); }
};
const toggleCategory = async (category: { id: string; name: string; position: number; isActive: boolean }) => {
try {
const response = await adminApi.updateCategory(category.id, { name: category.name, isActive: !category.isActive });
setCategories((current) => current.map((item) => item.id === category.id ? response.data : item));
} catch { showToast('Não foi possível atualizar a categoria.', 'error'); }
};
const saveHomeConfiguration = async () => {
if (!homeConfiguration) return;
try {
await adminApi.updateHomeConfiguration({ featuredCourseId: homeConfiguration.featuredCourseId, courseOrder: homeConfiguration.courseOrder, defaultCoverImageUrl: homeConfiguration.defaultCoverImageUrl || null });
showToast('Configuração da página inicial salva.', 'success');
} catch { showToast('Não foi possível salvar a configuração inicial.', 'error'); }
};
const moveHomeCourse = (courseId: string, direction: -1 | 1) => {
setHomeConfiguration((current) => {
if (!current) return current;
const published = current.courses.filter((course) => course.status === 'published');
const order = new Map<string, number>(current.courseOrder.map((id, index) => [id, index]));
const arranged = [...published].sort((a, b) => (order.get(a.id) ?? 999_999) - (order.get(b.id) ?? 999_999) || a.title.localeCompare(b.title));
const index = arranged.findIndex((course) => course.id === courseId);
const target = index + direction;
if (index < 0 || target < 0 || target >= arranged.length) return current;
[arranged[index], arranged[target]] = [arranged[target], arranged[index]];
return { ...current, courseOrder: arranged.map((course) => course.id) };
});
};
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 exportAudit = () => {
const csv = ['Data,Ação,Responsável,Tipo', ...filteredAuditEntries.map((entry) => [new Date(entry.createdAt).toISOString(), entry.action, entry.actorName, entry.subjectType].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 = 'registro-de-atividades-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>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
<section className="rounded-2xl border border-white/10 bg-zinc-950/80 p-5">
<h2 className="text-lg font-bold text-white mb-1">Categorias de cursos</h2>
<p className="text-xs text-gray-500 mb-4">Estas opções aparecem no editor de cursos e na biblioteca.</p>
<form onSubmit={createCategory} className="flex gap-2 mb-4">
<input value={newCategory} onChange={(event) => setNewCategory(event.target.value)} placeholder="Nova categoria" className="min-w-0 flex-1 rounded-xl bg-zinc-900 border border-white/10 px-3 py-2 text-sm text-white" />
<button className="rounded-xl bg-orange-500 hover:bg-orange-600 px-4 text-sm font-semibold text-white">Adicionar</button>
</form>
<div className="space-y-2 max-h-56 overflow-y-auto pr-1">
{categories.map((category) => <div key={category.id} className="flex items-center justify-between gap-3 rounded-xl bg-white/[0.03] px-3 py-2 text-sm"><span className={category.isActive ? 'text-gray-200' : 'text-gray-600 line-through'}>{category.name}</span><button onClick={() => void toggleCategory(category)} className={`rounded-full px-3 py-1 text-xs font-semibold ${category.isActive ? 'bg-emerald-500/15 text-emerald-400' : 'bg-white/10 text-gray-400'}`}>{category.isActive ? 'Ativa' : 'Inativa'}</button></div>)}
</div>
</section>
<section className="rounded-2xl border border-white/10 bg-zinc-950/80 p-5">
<h2 className="text-lg font-bold text-white mb-1">Página inicial</h2>
<p className="text-xs text-gray-500 mb-4">Defina o curso em destaque e a imagem padrão quando um curso não tem capa.</p>
{homeConfiguration && <div className="space-y-3">
<select value={homeConfiguration.featuredCourseId || ''} onChange={(event) => setHomeConfiguration((current) => current ? { ...current, featuredCourseId: event.target.value || null } : current)} className="w-full rounded-xl bg-zinc-900 border border-white/10 px-3 py-2 text-sm text-white"><option value="">Nenhum curso em destaque</option>{homeConfiguration.courses.filter((course) => course.status === 'published').map((course) => <option key={course.id} value={course.id}>{course.title}</option>)}</select>
<input value={homeConfiguration.defaultCoverImageUrl || ''} onChange={(event) => setHomeConfiguration((current) => current ? { ...current, defaultCoverImageUrl: event.target.value || null } : current)} placeholder="URL da capa padrão (opcional)" className="w-full rounded-xl bg-zinc-900 border border-white/10 px-3 py-2 text-sm text-white" />
<div className="max-h-32 space-y-1 overflow-y-auto rounded-xl bg-black/20 p-2">
{homeCourses.map((course, index) => <div key={course.id} className="flex items-center gap-2 text-xs text-gray-300"><span className="flex-1 truncate">{index + 1}. {course.title}</span><button onClick={() => moveHomeCourse(course.id, -1)} disabled={index === 0} className="p-1 disabled:opacity-30"><ChevronUp className="w-3.5 h-3.5" /></button><button onClick={() => moveHomeCourse(course.id, 1)} disabled={index === homeCourses.length - 1} className="p-1 disabled:opacity-30"><ChevronDown className="w-3.5 h-3.5" /></button></div>)}
</div>
<button onClick={() => void saveHomeConfiguration()} className="rounded-xl bg-white/10 hover:bg-white/15 px-4 py-2 text-sm font-semibold text-white">Salvar página inicial</button>
</div>}
</section>
</div>
{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 flex-col sm:flex-row gap-3 sm:items-center sm:justify-between"><div className="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><div className="flex gap-2"><input value={auditQuery} onChange={(event) => setAuditQuery(event.target.value)} placeholder="Filtrar registro" className="min-w-0 rounded-xl bg-zinc-900 border border-white/10 px-3 py-2 text-xs text-white" /><button onClick={exportAudit} className="rounded-xl bg-white/10 px-3 text-xs font-semibold text-white">CSV</button></div></div>
{filteredAuditEntries.length === 0 ? <p className="px-5 py-10 text-sm text-gray-500">Nenhuma atividade administrativa encontrada.</p> : <div className="divide-y divide-white/5">{filteredAuditEntries.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>
);