feat: add 2FA, secure cookies and publishing tools
This commit is contained in:
@@ -12,7 +12,7 @@ interface AuthPageProps {
|
||||
|
||||
export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
|
||||
const isRegistering = mode === 'signup';
|
||||
const { user, login, register } = useAuth();
|
||||
const { user, login, verifyTwoFactor, register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const lead = (location.state as { message?: string } | null)?.message;
|
||||
@@ -21,6 +21,9 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
|
||||
const [name, setName] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [challengeToken, setChallengeToken] = useState('');
|
||||
const [twoFactorCode, setTwoFactorCode] = useState('');
|
||||
const isTwoFactor = Boolean(challengeToken);
|
||||
|
||||
if (user && !isSubmitting) return <Navigate to={homeFor(user.role)} replace />;
|
||||
|
||||
@@ -40,9 +43,9 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
const signedInUser = isRegistering ? await register(name, email, password) : await login(email, password);
|
||||
const response = isRegistering ? await register(name, email, password) : await login(email, password);
|
||||
|
||||
if (!signedInUser) {
|
||||
if (!response) {
|
||||
setIsSubmitting(false);
|
||||
setError(isRegistering
|
||||
? 'Não foi possível criar sua conta. Use um e-mail válido e uma senha com pelo menos 8 caracteres.'
|
||||
@@ -50,33 +53,76 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if ('twoFactorRequired' in response) {
|
||||
setChallengeToken(response.challengeToken);
|
||||
setTwoFactorCode('');
|
||||
setError('');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const signedInUser = 'user' in response ? response.user : response;
|
||||
navigate(homeFor(signedInUser.role), { replace: true });
|
||||
};
|
||||
|
||||
const handleTwoFactor = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setError('');
|
||||
if (twoFactorCode.trim().length < 6) { setError('Informe o código de verificação.'); return; }
|
||||
setIsSubmitting(true);
|
||||
const verified = await verifyTwoFactor(challengeToken, twoFactorCode.trim());
|
||||
setIsSubmitting(false);
|
||||
if (!verified) {
|
||||
setError('Código inválido ou expirado. Tente novamente.');
|
||||
return;
|
||||
}
|
||||
navigate(homeFor(verified.role), { replace: true });
|
||||
};
|
||||
|
||||
const backToCredentials = () => {
|
||||
setChallengeToken('');
|
||||
setTwoFactorCode('');
|
||||
setError('');
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="wrap page auth-page enter">
|
||||
<div className="auth">
|
||||
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
|
||||
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
|
||||
<form noValidate onSubmit={handleSubmit}>
|
||||
{isRegistering && (
|
||||
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
|
||||
)}
|
||||
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
|
||||
<div className="field">
|
||||
<label htmlFor="auth-password">Senha</label>
|
||||
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
|
||||
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
|
||||
</div>
|
||||
{error && <p className="formmsg bad" role="alert">{error}</p>}
|
||||
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
|
||||
</form>
|
||||
<p className="alt">
|
||||
{isRegistering
|
||||
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
|
||||
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
|
||||
</p>
|
||||
{!isRegistering && <p className="alt"><Link className="link" to={paths.forgotPassword}>Esqueci minha senha</Link></p>}
|
||||
{isTwoFactor ? <>
|
||||
<h1>Verificação em duas etapas</h1>
|
||||
<p>Digite o código do seu autenticador ou um código de recuperação.</p>
|
||||
<form noValidate onSubmit={handleTwoFactor}>
|
||||
<div className="field">
|
||||
<label htmlFor="auth-2fa">Código de verificação</label>
|
||||
<input id="auth-2fa" value={twoFactorCode} onChange={(event) => setTwoFactorCode(event.target.value)} autoComplete="one-time-code" autoFocus required />
|
||||
</div>
|
||||
{error && <p className="formmsg bad" role="alert">{error}</p>}
|
||||
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Verificando…' : 'Verificar'}</button>
|
||||
</form>
|
||||
<p className="alt"><button className="link" type="button" onClick={backToCredentials}>Voltar</button></p>
|
||||
</> : <>
|
||||
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
|
||||
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
|
||||
<form noValidate onSubmit={handleSubmit}>
|
||||
{isRegistering && (
|
||||
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
|
||||
)}
|
||||
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
|
||||
<div className="field">
|
||||
<label htmlFor="auth-password">Senha</label>
|
||||
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
|
||||
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
|
||||
</div>
|
||||
{error && <p className="formmsg bad" role="alert">{error}</p>}
|
||||
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
|
||||
</form>
|
||||
<p className="alt">
|
||||
{isRegistering
|
||||
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
|
||||
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
|
||||
</p>
|
||||
{!isRegistering && <p className="alt"><Link className="link" to={paths.forgotPassword}>Esqueci minha senha</Link></p>}
|
||||
</>}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { Link, Navigate, useParams } from 'react-router-dom';
|
||||
import { BookmarkSimpleIcon, CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
|
||||
import { Attachment, Course } from '../types';
|
||||
@@ -6,15 +6,13 @@ import { useCourse, useLessonProgress } from '../hooks/useCourse';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useCatalog } from '../context/CatalogContext';
|
||||
import { ArtImage, CourseCard, Cover, courseFraming, useCoverImage } from '../components/catalog/Artwork';
|
||||
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
|
||||
import { MaterialButton, MaterialRow, attachmentIcon, useMaterialAction } from '../components/course/Materials';
|
||||
import { CourseReviews } from '../components/course/CourseReviews';
|
||||
import { Avatar } from '../components/ui/Avatar';
|
||||
import { courseMeta, lessonDuration, plural } from '../lib/format';
|
||||
import { paths } from '../lib/routes';
|
||||
import { useSavedCourses } from '../hooks/useSavedCourses';
|
||||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||||
import { MaterialButton, attachmentIcon } from '../components/course/Materials';
|
||||
import { useState } from 'react';
|
||||
|
||||
export type CourseMaterial = { attachment: Attachment; detail: string; lessonIndex?: number };
|
||||
|
||||
|
||||
@@ -7,13 +7,12 @@ import { useCourse, useLessonProgress } from '../hooks/useCourse';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { LessonVideo } from '../components/course/LessonVideo';
|
||||
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
|
||||
import { MaterialButton, MaterialRow, attachmentIcon, useMaterialAction } from '../components/course/Materials';
|
||||
import { Avatar } from '../components/ui/Avatar';
|
||||
import { lessonDuration } from '../lib/format';
|
||||
import { paths } from '../lib/routes';
|
||||
import { signUpState } from './CoursePage';
|
||||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||||
import { attachmentIcon, MaterialButton } from '../components/course/Materials';
|
||||
|
||||
export type LessonTab = 'aulas' | 'materiais' | 'discussao';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ChatCircleIcon, CircleNotchIcon, CopyIcon, TrashIcon } from '@phosphor-icons/react';
|
||||
import { CircleNotchIcon, CopyIcon, TrashIcon } from '@phosphor-icons/react';
|
||||
import { Attachment, AttachmentType, Comment, Course, Lesson, LessonMedia } from '../types';
|
||||
import { deleteCourse, duplicateCourse, getComments, getManagedCourses, moderateComment, replyToComment, saveCourse } from '../services/db';
|
||||
import { courseApi, instructorApi, InstructorAnalytics } from '../services/api';
|
||||
@@ -12,7 +12,7 @@ import { ConfirmDialog } from '../components/ui/ConfirmDialog';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { attachmentIcon, attachmentLabel } from '../components/course/Materials';
|
||||
import { ArrowRightMockIcon, CheckCircleMockIcon, DragMockIcon, EditMockIcon, MoreMockIcon, PlusMockIcon, SpinnerMockIcon, UploadMockIcon, WarningCircleMockIcon } from '../components/ui/MockupIcons';
|
||||
import { ArrowRightMockIcon, CheckCircleMockIcon, DragMockIcon, EditMockIcon, PlusMockIcon, SpinnerMockIcon, UploadMockIcon, WarningCircleMockIcon } from '../components/ui/MockupIcons';
|
||||
import { formatMinutes, lessonDuration, shortDate } from '../lib/format';
|
||||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||||
import { paths } from '../lib/routes';
|
||||
@@ -25,6 +25,23 @@ const formatSize = (bytes?: number | null) => {
|
||||
return `${new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 1 }).format(bytes / 1024 ** (index + 1))} ${units[index]}`;
|
||||
};
|
||||
|
||||
const toDatetimeLocal = (value?: string | null) => {
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 16);
|
||||
};
|
||||
|
||||
const formatScheduled = (value?: string | null) => value
|
||||
? new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value))
|
||||
: '';
|
||||
|
||||
const courseStatusText = (course: Course) => course.status === 'published'
|
||||
? 'Publicado'
|
||||
: course.scheduledPublishAt
|
||||
? `Agendado para ${formatScheduled(course.scheduledPublishAt)}`
|
||||
: 'Rascunho';
|
||||
|
||||
const newLessonId = () => `lesson-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||
const statusLabel = (lesson: Lesson) => {
|
||||
const status = lesson.media?.[0]?.status;
|
||||
@@ -46,6 +63,7 @@ const CourseEditor: React.FC<{
|
||||
const [description, setDescription] = useState(initialData?.description || '');
|
||||
const [category, setCategory] = useState(initialData?.category || categories[0] || '');
|
||||
const [status, setStatus] = useState<Course['status']>(initialData?.status || 'draft');
|
||||
const [scheduledPublishAt, setScheduledPublishAt] = useState(toDatetimeLocal(initialData?.scheduledPublishAt));
|
||||
const [cover, setCover] = useState(initialData?.thumbnail && initialData.thumbnail !== '/course-placeholder.svg' ? initialData.thumbnail : '');
|
||||
const [lessons, setLessons] = useState<Lesson[]>(initialData?.lessons || []);
|
||||
const [editingLessonId, setEditingLessonId] = useState<string | null>(null);
|
||||
@@ -190,6 +208,15 @@ const CourseEditor: React.FC<{
|
||||
if (!title.trim()) { showToast('Informe o título do curso.', 'error'); return; }
|
||||
if (!category) { showToast('Selecione uma área para o curso.', 'error'); return; }
|
||||
if (!lessons.length) { showToast('Adicione pelo menos uma aula.', 'error'); return; }
|
||||
const scheduleDate = nextStatus === 'draft' && scheduledPublishAt ? new Date(scheduledPublishAt) : null;
|
||||
if (scheduledPublishAt && Number.isNaN(new Date(scheduledPublishAt).getTime())) {
|
||||
showToast('Informe uma data de publicação válida.', 'error');
|
||||
return;
|
||||
}
|
||||
if (scheduleDate && scheduleDate.getTime() <= Date.now()) {
|
||||
showToast('Escolha uma data futura para agendar a publicação.', 'error');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const seconds = lessons.reduce((total, lesson) => total + (lesson.media?.[0]?.durationSeconds || 0), 0);
|
||||
@@ -199,6 +226,7 @@ const CourseEditor: React.FC<{
|
||||
description,
|
||||
category,
|
||||
status: nextStatus,
|
||||
scheduledPublishAt: scheduleDate ? scheduleDate.toISOString() : null,
|
||||
thumbnail: cover || '/course-placeholder.svg',
|
||||
coverImageZoom: initialData?.coverImageZoom || 1,
|
||||
coverImagePositionX: initialData?.coverImagePositionX ?? 50,
|
||||
@@ -211,7 +239,8 @@ const CourseEditor: React.FC<{
|
||||
attachments,
|
||||
});
|
||||
setStatus(nextStatus);
|
||||
showToast('Curso salvo.', 'success');
|
||||
if (nextStatus === 'published') setScheduledPublishAt('');
|
||||
showToast(nextStatus === 'draft' && scheduleDate ? 'Curso salvo e agendado.' : 'Curso salvo.', 'success');
|
||||
onSaved();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Não foi possível salvar o curso.', 'error');
|
||||
@@ -232,7 +261,7 @@ const CourseEditor: React.FC<{
|
||||
<div className="m-cover sm" style={cover ? { backgroundImage: `url("${cover}")`, backgroundSize: 'cover', backgroundPosition: 'center' } : { background: 'var(--bg-2)' }}>{!cover && <span className="t">{title || 'Novo curso'}</span>}</div>
|
||||
<div className="m-under"><button className="link" type="button" disabled={!coverConfigured || coverUploading} onClick={() => coverInput.current?.click()}>{coverUploading ? 'Enviando…' : 'Trocar capa'}</button>{initialData?.id && status === 'published' && <Link className="link" to={paths.course(initialData.id)}>Ver como aluno</Link>}</div>
|
||||
<input ref={coverInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadCover(file); }} />
|
||||
<header className="m-title"><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></header>
|
||||
<header className="m-title"><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : scheduledPublishAt ? `Agendado para ${formatScheduled(scheduledPublishAt)}` : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></header>
|
||||
<section className="m-group"><h2>Aulas</h2><div className="m-list">
|
||||
{lessons.map((lesson, index) => <button className="m-row" type="button" key={lesson.id} onClick={() => setEditingLessonId(lesson.id)}><span className="m-n num">{index + 1}</span><span className="m-rt"><b>{lesson.title}</b><small>{lessonDuration(lesson) || 'Sem duração'}</small></span>{statusLabel(lesson)}</button>)}
|
||||
<label className="m-row m-add" style={{ opacity: bunnyConfigured ? 1 : 0.6 }}>
|
||||
@@ -245,6 +274,7 @@ const CourseEditor: React.FC<{
|
||||
<div className="m-field"><span>Área</span><Select variant="mobile" value={category} options={categories.map((item) => ({ value: item, label: item }))} onChange={setCategory} ariaLabel="Área do curso" /></div>
|
||||
<label className="m-field"><span>Título</span><input value={title} onChange={(event) => setTitle(event.target.value)} /></label>
|
||||
<label className="m-field col"><span>Descrição</span><textarea rows={4} value={description} onChange={(event) => setDescription(event.target.value)} /></label>
|
||||
{status === 'draft' && <label className="m-field col"><span>Agendar publicação</span><input type="datetime-local" value={scheduledPublishAt} onChange={(event) => setScheduledPublishAt(event.target.value)} /><small>Opcional. O curso publica sozinho quando os vídeos estiverem prontos.</small></label>}
|
||||
</div>{status === 'draft' && <button className="link" type="button" style={{ marginTop: 12 }} onClick={() => void save('draft')} disabled={saving}>Salvar rascunho</button>}</section>
|
||||
<section className="m-group"><h2>Materiais</h2><div className="m-list">
|
||||
{attachments.map((attachment) => <div className="m-row" key={attachment.id}><span className="m-ic">{attachmentIcon(attachment.type)}</span><span className="m-rt"><b>{attachment.name}</b><small>{[attachmentLabel(attachment.type), attachment.size].filter(Boolean).join(' · ')}</small></span><button className="m-icb" type="button" onClick={() => removeAttachment(attachment.id)} aria-label={`Remover ${attachment.name}`}><TrashIcon className="ph" /></button></div>)}
|
||||
@@ -272,7 +302,7 @@ const CourseEditor: React.FC<{
|
||||
return <main className="wrap page enter">
|
||||
<div className="crumb"><Link to={paths.manage} onClick={onClose}>Gerenciar cursos</Link><ArrowRightMockIcon className="ph" /><span>{title || 'Novo curso'}</span></div>
|
||||
<div className="ptitle">
|
||||
<div><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></div>
|
||||
<div><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : scheduledPublishAt ? `Agendado para ${formatScheduled(scheduledPublishAt)}` : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></div>
|
||||
<div className="acts">
|
||||
{initialData?.id && status === 'published' && <Link className="btn sec" to={paths.course(initialData.id)}>Ver como aluno</Link>}
|
||||
{status === 'draft' && <button className="btn ghost" type="button" onClick={() => void save()} disabled={saving}>Salvar rascunho</button>}
|
||||
@@ -326,6 +356,7 @@ const CourseEditor: React.FC<{
|
||||
<div className="field"><label htmlFor="manage-title">Título</label><input id="manage-title" value={title} onChange={(event) => setTitle(event.target.value)} /></div>
|
||||
<div className="field"><label>Área</label><Select variant="field" value={category} options={categories.map((item) => ({ value: item, label: item }))} onChange={setCategory} ariaLabel="Área do curso" /></div>
|
||||
<div className="field"><label htmlFor="manage-description">Descrição</label><textarea id="manage-description" rows={4} value={description} onChange={(event) => setDescription(event.target.value)} /></div>
|
||||
{status === 'draft' && <div className="field"><label htmlFor="manage-schedule">Agendar publicação <span className="faint">(opcional)</span></label><input id="manage-schedule" type="datetime-local" value={scheduledPublishAt} onChange={(event) => setScheduledPublishAt(event.target.value)} /><small>O curso publica sozinho quando os vídeos estiverem prontos.</small></div>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="box">
|
||||
@@ -459,7 +490,7 @@ export const ManageCourses: React.FC = () => {
|
||||
<header className="m-large"><h1>Gerenciar cursos</h1><button className="m-icb" type="button" onClick={openNew} aria-label="Novo curso"><PlusMockIcon className="ph" /></button></header>
|
||||
<div className="m-stats num"><div><b>{published}</b><small>Publicados</small></div><div><b>{courses.length - published}</b><small>Rascunhos</small></div><div><b>{analytics?.learners ?? 0}</b><small>Alunos</small></div><div><b>{analytics?.unansweredComments ?? 0}</b><small>Sem resposta</small></div></div>
|
||||
<div className="m-seg" role="tablist"><button type="button" role="tab" aria-selected={activeTab === 'courses'} onClick={() => setActiveTab('courses')}>Cursos</button><button type="button" role="tab" aria-selected={activeTab === 'comments'} onClick={() => setActiveTab('comments')}>Discussões</button></div>
|
||||
{activeTab === 'courses' ? <section className="m-group"><div className="m-list">{courses.map((course) => <div className="m-row" key={course.id}><Thumb course={course} className="m-th" /><button className="m-rt" type="button" onClick={() => openCourse(course)}><b>{course.title}</b><small>{course.status === 'published' ? 'Publicado' : 'Rascunho'} · {course.lessons.length} aulas{course.learners ? ` · ${course.learners} alunos` : ''}</small></button><button className="m-icb" type="button" onClick={() => void duplicate(course)} aria-label={`Duplicar ${course.title}`}><CopyIcon className="ph" /></button><button className="m-icb" type="button" onClick={() => setCourseDeleteTarget(course)} aria-label={`Excluir ${course.title}`}><TrashIcon className="ph" /></button></div>)}</div>{!loading && !courses.length && <p className="m-empty">Nenhum curso ainda.</p>}</section>
|
||||
{activeTab === 'courses' ? <section className="m-group"><div className="m-list">{courses.map((course) => <div className="m-row" key={course.id}><Thumb course={course} className="m-th" /><button className="m-rt" type="button" onClick={() => openCourse(course)}><b>{course.title}</b><small>{courseStatusText(course)} · {course.lessons.length} aulas{course.learners ? ` · ${course.learners} alunos` : ''}</small></button><button className="m-icb" type="button" onClick={() => void duplicate(course)} aria-label={`Duplicar ${course.title}`}><CopyIcon className="ph" /></button><button className="m-icb" type="button" onClick={() => setCourseDeleteTarget(course)} aria-label={`Excluir ${course.title}`}><TrashIcon className="ph" /></button></div>)}</div>{!loading && !courses.length && <p className="m-empty">Nenhum curso ainda.</p>}</section>
|
||||
: <><div className="m-chips" role="group" aria-label="Filtrar discussões">{([['all', 'Todas'], ['unanswered', 'Sem resposta'], ['answered', 'Respondidas']] as const).map(([key, label]) => <button key={key} type="button" aria-pressed={commentFilter === key} onClick={() => setCommentFilter(key)}>{label}</button>)}</div><section className="m-group"><div className="m-list multi">{visibleComments.map(({ comment, courseTitle }) => <div className="m-row" key={comment.id}><span className="m-rt"><b>{comment.text}</b><small>{comment.user} · {courseTitle} · {comment.date}</small>{comment.reply ? <small>Professor respondeu: {comment.reply}</small> : replyingTo === comment.id ? <span className="m-reply"><input value={replyText} onChange={(event) => setReplyText(event.target.value)} placeholder="Escrever resposta" /><button className="link" type="button" disabled={sendingReply} onClick={() => void sendReply(comment.id)}>Enviar</button></span> : <button className="link" type="button" onClick={() => { setReplyingTo(comment.id); setReplyText(''); }}>Responder</button>}<button className="link bad-text" type="button" onClick={() => setCommentDeleteTarget(comment)}>Remover</button></span></div>)}</div>{!loading && !visibleComments.length && <p className="m-empty">Nenhuma discussão encontrada.</p>}</section></>}
|
||||
{listDialogs}
|
||||
</main>;
|
||||
@@ -478,7 +509,7 @@ export const ManageCourses: React.FC = () => {
|
||||
</div>
|
||||
{activeTab === 'comments' && <div className="chips2" role="group" aria-label="Filtrar discussões">{([['all', 'Todas'], ['unanswered', 'Sem resposta'], ['answered', 'Respondidas']] as const).map(([key, label]) => <button key={key} type="button" aria-pressed={commentFilter === key} onClick={() => setCommentFilter(key)}>{label}</button>)}</div>}
|
||||
{activeTab === 'courses' ? (loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : courses.length ? <div className="tablewrap"><table className="t-ger"><thead><tr><th>Curso</th><th>Status</th><th>Aulas</th><th>Alunos</th><th>Atualizado</th><th></th></tr></thead><tbody>
|
||||
{courses.map((course) => <tr className="click" key={course.id} onClick={() => openCourse(course)}><td><span className="person"><Thumb course={course} /><span><b style={{ fontWeight: 500 }}>{course.title}</b><small>{course.category}</small></span></span></td><td><span className={`st ${course.status === 'published' ? 'ok' : 'mut'}`}>{course.status === 'published' ? 'Publicado' : 'Rascunho'}</span></td><td className="num">{course.lessons.length}</td><td className="num">{course.learners ?? 0}</td><td className="num">{shortDate(course.updatedAt) || '—'}</td><td className="right"><div className="acts"><button className="iconbtn" type="button" aria-label={`Editar ${course.title}`} onClick={(event) => { event.stopPropagation(); openCourse(course); }}><EditMockIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Duplicar ${course.title}`} onClick={(event) => { event.stopPropagation(); void duplicate(course); }}><CopyIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Excluir ${course.title}`} onClick={(event) => { event.stopPropagation(); setCourseDeleteTarget(course); }}><TrashIcon className="ph" /></button></div></td></tr>)}
|
||||
{courses.map((course) => <tr className="click" key={course.id} onClick={() => openCourse(course)}><td><span className="person"><Thumb course={course} /><span><b style={{ fontWeight: 500 }}>{course.title}</b><small>{course.category}</small></span></span></td><td><span className={`st ${course.status === 'published' ? 'ok' : 'mut'}`}>{courseStatusText(course)}</span></td><td className="num">{course.lessons.length}</td><td className="num">{course.learners ?? 0}</td><td className="num">{shortDate(course.updatedAt) || '—'}</td><td className="right"><div className="acts"><button className="iconbtn" type="button" aria-label={`Editar ${course.title}`} onClick={(event) => { event.stopPropagation(); openCourse(course); }}><EditMockIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Duplicar ${course.title}`} onClick={(event) => { event.stopPropagation(); void duplicate(course); }}><CopyIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Excluir ${course.title}`} onClick={(event) => { event.stopPropagation(); setCourseDeleteTarget(course); }}><TrashIcon className="ph" /></button></div></td></tr>)}
|
||||
</tbody></table></div> : <p className="empty">Nenhum curso criado ainda.</p>) : visibleComments.length ? <div className="list">{visibleComments.map(({ comment, courseTitle }) => <article className="manage-comment" key={comment.id}><div><b>{comment.user}</b><small>{courseTitle} · {comment.date}</small></div><p>{comment.text}</p>{comment.reply ? <div className="reply"><small>Resposta do professor</small><p>{comment.reply}</p></div> : replyingTo === comment.id ? <div className="composer"><textarea value={replyText} onChange={(event) => setReplyText(event.target.value)} placeholder="Escreva sua resposta" /><button className="btn" type="button" disabled={sendingReply} onClick={() => void sendReply(comment.id)}>Enviar</button></div> : <button className="link" type="button" onClick={() => { setReplyingTo(comment.id); setReplyText(''); }}>Responder</button>}<button className="link bad-text" type="button" onClick={() => setCommentDeleteTarget(comment)}>Remover comentário</button></article>)}</div> : <p className="empty">{allComments.length ? 'Nenhuma discussão com esse filtro.' : 'Nenhuma discussão ainda.'}</p>}
|
||||
{listDialogs}
|
||||
</main>;
|
||||
|
||||
@@ -2,10 +2,17 @@ import React, { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { BellIcon, CircleNotchIcon } from '@phosphor-icons/react';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { NotificationFeed, NotificationItem, getNotifications, markAllNotificationsRead, markNotificationRead } from '../services/notifications';
|
||||
import {
|
||||
NotificationFeed,
|
||||
NotificationItem,
|
||||
getNotifications,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
} from '../services/notifications';
|
||||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||||
|
||||
const formatWhen = (value: string) => new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
const formatWhen = (value: string) =>
|
||||
new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
|
||||
export const NotificationsPage: React.FC = () => {
|
||||
const { showToast } = useToast();
|
||||
@@ -25,12 +32,18 @@ export const NotificationsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { void load(); }, []);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const markAll = async () => {
|
||||
try {
|
||||
await markAllNotificationsRead();
|
||||
setFeed((current) => current ? { ...current, unread: 0, items: current.items.map((item) => ({ ...item, readAt: item.readAt || new Date().toISOString() })) } : current);
|
||||
setFeed((current) =>
|
||||
current
|
||||
? { ...current, unread: 0, items: current.items.map((item) => ({ ...item, readAt: item.readAt || new Date().toISOString() })) }
|
||||
: current,
|
||||
);
|
||||
window.dispatchEvent(new Event('compor:notifications-updated'));
|
||||
} catch {
|
||||
showToast('Não foi possível marcar as notificações como lidas.', 'error');
|
||||
@@ -39,34 +52,78 @@ export const NotificationsPage: React.FC = () => {
|
||||
|
||||
const open = (item: NotificationItem) => {
|
||||
if (item.readAt) return;
|
||||
void markNotificationRead(item.id).then(() => {
|
||||
setFeed((current) => current ? {
|
||||
...current,
|
||||
unread: Math.max(0, current.unread - 1),
|
||||
items: current.items.map((entry) => entry.id === item.id ? { ...entry, readAt: new Date().toISOString() } : entry),
|
||||
} : current);
|
||||
window.dispatchEvent(new Event('compor:notifications-updated'));
|
||||
}).catch(() => undefined);
|
||||
void markNotificationRead(item.id)
|
||||
.then(() => {
|
||||
setFeed((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
unread: Math.max(0, current.unread - 1),
|
||||
items: current.items.map((entry) => (entry.id === item.id ? { ...entry, readAt: new Date().toISOString() } : entry)),
|
||||
}
|
||||
: current,
|
||||
);
|
||||
window.dispatchEvent(new Event('compor:notifications-updated'));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
const list = loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : feed?.items.length ? <div className="notification-list">
|
||||
{feed.items.map((item) => <Link className={`notification${item.readAt ? '' : ' unread'}`} to={item.href} key={item.id} onClick={() => open(item)}>
|
||||
<span className="n-ic"><BellIcon className="ph" /></span>
|
||||
<span className="n-copy"><b>{item.title}</b>{item.body && <p>{item.body}</p>}</span>
|
||||
<small>{formatWhen(item.createdAt)}</small>
|
||||
</Link>)}
|
||||
</div> : <div className="empty notification-empty"><BellIcon className="ph" /><h2>Nenhuma notificação</h2><p>Quando alguém responder seus comentários ou fizer uma pergunta nos seus cursos, você verá aqui.</p></div>;
|
||||
|
||||
if (isMobile) return <main className="m-page m-gut enter">
|
||||
<header className="m-large"><h1>Notificações</h1>{Boolean(feed?.unread) && <button className="link" type="button" onClick={() => void markAll()}>Marcar lidas</button>}</header>
|
||||
{list}
|
||||
</main>;
|
||||
|
||||
return <main className="wrap page enter">
|
||||
<div className="ptitle">
|
||||
<div><h1>Notificações</h1><p>{feed?.unread ? `${feed.unread} não ${feed.unread === 1 ? 'lida' : 'lidas'}` : 'Tudo em dia.'}</p></div>
|
||||
{Boolean(feed?.unread) && <button className="btn sec" type="button" onClick={() => void markAll()}>Marcar todas como lidas</button>}
|
||||
const list = loading ? (
|
||||
<div className="loading">
|
||||
<CircleNotchIcon className="ph spin" />
|
||||
</div>
|
||||
{list}
|
||||
</main>;
|
||||
) : feed?.items.length ? (
|
||||
<div className="notification-list">
|
||||
{feed.items.map((item) => (
|
||||
<Link className={`notification${item.readAt ? '' : ' unread'}`} to={item.href} key={item.id} onClick={() => open(item)}>
|
||||
<span className="n-ic">
|
||||
<BellIcon className="ph" />
|
||||
</span>
|
||||
<span className="n-copy">
|
||||
<b>{item.title}</b>
|
||||
{item.body && <p>{item.body}</p>}
|
||||
</span>
|
||||
<small>{formatWhen(item.createdAt)}</small>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty notification-empty">
|
||||
<BellIcon className="ph" />
|
||||
<h2>Nenhuma notificação</h2>
|
||||
<p>Quando alguém responder seus comentários ou fizer uma pergunta nos seus cursos, você verá aqui.</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isMobile)
|
||||
return (
|
||||
<main className="m-page m-gut enter">
|
||||
<header className="m-large">
|
||||
<h1>Notificações</h1>
|
||||
{Boolean(feed?.unread) && (
|
||||
<button className="link" type="button" onClick={() => void markAll()}>
|
||||
Marcar lidas
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
{list}
|
||||
</main>
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="wrap page enter">
|
||||
<div className="ptitle">
|
||||
<div>
|
||||
<h1>Notificações</h1>
|
||||
<p>{feed?.unread ? `${feed.unread} não ${feed.unread === 1 ? 'lida' : 'lidas'}` : 'Tudo em dia.'}</p>
|
||||
</div>
|
||||
{Boolean(feed?.unread) && (
|
||||
<button className="btn sec" type="button" onClick={() => void markAll()}>
|
||||
Marcar todas como lidas
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{list}
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,9 +4,9 @@ import { ArrowSquareOutIcon, CameraIcon, CircleNotchIcon, GlobeIcon, InstagramLo
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { Profile, ProfileInput, instructorApi, profileApi } from '../services/api';
|
||||
import { CourseCoverImage } from '../components/CourseCoverImage';
|
||||
import { TwoFactorSettings } from '../components/account/TwoFactorSettings';
|
||||
import { Switch } from '../components/ui/Switch';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { paths } from '../lib/routes';
|
||||
|
||||
const emptyProfile = (user: { id: string; email: string; name: string; role: string }): Profile => ({
|
||||
id: user.id, email: user.email, name: user.name,
|
||||
@@ -52,6 +52,7 @@ export const ProfilePage: React.FC = () => {
|
||||
<section className="form"><h2>Links e visibilidade</h2><p className="muted">Use links completos, começando com https://.</p><UrlField icon={<GlobeIcon />} label="Site" value={profile.websiteUrl} onChange={(value) => update('websiteUrl', value || null)} /><UrlField icon={<LinkedinLogoIcon />} label="LinkedIn" value={profile.linkedinUrl} onChange={(value) => update('linkedinUrl', value || null)} /><UrlField icon={<InstagramLogoIcon />} label="Instagram" value={profile.instagramUrl} onChange={(value) => update('instagramUrl', value || null)} /><UrlField icon={<YoutubeLogoIcon />} label="YouTube" value={profile.youtubeUrl} onChange={(value) => update('youtubeUrl', value || null)} /><div className="toggle"><span>Perfil público<small>Permite que outras pessoas vejam sua apresentação e seus cursos.</small></span><Switch checked={profile.isPublic} onChange={(checked) => update('isPublic', checked)} label="Perfil público" /></div></section></div>
|
||||
<button className="btn lg profile-save" type="submit" disabled={isSaving}>{isSaving ? 'Salvando…' : 'Salvar'}</button>
|
||||
</form>
|
||||
{user.role === 'superadmin' && <TwoFactorSettings />}
|
||||
</main>;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { CircleNotchIcon } from '@phosphor-icons/react';
|
||||
import { CheckIcon, CircleNotchIcon } from '@phosphor-icons/react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { useCatalog } from '../context/CatalogContext';
|
||||
@@ -13,6 +13,7 @@ import { CategoryManager } from '../components/admin/CategoryManager';
|
||||
import { TrailManager } from '../components/admin/TrailManager';
|
||||
import { DragMockIcon, MoreMockIcon, PlusMockIcon, SearchMockIcon } from '../components/ui/MockupIcons';
|
||||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||||
import { paths } from '../lib/routes';
|
||||
|
||||
type HomeConfiguration = {
|
||||
featuredCourseId: string | null;
|
||||
@@ -78,6 +79,13 @@ export const SuperAdmin: React.FC = () => {
|
||||
const [draggedCourseId, setDraggedCourseId] = useState<string | null>(null);
|
||||
const [mobileUser, setMobileUser] = useState<ManagedUser | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ManagedUser | null>(null);
|
||||
const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
|
||||
const [bulkTarget, setBulkTarget] = useState<boolean | null>(null);
|
||||
const [bulkBusy, setBulkBusy] = useState(false);
|
||||
const [bulkInvites, setBulkInvites] = useState<Array<{ email: string; inviteUrl?: string; error?: string }>>([]);
|
||||
const [bulkInviteOpen, setBulkInviteOpen] = useState(false);
|
||||
const [bulkInviteBusy, setBulkInviteBusy] = useState(false);
|
||||
const bulkInviteInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadData = async () => {
|
||||
setLoading(true);
|
||||
@@ -112,6 +120,38 @@ export const SuperAdmin: React.FC = () => {
|
||||
return audit.filter((entry) => [entry.actorName, describeAction(entry), dateTime(entry.createdAt)].some((value) => value.toLowerCase().includes(normalized)));
|
||||
}, [audit, auditQuery]);
|
||||
|
||||
const selectableUsers = useMemo(() => filteredUsers.filter((account) => account.id !== user?.id), [filteredUsers, user?.id]);
|
||||
const allSelected = selectableUsers.length > 0 && selectableUsers.every((account) => selectedUsers.has(account.id));
|
||||
|
||||
const toggleSelected = (accountId: string) => {
|
||||
setSelectedUsers((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(accountId)) next.delete(accountId);
|
||||
else next.add(accountId);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleAllSelected = () => {
|
||||
setSelectedUsers(allSelected ? new Set() : new Set(selectableUsers.map((account) => account.id)));
|
||||
};
|
||||
|
||||
const performBulkStatus = async () => {
|
||||
if (bulkTarget === null || !selectedUsers.size) return;
|
||||
setBulkBusy(true);
|
||||
try {
|
||||
const response = await adminApi.bulkUpdateUsers([...selectedUsers], bulkTarget);
|
||||
setUsers((current) => current.map((account) => response.data.find((updated) => updated.id === account.id) || account));
|
||||
setSelectedUsers(new Set());
|
||||
setBulkTarget(null);
|
||||
showToast(bulkTarget ? 'Contas ativadas.' : 'Contas desativadas.', 'success');
|
||||
} catch {
|
||||
showToast('Não foi possível atualizar as contas selecionadas.', 'error');
|
||||
} finally {
|
||||
setBulkBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const exportUsersCsv = () => {
|
||||
const rows = [
|
||||
['Nome', 'E-mail', 'Papel', 'Status', 'Cadastro', 'Último acesso'],
|
||||
@@ -168,6 +208,52 @@ export const SuperAdmin: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const importBulkInvitations = async (file?: File) => {
|
||||
if (!file) return;
|
||||
setBulkInviteBusy(true);
|
||||
try {
|
||||
const text = await file.text();
|
||||
const emails = [...new Set(text.split(/\r?\n/)
|
||||
.map((line) => line.split(/[;,]/)[0].trim().replace(/^"|"$/g, ''))
|
||||
.filter((value) => value && value.toLowerCase() !== 'email' && value.toLowerCase() !== 'e-mail' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)))].slice(0, 100);
|
||||
if (!emails.length) {
|
||||
showToast('Nenhum e-mail válido encontrado no CSV.', 'error');
|
||||
return;
|
||||
}
|
||||
const response = await adminApi.bulkInvite(emails);
|
||||
setBulkInvites(response.data);
|
||||
setBulkInviteOpen(true);
|
||||
const created = response.data.filter((item) => item.inviteUrl).length;
|
||||
showToast(`${created} ${created === 1 ? 'convite gerado' : 'convites gerados'}.`, 'success');
|
||||
} catch {
|
||||
showToast('Não foi possível importar os convites.', 'error');
|
||||
} finally {
|
||||
setBulkInviteBusy(false);
|
||||
if (bulkInviteInput.current) bulkInviteInput.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const copyBulkLinks = () => {
|
||||
const links = bulkInvites
|
||||
.filter((item) => item.inviteUrl)
|
||||
.map((item) => `${item.email}: ${item.inviteUrl}`)
|
||||
.join('\n');
|
||||
if (links) void navigator.clipboard.writeText(links);
|
||||
};
|
||||
|
||||
const impersonate = async (account: ManagedUser) => {
|
||||
setBusyUserId(account.id);
|
||||
setOpenMenu(null);
|
||||
setMobileUser(null);
|
||||
try {
|
||||
await adminApi.impersonate(account.id);
|
||||
window.location.assign(paths.explore);
|
||||
} catch {
|
||||
setBusyUserId(null);
|
||||
showToast('Não foi possível entrar como este usuário.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const resetPassword = async (account: ManagedUser) => {
|
||||
setBusyUserId(account.id);
|
||||
setOpenMenu(null);
|
||||
@@ -252,6 +338,32 @@ export const SuperAdmin: React.FC = () => {
|
||||
onConfirm={() => void performDelete()}
|
||||
/>;
|
||||
|
||||
const bulkInviteDialog = <>{bulkInviteOpen && <div className="scrim" role="dialog" aria-modal="true" aria-label="Convites importados" onMouseDown={(event) => { if (event.target === event.currentTarget) setBulkInviteOpen(false); }}>
|
||||
<div className="dialog" style={{ maxWidth: 620 }}>
|
||||
<header><div><h2>Convites importados</h2><p>{bulkInvites.filter((item) => item.inviteUrl).length} links gerados. Você também pode copiar todos e enviar pelo canal que preferir.</p></div><button type="button" className="iconbtn" onClick={() => setBulkInviteOpen(false)} aria-label="Fechar">×</button></header>
|
||||
<div className="list" style={{ maxHeight: 360, overflow: 'auto' }}>
|
||||
{bulkInvites.map((item) => <div className="row" key={item.email} style={{ gridTemplateColumns: 'minmax(0, 1fr) auto', padding: '10px 0' }}>
|
||||
<span className="t">{item.email}<small>{item.inviteUrl ? 'Convite criado' : item.error || 'Não foi possível criar o convite.'}</small></span>
|
||||
{item.inviteUrl && <button className="btn sec" type="button" onClick={() => void navigator.clipboard.writeText(item.inviteUrl!)}>Copiar</button>}
|
||||
</div>)}
|
||||
</div>
|
||||
<div className="review-actions" style={{ marginTop: 16 }}>
|
||||
<button className="btn" type="button" onClick={copyBulkLinks} disabled={!bulkInvites.some((item) => item.inviteUrl)}>Copiar todos os links</button>
|
||||
<button className="btn sec" type="button" onClick={() => setBulkInviteOpen(false)}>Fechar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>}</>;
|
||||
|
||||
const bulkDialog = <ConfirmDialog
|
||||
open={bulkTarget !== null}
|
||||
title={bulkTarget ? 'Ativar contas' : 'Desativar contas'}
|
||||
message={bulkTarget === null ? '' : `${selectedUsers.size} ${selectedUsers.size === 1 ? 'conta será' : 'contas serão'} ${bulkTarget ? 'ativadas' : 'desativadas'}.`}
|
||||
confirmLabel={bulkTarget ? 'Ativar' : 'Desativar'}
|
||||
busy={bulkBusy}
|
||||
onCancel={() => { if (!bulkBusy) setBulkTarget(null); }}
|
||||
onConfirm={() => void performBulkStatus()}
|
||||
/>;
|
||||
|
||||
if (isMobile) return <main className="m-page m-gut enter">
|
||||
<header className="m-large"><h1>Administração</h1><button className="m-icb" type="button" aria-label="Convidar usuário" onClick={() => { setAccessLink(''); setInviteOpen(true); }}><PlusMockIcon className="ph" /></button></header>
|
||||
<div className="m-stats num"><div><b>{analytics?.totalUsers ?? users.length}</b><small>Usuários</small></div><div><b>{instructorCount}</b><small>Professores</small></div><div><b>{analytics?.publishedCourses ?? 0}</b><small>Cursos</small></div><div><b>{analytics?.pendingInvitations ?? 0}</b><small>Convites</small></div></div>
|
||||
@@ -301,11 +413,14 @@ export const SuperAdmin: React.FC = () => {
|
||||
<div className="field"><label>Papel</label><Select variant="field" value={mobileUser.role} options={roleOptions} disabled={mobileUser.id === user?.id} onChange={(role) => { setMobileUser(null); void updateUser(mobileUser, { role: role as ManagedUser['role'] }); }} ariaLabel={`Papel de ${mobileUser.name}`} /></div>
|
||||
<button className="btn sec" type="button" onClick={() => { setMobileUser(null); void updateUser(mobileUser, { isActive: !mobileUser.isActive }); }}>{mobileUser.isActive ? 'Desativar conta' : 'Ativar conta'}</button>
|
||||
<button className="btn sec" type="button" onClick={() => { setMobileUser(null); void resetPassword(mobileUser); }}>Redefinir senha</button>
|
||||
{mobileUser.role !== 'admin' && mobileUser.isActive && <button className="btn sec" type="button" onClick={() => void impersonate(mobileUser)}>Entrar como usuário</button>}
|
||||
{mobileUser.id !== user?.id && <button className="btn sec bad-text" type="button" onClick={() => { setMobileUser(null); void deleteUser(mobileUser); }}>Excluir conta</button>}
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
{deleteDialog}
|
||||
{bulkDialog}
|
||||
{bulkInviteDialog}
|
||||
</main>;
|
||||
|
||||
return <main className="wrap page enter">
|
||||
@@ -326,18 +441,22 @@ export const SuperAdmin: React.FC = () => {
|
||||
<div className="toolbar">
|
||||
<label className="search"><SearchMockIcon className="ph" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar por nome ou e-mail" aria-label="Buscar usuários" /></label>
|
||||
<span className="sp" />
|
||||
<input ref={bulkInviteInput} type="file" accept=".csv,text/csv" hidden onChange={(event) => void importBulkInvitations(event.target.files?.[0])} />
|
||||
<button className="btn sec" type="button" onClick={() => bulkInviteInput.current?.click()} disabled={bulkInviteBusy}>{bulkInviteBusy ? 'Importando…' : 'Importar CSV'}</button>
|
||||
<button className="btn sec" type="button" onClick={exportUsersCsv} disabled={!filteredUsers.length}>Exportar CSV</button>
|
||||
<button className="btn" type="button" onClick={() => { setAccessLink(''); setInviteOpen(true); }}><PlusMockIcon className="ph" /> Convidar</button>
|
||||
</div>
|
||||
{loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : <div className="tablewrap"><table><thead><tr><th>Nome</th><th>Papel</th><th>Status</th><th>Último acesso</th><th></th></tr></thead><tbody>
|
||||
{selectedUsers.size > 0 && <div className="bulkbar"><span className="num">{selectedUsers.size} {selectedUsers.size === 1 ? 'conta selecionada' : 'contas selecionadas'}</span><span className="sp" /><button className="btn sec" type="button" onClick={() => setBulkTarget(true)}>Ativar</button><button className="btn sec bad-text" type="button" onClick={() => setBulkTarget(false)}>Desativar</button><button className="link" type="button" onClick={() => setSelectedUsers(new Set())}>Limpar seleção</button></div>}
|
||||
{loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : <div className="tablewrap"><table><thead><tr><th style={{ width: 36 }}><button className="check" type="button" role="checkbox" aria-checked={allSelected} aria-label="Selecionar todos" disabled={!selectableUsers.length} onClick={toggleAllSelected}>{allSelected && <CheckIcon className="ph" />}</button></th><th>Nome</th><th>Papel</th><th>Status</th><th>Último acesso</th><th></th></tr></thead><tbody>
|
||||
{filteredUsers.map((account) => <tr key={account.id}>
|
||||
<td><button className="check" type="button" role="checkbox" aria-checked={selectedUsers.has(account.id)} aria-label={`Selecionar ${account.name}`} disabled={account.id === user?.id} onClick={() => toggleSelected(account.id)}>{selectedUsers.has(account.id) && <CheckIcon className="ph" />}</button></td>
|
||||
<td><span className="person"><Avatar name={account.name} size="sm" /><span>{account.name}<small>{account.email}</small></span></span></td>
|
||||
<td><Select value={account.role} options={roleOptions} disabled={busyUserId === account.id || account.id === user?.id} onChange={(role) => void updateUser(account, { role: role as ManagedUser['role'] })} ariaLabel={`Papel de ${account.name}`} /></td>
|
||||
<td><span className={`st ${account.isActive ? 'ok' : 'mut'}`}>{account.isActive ? 'Ativo' : 'Desativado'}</span></td>
|
||||
<td className="num" style={{ color: 'var(--fg-2)' }}>{lastAccess(account.lastAccessAt)}</td>
|
||||
<td className="right"><div className="rowmenu"><button className="iconbtn" type="button" aria-label={`Mais ações para ${account.name}`} aria-haspopup="menu" aria-expanded={openMenu?.account.id === account.id} disabled={busyUserId === account.id} onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect(); setOpenMenu({ account, top: Math.min(rect.bottom + 6, window.innerHeight - 160), right: Math.max(12, window.innerWidth - rect.right) }); }}><MoreMockIcon className="ph" /></button></div></td>
|
||||
</tr>)}
|
||||
{!filteredUsers.length && <tr><td colSpan={5}><p className="empty">Nenhum usuário encontrado.</p></td></tr>}
|
||||
{!filteredUsers.length && <tr><td colSpan={6}><p className="empty">Nenhum usuário encontrado.</p></td></tr>}
|
||||
</tbody></table></div>}
|
||||
</>}
|
||||
|
||||
@@ -396,10 +515,13 @@ export const SuperAdmin: React.FC = () => {
|
||||
<button type="button" className="menu-scrim" aria-label="Fechar menu" onClick={() => setOpenMenu(null)} />
|
||||
<div className="menu" role="menu" style={{ top: openMenu.top, right: openMenu.right, transformOrigin: 'top right' }}>
|
||||
<button role="menuitem" type="button" onClick={() => void resetPassword(openMenu.account)}>Redefinir senha</button>
|
||||
{openMenu.account.role !== 'admin' && openMenu.account.isActive && <button role="menuitem" type="button" onClick={() => void impersonate(openMenu.account)}>Entrar como usuário</button>}
|
||||
<button role="menuitem" type="button" onClick={() => void updateUser(openMenu.account, { isActive: !openMenu.account.isActive })}>{openMenu.account.isActive ? 'Desativar conta' : 'Ativar conta'}</button>
|
||||
{openMenu.account.id !== user?.id && <button role="menuitem" type="button" className="bad-text" onClick={() => deleteUser(openMenu.account)}>Excluir conta</button>}
|
||||
</div>
|
||||
</>, document.body)}
|
||||
{deleteDialog}
|
||||
{bulkDialog}
|
||||
{bulkInviteDialog}
|
||||
</main>;
|
||||
};
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
ArrowSquareOutIcon as ExternalLink,
|
||||
CircleNotchIcon as Loader2,
|
||||
PencilIcon as Pencil,
|
||||
PlusIcon as Plus,
|
||||
FloppyDiskIcon as Save,
|
||||
TrashIcon as Trash2,
|
||||
UploadSimpleIcon as Upload,
|
||||
|
||||
@@ -24,6 +24,6 @@ export const YouPage: React.FC = () => {
|
||||
<Group title="Conta" entries={[{ label: 'Notificações', to: paths.notifications, icon: BellIcon }, { label: 'Dados pessoais', to: paths.account, icon: UserIcon }]} />
|
||||
</> : <><div className="m-signin"><UserIcon className="m-ic xl" /><h2>Entre para continuar</h2><p>Com uma conta gratuita você assiste aos cursos, salva o progresso e participa da comunidade.</p><Link className="btn m-big" to={paths.signUp}>Criar conta</Link><Link className="btn sec m-big" to={paths.signIn}>Entrar</Link></div><Group title="Materiais" entries={[{ label: 'Biblioteca', to: paths.library, icon: FolderIcon }]} /></>}
|
||||
<section className="m-group"><h2>Aparência</h2><div className="m-list"><div className="m-row"><span className="m-ic"><MoonIcon className="ph" /></span><span className="m-rt"><b>Modo escuro</b></span><button className="sw" type="button" role="switch" aria-checked={theme === 'dark'} aria-label="Modo escuro" onClick={toggleTheme} /></div></div></section>
|
||||
{user && <section className="m-group"><div className="m-list"><button className="m-row m-danger" type="button" onClick={() => { logout(); navigate(paths.explore); }}><span className="m-ic"><SignOutIcon className="ph" /></span><span className="m-rt"><b>Sair</b></span></button></div></section>}
|
||||
{user && <section className="m-group"><div className="m-list"><button className="m-row m-danger" type="button" onClick={() => { void logout().then(() => navigate(paths.explore)); }}><span className="m-ic"><SignOutIcon className="ph" /></span><span className="m-rt"><b>Sair</b></span></button></div></section>}
|
||||
</main>;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user