feat: expand admin and instructor tools
This commit is contained in:
24
pages/AccessTokenPage.tsx
Normal file
24
pages/AccessTokenPage.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { authApi, saveSession } from '../services/api';
|
||||
|
||||
export const AccessTokenPage: React.FC<{ mode: 'invite' | 'reset' }> = ({ mode }) => {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const token = new URLSearchParams(location.search).get('token') || '';
|
||||
const [name, setName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const submit = async (event: React.FormEvent) => {
|
||||
event.preventDefault(); setSaving(true); setError('');
|
||||
try {
|
||||
if (mode === 'invite') {
|
||||
const session = await authApi.acceptInvitation(token, name, password);
|
||||
saveSession(session); navigate(session.user.role === 'admin' ? '/admin' : session.user.role === 'instructor' ? '/gerenciar' : '/');
|
||||
} else { await authApi.resetPassword(token, password); navigate('/'); }
|
||||
} catch { setError('Este link é inválido, expirou ou não pôde ser usado.'); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
return <main className="min-h-screen pt-32 px-6 flex justify-center"><form onSubmit={submit} className="w-full max-w-md rounded-2xl border border-white/10 bg-zinc-950 p-7 space-y-4"><h1 className="text-2xl font-bold">{mode === 'invite' ? 'Criar seu acesso' : 'Redefinir senha'}</h1>{mode === 'invite' && <input required value={name} onChange={(event) => setName(event.target.value)} placeholder="Seu nome" className="w-full rounded-xl bg-zinc-900 p-3" />}<input required minLength={12} type="password" value={password} onChange={(event) => setPassword(event.target.value)} placeholder="Nova senha (mínimo 12 caracteres)" className="w-full rounded-xl bg-zinc-900 p-3" />{error && <p className="text-sm text-red-400">{error}</p>}<button disabled={!token || saving} className="w-full rounded-xl bg-orange-500 p-3 font-semibold">{saving ? 'Salvando...' : mode === 'invite' ? 'Criar conta' : 'Redefinir senha'}</button></form></main>;
|
||||
};
|
||||
@@ -27,9 +27,10 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { Course, Comment, Attachment, Lesson, AttachmentType } from '../types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { getManagedCourses, saveCourse, deleteCourse, getComments, saveComment } from '../services/db';
|
||||
import { getManagedCourses, saveCourse, deleteCourse, getComments, replyToComment, moderateComment } from '../services/db';
|
||||
import { CATEGORIES } from '../constants';
|
||||
import { getAttachmentIcon, getAttachmentBadge } from '../components/MaterialCard';
|
||||
import { instructorApi, InstructorAnalytics } from '../services/api';
|
||||
|
||||
// 1. Create/Edit Course Modal
|
||||
const CourseModal: React.FC<{
|
||||
@@ -525,6 +526,7 @@ export const ManageCourses: React.FC = () => {
|
||||
const [allComments, setAllComments] = useState<{comment: Comment, courseTitle: string}[]>([]);
|
||||
const [replyingTo, setReplyingTo] = useState<string | null>(null);
|
||||
const [replyText, setReplyText] = useState('');
|
||||
const [analytics, setAnalytics] = useState<InstructorAnalytics | null>(null);
|
||||
|
||||
const { showToast } = useToast();
|
||||
|
||||
@@ -532,6 +534,8 @@ export const ManageCourses: React.FC = () => {
|
||||
setLoading(true);
|
||||
const data = await getManagedCourses();
|
||||
setCourses(data);
|
||||
const analyticsResponse = await instructorApi.analytics();
|
||||
setAnalytics(analyticsResponse.data);
|
||||
|
||||
// Load all comments
|
||||
const commentsAccumulator: {comment: Comment, courseTitle: string}[] = [];
|
||||
@@ -578,12 +582,7 @@ export const ManageCourses: React.FC = () => {
|
||||
|
||||
const target = allComments.find(c => c.comment.id === commentId);
|
||||
if (target) {
|
||||
const updatedComment: Comment = {
|
||||
...target.comment,
|
||||
reply: replyText,
|
||||
replyDate: new Date().toLocaleDateString('pt-BR')
|
||||
};
|
||||
await saveComment(updatedComment);
|
||||
await replyToComment(commentId, replyText);
|
||||
showToast('Resposta enviada com sucesso!', 'success');
|
||||
setReplyingTo(null);
|
||||
setReplyText('');
|
||||
@@ -591,8 +590,17 @@ export const ManageCourses: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleModerateComment = async (commentId: string) => {
|
||||
if (!window.confirm('Remover este comentário permanentemente?')) return;
|
||||
await moderateComment(commentId);
|
||||
showToast('Comentário removido.', 'success');
|
||||
loadData();
|
||||
};
|
||||
|
||||
// Metrics
|
||||
const totalViews = courses.reduce((acc, c) => acc + (c.views || 0), 0);
|
||||
const totalLearners = analytics?.learners ?? 0;
|
||||
const completedLessons = analytics?.completedLessons ?? 0;
|
||||
const totalQuestions = analytics?.comments ?? allComments.length;
|
||||
const totalLessons = courses.reduce((acc, c) => acc + c.lessons.length, 0);
|
||||
const totalMaterials = courses.reduce((acc, c) => {
|
||||
const globalCount = c.attachments?.length || 0;
|
||||
@@ -631,7 +639,7 @@ export const ManageCourses: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* Metrics Row */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 my-8">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 my-8">
|
||||
<div className="bg-zinc-900/60 border border-white/10 p-5 rounded-[8px] shadow-xl">
|
||||
<span className="text-caption text-gray-400 font-semibold uppercase tracking-caption">Total de Cursos</span>
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-white mt-1">{courses.length}</p>
|
||||
@@ -645,8 +653,16 @@ export const ManageCourses: React.FC = () => {
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-emerald-400 mt-1">{totalMaterials}</p>
|
||||
</div>
|
||||
<div className="bg-zinc-900/60 border border-white/10 p-5 rounded-[8px] shadow-xl">
|
||||
<span className="text-caption text-gray-400 font-semibold uppercase tracking-caption">Visualizações Acumuladas</span>
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-white mt-1">{totalViews.toLocaleString('pt-BR')}</p>
|
||||
<span className="text-caption text-gray-400 font-semibold uppercase tracking-caption">Alunos com Progresso</span>
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-white mt-1">{totalLearners.toLocaleString('pt-BR')}</p>
|
||||
</div>
|
||||
<div className="bg-zinc-900/60 border border-white/10 p-5 rounded-[8px] shadow-xl">
|
||||
<span className="text-caption text-gray-400 font-semibold uppercase tracking-caption">Aulas Concluídas</span>
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-orange-400 mt-1">{completedLessons.toLocaleString('pt-BR')}</p>
|
||||
</div>
|
||||
<div className="bg-zinc-900/60 border border-white/10 p-5 rounded-[8px] shadow-xl">
|
||||
<span className="text-caption text-gray-400 font-semibold uppercase tracking-caption">Dúvidas Recebidas</span>
|
||||
<p className="font-display text-subheading md:text-heading-sm font-bold text-white mt-1">{totalQuestions.toLocaleString('pt-BR')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -810,6 +826,7 @@ export const ManageCourses: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<button onClick={() => handleModerateComment(comment.id)} className="text-xs text-red-400 hover:text-red-300 font-semibold">Remover comentário</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Loader2, RefreshCw, ShieldCheck, UserCheck, UserX, Users } from 'lucide-react';
|
||||
import { adminApi, ManagedUser } from '../services/api';
|
||||
import { adminApi, ManagedUser, ManagedUserDetail, PlatformAnalytics } from '../services/api';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
@@ -19,12 +19,20 @@ export const SuperAdmin: React.FC = () => {
|
||||
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 loadUsers = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await adminApi.listUsers();
|
||||
setUsers(response.data);
|
||||
const dashboard = await adminApi.dashboard();
|
||||
setAnalytics(dashboard.data);
|
||||
} catch {
|
||||
showToast('Não foi possível carregar os usuários.', 'error');
|
||||
} finally {
|
||||
@@ -59,6 +67,28 @@ export const SuperAdmin: React.FC = () => {
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="min-h-screen pt-28 pb-20 px-6 md:px-12 max-w-[1440px] mx-auto">
|
||||
@@ -86,12 +116,42 @@ export const SuperAdmin: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
|
||||
<StatCard icon={<Users className="w-5 h-5" />} label="Usuários cadastrados" value={users.length} />
|
||||
<StatCard icon={<UserCheck className="w-5 h-5" />} label="Contas ativas" value={activeUsers} />
|
||||
<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>
|
||||
@@ -116,6 +176,7 @@ export const SuperAdmin: React.FC = () => {
|
||||
<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">
|
||||
@@ -151,6 +212,12 @@ export const SuperAdmin: React.FC = () => {
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
@@ -169,3 +236,10 @@ const StatCard: React.FC<{ icon: React.ReactNode; label: string; value: number }
|
||||
<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>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user