486 lines
37 KiB
TypeScript
486 lines
37 KiB
TypeScript
import React, { useEffect, useMemo, useState } from 'react';
|
||
import { Link } from 'react-router-dom';
|
||
import { ChatCircleIcon, 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';
|
||
import { CourseCoverImage } from '../components/CourseCoverImage';
|
||
import { Thumb } from '../components/catalog/Artwork';
|
||
import { Select } from '../components/ui/Select';
|
||
import { Switch } from '../components/ui/Switch';
|
||
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 { formatMinutes, lessonDuration, shortDate } from '../lib/format';
|
||
import { useIsMobile } from '../hooks/useMediaQuery';
|
||
import { paths } from '../lib/routes';
|
||
|
||
const formatSize = (bytes?: number | null) => {
|
||
if (!bytes) return '';
|
||
if (bytes < 1024) return `${bytes} B`;
|
||
const units = ['KB', 'MB', 'GB'];
|
||
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)) - 1, units.length - 1);
|
||
return `${new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 1 }).format(bytes / 1024 ** (index + 1))} ${units[index]}`;
|
||
};
|
||
|
||
const newLessonId = () => `lesson-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||
const statusLabel = (lesson: Lesson) => {
|
||
const status = lesson.media?.[0]?.status;
|
||
if (!lesson.media?.length) return <span className="state">Sem vídeo</span>;
|
||
if (status === 'ready') return <span className="state done"><CheckCircleMockIcon className="ph" /> Pronto</span>;
|
||
if (status === 'failed') return <span className="state bad"><WarningCircleMockIcon className="ph" /> Falhou no envio</span>;
|
||
return <span className="state"><SpinnerMockIcon className="ph spin" /> Processando</span>;
|
||
};
|
||
|
||
const CourseEditor: React.FC<{
|
||
initialData?: Course;
|
||
categories: string[];
|
||
onClose: () => void;
|
||
onSaved: () => void;
|
||
}> = ({ initialData, categories, onClose, onSaved }) => {
|
||
const { showToast } = useToast();
|
||
const isMobile = useIsMobile();
|
||
const [title, setTitle] = useState(initialData?.title || '');
|
||
const [description, setDescription] = useState(initialData?.description || '');
|
||
const [category, setCategory] = useState(initialData?.category || categories[0] || '');
|
||
const [status, setStatus] = useState<Course['status']>(initialData?.status || 'draft');
|
||
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);
|
||
const [draggedLessonId, setDraggedLessonId] = useState<string | null>(null);
|
||
const [coverConfigured, setCoverConfigured] = useState(false);
|
||
const [bunnyConfigured, setBunnyConfigured] = useState(false);
|
||
const [coverUploading, setCoverUploading] = useState(false);
|
||
const [videoUploading, setVideoUploading] = useState(false);
|
||
const [saving, setSaving] = useState(false);
|
||
const [attachments, setAttachments] = useState<Attachment[]>(initialData?.attachments || []);
|
||
const [assetConfigured, setAssetConfigured] = useState(false);
|
||
const [assetUploading, setAssetUploading] = useState(false);
|
||
const [assetMessage, setAssetMessage] = useState('');
|
||
const [newLinkName, setNewLinkName] = useState('');
|
||
const [newLinkUrl, setNewLinkUrl] = useState('');
|
||
const coverInput = React.useRef<HTMLInputElement>(null);
|
||
const assetInput = React.useRef<HTMLInputElement>(null);
|
||
|
||
useEffect(() => {
|
||
instructorApi.coverConfiguration().then((response) => setCoverConfigured(response.data.configured)).catch(() => setCoverConfigured(false));
|
||
instructorApi.bunnyConfiguration().then((response) => setBunnyConfigured(response.data.configured)).catch(() => setBunnyConfigured(false));
|
||
instructorApi.assetConfiguration().then((response) => setAssetConfigured(response.data.configured)).catch(() => setAssetConfigured(false));
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!category && categories.length) setCategory(categories[0]);
|
||
}, [categories, category]);
|
||
|
||
const updateLesson = (lessonId: string, patch: Partial<Lesson>) => {
|
||
setLessons((current) => current.map((lesson) => lesson.id === lessonId ? { ...lesson, ...patch } : lesson));
|
||
};
|
||
|
||
const addLesson = () => {
|
||
const lesson: Lesson = { id: newLessonId(), title: 'Nova aula', duration: '—', videoUrl: '', isFree: false, media: [], attachments: [] };
|
||
setLessons((current) => [...current, lesson]);
|
||
setEditingLessonId(lesson.id);
|
||
};
|
||
|
||
const removeLesson = (lessonId: string) => {
|
||
setLessons((current) => current.filter((lesson) => lesson.id !== lessonId));
|
||
setEditingLessonId(null);
|
||
};
|
||
|
||
const dropLesson = (targetId: string) => {
|
||
if (!draggedLessonId || draggedLessonId === targetId) return;
|
||
setLessons((current) => {
|
||
const ids = current.map((lesson) => lesson.id);
|
||
const from = ids.indexOf(draggedLessonId);
|
||
const to = ids.indexOf(targetId);
|
||
if (from < 0 || to < 0) return current;
|
||
const next = [...current];
|
||
const [moved] = next.splice(from, 1);
|
||
next.splice(to, 0, moved);
|
||
return next;
|
||
});
|
||
setDraggedLessonId(null);
|
||
};
|
||
|
||
const uploadCover = async (file?: File) => {
|
||
if (!file) return;
|
||
if (!coverConfigured) {
|
||
showToast('O envio de imagens ainda não está configurado.', 'error');
|
||
return;
|
||
}
|
||
setCoverUploading(true);
|
||
try {
|
||
const response = await instructorApi.uploadCover(file);
|
||
setCover(response.data.coverImageUrl);
|
||
showToast('Capa enviada.', 'success');
|
||
} catch {
|
||
showToast('Não foi possível enviar a capa.', 'error');
|
||
} finally {
|
||
setCoverUploading(false);
|
||
}
|
||
};
|
||
|
||
const uploadVideo = async (file?: File) => {
|
||
if (!file) return;
|
||
if (!bunnyConfigured) {
|
||
showToast('O envio de vídeos ainda não está disponível.', 'error');
|
||
return;
|
||
}
|
||
setVideoUploading(true);
|
||
try {
|
||
const created = await instructorApi.createBunnyVideo(file.name.replace(/\.[^.]+$/, ''));
|
||
const uploaded = await instructorApi.uploadBunnyVideo(created.data.id, file);
|
||
const media: LessonMedia = { provider: 'bunny', externalId: uploaded.data.id, status: uploaded.data.status, durationSeconds: uploaded.data.durationSeconds };
|
||
const lesson: Lesson = {
|
||
id: newLessonId(),
|
||
title: file.name.replace(/\.[^.]+$/, ''),
|
||
duration: uploaded.data.durationSeconds ? formatMinutes(Math.max(1, Math.round(uploaded.data.durationSeconds / 60))) : '—',
|
||
videoUrl: '',
|
||
mediaProvider: 'bunny',
|
||
media: [media],
|
||
isFree: false,
|
||
attachments: [],
|
||
};
|
||
setLessons((current) => [...current, lesson]);
|
||
setEditingLessonId(lesson.id);
|
||
showToast(uploaded.data.status === 'ready' ? 'Vídeo adicionado à aula.' : 'Vídeo enviado; o processamento continua no Bunny.', 'success');
|
||
} catch {
|
||
showToast('Não foi possível enviar o vídeo.', 'error');
|
||
} finally {
|
||
setVideoUploading(false);
|
||
}
|
||
};
|
||
|
||
const uploadAsset = async (file?: File) => {
|
||
if (!file) return;
|
||
if (!assetConfigured) { showToast('O envio de materiais ainda não está configurado.', 'error'); return; }
|
||
setAssetUploading(true);
|
||
setAssetMessage('Enviando arquivo…');
|
||
try {
|
||
const response = await instructorApi.uploadAsset(file);
|
||
const type: AttachmentType = response.data.kind === 'spreadsheet' ? 'spreadsheet' : response.data.kind === 'archive' ? 'zip' : file.name.toLowerCase().endsWith('.pdf') ? 'pdf' : 'doc';
|
||
setAttachments((current) => [...current, { id: `asset-${response.data.key}`, name: file.name, type, url: response.data.assetUrl, sizeBytes: response.data.sizeBytes, size: formatSize(response.data.sizeBytes), createdAt: new Date().toISOString() }]);
|
||
setAssetMessage('Material anexado. Salve o curso para confirmar.');
|
||
showToast('Material anexado.', 'success');
|
||
} catch {
|
||
setAssetMessage('');
|
||
showToast('Não foi possível enviar o material.', 'error');
|
||
} finally {
|
||
setAssetUploading(false);
|
||
}
|
||
};
|
||
|
||
const addLink = () => {
|
||
if (!newLinkName.trim() || !/^https?:\/\//i.test(newLinkUrl)) {
|
||
showToast('Informe um nome e um link HTTP ou HTTPS válido.', 'error');
|
||
return;
|
||
}
|
||
setAttachments((current) => [...current, { id: `link-${Date.now()}`, name: newLinkName.trim(), type: 'link', url: newLinkUrl, createdAt: new Date().toISOString() }]);
|
||
setNewLinkName('');
|
||
setNewLinkUrl('');
|
||
showToast('Link adicionado. Salve o curso para confirmar.', 'success');
|
||
};
|
||
|
||
const removeAttachment = (attachmentId: string) => setAttachments((current) => current.filter((attachment) => attachment.id !== attachmentId));
|
||
|
||
const save = async (statusOverride?: Course['status']) => {
|
||
const nextStatus = statusOverride || status;
|
||
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; }
|
||
setSaving(true);
|
||
try {
|
||
const seconds = lessons.reduce((total, lesson) => total + (lesson.media?.[0]?.durationSeconds || 0), 0);
|
||
await saveCourse({
|
||
id: initialData?.id || `course-${Date.now()}`,
|
||
title: title.trim(),
|
||
description,
|
||
category,
|
||
status: nextStatus,
|
||
thumbnail: cover || '/course-placeholder.svg',
|
||
coverImageZoom: initialData?.coverImageZoom || 1,
|
||
coverImagePositionX: initialData?.coverImagePositionX ?? 50,
|
||
coverImagePositionY: initialData?.coverImagePositionY ?? 50,
|
||
duration: seconds ? formatMinutes(Math.round(seconds / 60)) : 'Processando',
|
||
instructor: initialData?.instructor || '',
|
||
views: initialData?.views || 0,
|
||
progress: initialData?.progress || 0,
|
||
lessons,
|
||
attachments,
|
||
});
|
||
setStatus(nextStatus);
|
||
showToast('Curso salvo.', 'success');
|
||
onSaved();
|
||
} catch (error) {
|
||
showToast(error instanceof Error ? error.message : 'Não foi possível salvar o curso.', 'error');
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const publish = async () => {
|
||
await save(status === 'draft' ? 'published' : status);
|
||
};
|
||
|
||
if (isMobile) {
|
||
const editingLesson = lessons.find((lesson) => lesson.id === editingLessonId);
|
||
return <main className="m-page m-gut enter">
|
||
<header className="m-large"><h1>Gerenciar cursos</h1><button className="m-tb" type="button" onClick={() => void publish()} disabled={saving}>{saving ? 'Salvando…' : status === 'published' ? 'Salvar' : 'Publicar'}</button></header>
|
||
<button className="link" type="button" onClick={onClose} style={{ marginBottom: 12 }}>← Voltar para cursos</button>
|
||
<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>
|
||
<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 }}>
|
||
<span className="m-ic"><UploadMockIcon className="ph" /></span>
|
||
<span className="m-rt"><b>{bunnyConfigured ? 'Adicionar vídeos' : 'Envio de vídeos indisponível'}</b><small>MP4 ou MOV</small></span>
|
||
<input type="file" accept="video/*" hidden disabled={!bunnyConfigured || videoUploading} onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadVideo(file); }} />
|
||
</label>
|
||
</div></section>
|
||
<section className="m-group"><h2>Detalhes</h2><div className="m-list">
|
||
<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>
|
||
</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>)}
|
||
<label className="m-row m-add" style={{ opacity: assetConfigured ? 1 : 0.6 }}><span className="m-ic"><UploadMockIcon className="ph" /></span><span className="m-rt"><b>{assetUploading ? 'Enviando…' : 'Enviar arquivo'}</b><small>PDF, DOCX, XLSX, CSV ou ZIP</small></span><input ref={assetInput} type="file" accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.zip" hidden disabled={!assetConfigured || assetUploading} onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadAsset(file); }} /></label>
|
||
</div>
|
||
{assetMessage && <p className="muted" style={{ fontSize: 13, marginTop: 8 }}>{assetMessage}</p>}
|
||
{!assetConfigured && <p className="muted" style={{ fontSize: 13, marginTop: 8 }}>O armazenamento de materiais ainda não está configurado.</p>}
|
||
<div className="m-list" style={{ marginTop: 10 }}><label className="m-field"><span>Nome do link</span><input value={newLinkName} onChange={(event) => setNewLinkName(event.target.value)} /></label><label className="m-field"><span>URL</span><input type="url" value={newLinkUrl} onChange={(event) => setNewLinkUrl(event.target.value)} placeholder="https://" /></label></div>
|
||
<button className="link" type="button" style={{ marginTop: 10 }} onClick={addLink}>Adicionar link</button>
|
||
</section>
|
||
<div style={{ height: 60 }} />
|
||
{editingLesson && <div className="scrim" role="dialog" aria-modal="true" aria-label={`Editar aula ${editingLesson.title}`} onMouseDown={(event) => { if (event.target === event.currentTarget) setEditingLessonId(null); }}>
|
||
<div className="dialog" style={{ maxWidth: 420 }}>
|
||
<header><div><h2>Aula</h2><p>{editingLesson.title}</p></div><button type="button" className="iconbtn" onClick={() => setEditingLessonId(null)} aria-label="Fechar">×</button></header>
|
||
<div className="form">
|
||
<div className="field"><label htmlFor="m-lesson-title">Título da aula</label><input id="m-lesson-title" value={editingLesson.title} onChange={(event) => updateLesson(editingLesson.id, { title: event.target.value })} /></div>
|
||
<div className="toggle"><span>Aberta para visitantes</span><Switch checked={editingLesson.isFree} onChange={(checked) => updateLesson(editingLesson.id, { isFree: checked })} label="Aberta para visitantes" /></div>
|
||
<button className="btn sec bad-text" type="button" onClick={() => removeLesson(editingLesson.id)}>Excluir aula</button>
|
||
</div>
|
||
</div>
|
||
</div>}
|
||
</main>;
|
||
}
|
||
|
||
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 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>}
|
||
<button className="btn" type="button" onClick={() => void publish()} disabled={saving}>{saving ? 'Salvando…' : status === 'published' ? 'Salvar' : 'Publicar'}</button>
|
||
</div>
|
||
</div>
|
||
<div className="split">
|
||
<div>
|
||
<section className="shelf" style={{ marginTop: 0 }}>
|
||
<header><h2>Aulas</h2><button className="btn sec" type="button" onClick={addLesson}><PlusMockIcon className="ph" /> Nova aula</button></header>
|
||
{lessons.length ? <ol className="list">{lessons.map((lesson, index) => <li key={lesson.id}>
|
||
<div className="row" draggable onDragStart={(event) => { setDraggedLessonId(lesson.id); event.dataTransfer.setData('text/plain', lesson.id); event.dataTransfer.effectAllowed = 'move'; }} onDragOver={(event) => event.preventDefault()} onDrop={() => dropLesson(lesson.id)} style={{ gridTemplateColumns: '20px 28px minmax(0, 1fr) auto auto', cursor: 'grab' }}>
|
||
<span style={{ color: 'var(--fg-3)' }}><DragMockIcon className="ph" /></span>
|
||
<span className="i num">{index + 1}</span>
|
||
<span className="t">{lesson.title}<small className="num">{[lessonDuration(lesson), lesson.isFree ? 'Aberta para visitantes' : 'Requer conta'].filter(Boolean).join(' · ')}</small></span>
|
||
{statusLabel(lesson)}
|
||
<button className="iconbtn" type="button" aria-label={`Editar aula ${lesson.title}`} onClick={() => setEditingLessonId((current) => current === lesson.id ? null : lesson.id)}><EditMockIcon className="ph" /></button>
|
||
</div>
|
||
{editingLessonId === lesson.id && <div className="form" style={{ padding: '4px 16px 16px 60px' }}>
|
||
<div className="field"><label htmlFor={`lesson-title-${lesson.id}`}>Título da aula</label><input id={`lesson-title-${lesson.id}`} value={lesson.title} onChange={(event) => updateLesson(lesson.id, { title: event.target.value })} /></div>
|
||
<div className="toggle"><span>Aberta para visitantes</span><Switch checked={lesson.isFree} onChange={(checked) => updateLesson(lesson.id, { isFree: checked })} label="Aberta para visitantes" /></div>
|
||
<div><button className="btn ghost bad-text" type="button" onClick={() => removeLesson(lesson.id)}>Excluir aula</button></div>
|
||
</div>}
|
||
</li>)}</ol> : <p className="empty">Nenhuma aula cadastrada ainda.</p>}
|
||
<label
|
||
className="drop"
|
||
style={{ marginTop: 20, opacity: bunnyConfigured ? 1 : 0.6, cursor: bunnyConfigured ? 'pointer' : 'not-allowed' }}
|
||
onDragOver={(event) => event.preventDefault()}
|
||
onDrop={(event) => { event.preventDefault(); if (bunnyConfigured) void uploadVideo(event.dataTransfer.files[0]); }}
|
||
>
|
||
<UploadMockIcon className="ph" />
|
||
{videoUploading ? 'Enviando vídeo…' : bunnyConfigured ? 'Arraste vídeos aqui para criar aulas' : 'O envio de vídeos ainda não está configurado'}
|
||
<small>MP4 ou MOV</small>
|
||
<input type="file" accept="video/*" hidden disabled={!bunnyConfigured || videoUploading} onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadVideo(file); }} />
|
||
</label>
|
||
</section>
|
||
</div>
|
||
<aside className="side">
|
||
<div className="box">
|
||
<h3>Capa</h3>
|
||
<div style={{ aspectRatio: '16/9', borderRadius: 12, overflow: 'hidden', background: 'var(--bg-2)', marginBottom: 12 }}>
|
||
{cover ? <CourseCoverImage source={cover} alt="Capa do curso" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span className={`tr-${'midia'}`} style={{ display: 'block', width: '100%', height: '100%', background: 'var(--cc)' }} />}
|
||
</div>
|
||
<button className="btn sec" type="button" disabled={!coverConfigured || coverUploading} onClick={() => coverInput.current?.click()}>{coverUploading ? 'Enviando…' : 'Enviar imagem'}</button>
|
||
<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); }} />
|
||
{!coverConfigured && <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>O armazenamento de imagens ainda não está configurado.</p>}
|
||
</div>
|
||
<div className="box">
|
||
<h3>Detalhes</h3>
|
||
<div className="form">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
<div className="box">
|
||
<h3>Materiais</h3>
|
||
<input ref={assetInput} type="file" accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.zip" hidden onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadAsset(file); }} />
|
||
<button className="btn sec" type="button" disabled={!assetConfigured || assetUploading} onClick={() => assetInput.current?.click()}><UploadMockIcon className="ph" /> {assetUploading ? 'Enviando…' : 'Enviar arquivo'}</button>
|
||
{assetMessage && <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>{assetMessage}</p>}
|
||
{!assetConfigured && <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>O armazenamento de materiais ainda não está configurado.</p>}
|
||
{attachments.length ? <div className="list" style={{ marginTop: 12 }}>{attachments.map((attachment) => <div className="file" key={attachment.id} style={{ padding: '8px 0' }}><span className="ic">{attachmentIcon(attachment.type)}</span><span>{attachment.name}<small>{[attachmentLabel(attachment.type), attachment.size].filter(Boolean).join(' · ')}</small></span><button className="iconbtn" type="button" onClick={() => removeAttachment(attachment.id)} aria-label={`Remover ${attachment.name}`}><TrashIcon className="ph" /></button></div>)}</div> : <p className="muted" style={{ fontSize: 12, marginTop: 8 }}>Nenhum material anexado.</p>}
|
||
<div className="form" style={{ marginTop: 14 }}>
|
||
<div className="field"><label htmlFor="material-name">Link — nome</label><input id="material-name" value={newLinkName} onChange={(event) => setNewLinkName(event.target.value)} placeholder="Nome do link" /></div>
|
||
<div className="field"><label htmlFor="material-url">URL</label><input id="material-url" type="url" value={newLinkUrl} onChange={(event) => setNewLinkUrl(event.target.value)} placeholder="https://" /></div>
|
||
<button className="btn sec" type="button" onClick={addLink}>Adicionar link</button>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
</div>
|
||
</main>;
|
||
};
|
||
|
||
export const ManageCourses: React.FC = () => {
|
||
const { showToast } = useToast();
|
||
const { user } = useAuth();
|
||
const isMobile = useIsMobile();
|
||
const [courses, setCourses] = useState<Course[]>([]);
|
||
const [analytics, setAnalytics] = useState<InstructorAnalytics | null>(null);
|
||
const [categories, setCategories] = useState<string[]>([]);
|
||
const [loading, setLoading] = useState(true);
|
||
const [editorOpen, setEditorOpen] = useState(false);
|
||
const [editingCourse, setEditingCourse] = useState<Course | undefined>(undefined);
|
||
const [activeTab, setActiveTab] = useState<'courses' | 'comments'>('courses');
|
||
const [allComments, setAllComments] = useState<Array<{ comment: Comment; courseTitle: string }>>([]);
|
||
const [commentFilter, setCommentFilter] = useState<'all' | 'unanswered' | 'answered'>('all');
|
||
const [replyingTo, setReplyingTo] = useState<string | null>(null);
|
||
const [replyText, setReplyText] = useState('');
|
||
const [sendingReply, setSendingReply] = useState(false);
|
||
const [courseDeleteTarget, setCourseDeleteTarget] = useState<Course | null>(null);
|
||
const [commentDeleteTarget, setCommentDeleteTarget] = useState<Comment | null>(null);
|
||
|
||
const loadData = async () => {
|
||
setLoading(true);
|
||
try {
|
||
const data = await getManagedCourses();
|
||
setCourses(data);
|
||
const response = await instructorApi.analytics();
|
||
setAnalytics(response.data);
|
||
const commentLists = await Promise.all(data.map(async (course) => ({ course, comments: await getComments(course.id).catch(() => []) })));
|
||
setAllComments(commentLists.flatMap(({ course, comments }) => comments.map((comment) => ({ comment, courseTitle: course.title }))));
|
||
} catch {
|
||
showToast('Não foi possível carregar o painel do instrutor.', 'error');
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
useEffect(() => {
|
||
void loadData();
|
||
courseApi.categories().then((response) => setCategories(response.data)).catch(() => setCategories([]));
|
||
}, []);
|
||
|
||
const openNew = () => { setEditingCourse(undefined); setEditorOpen(true); };
|
||
const openCourse = (course: Course) => { setEditingCourse(course); setEditorOpen(true); };
|
||
const closeEditor = () => { setEditorOpen(false); setEditingCourse(undefined); };
|
||
const saved = async () => { closeEditor(); await loadData(); };
|
||
|
||
const duplicate = async (course: Course) => {
|
||
try {
|
||
await duplicateCourse(course.id);
|
||
showToast('Cópia criada como rascunho.', 'success');
|
||
await loadData();
|
||
} catch (error) {
|
||
showToast(error instanceof Error ? error.message : 'Não foi possível duplicar o curso.', 'error');
|
||
}
|
||
};
|
||
|
||
const performDeleteCourse = async () => {
|
||
if (!courseDeleteTarget) return;
|
||
try {
|
||
await deleteCourse(courseDeleteTarget.id);
|
||
setCourseDeleteTarget(null);
|
||
showToast('Curso excluído e removido da listagem.', 'success');
|
||
await loadData();
|
||
} catch {
|
||
showToast('Não foi possível excluir o curso.', 'error');
|
||
}
|
||
};
|
||
|
||
const sendReply = async (commentId: string) => {
|
||
if (!replyText.trim()) return;
|
||
setSendingReply(true);
|
||
try {
|
||
await replyToComment(commentId, replyText);
|
||
setReplyingTo(null);
|
||
setReplyText('');
|
||
showToast('Resposta publicada.', 'success');
|
||
await loadData();
|
||
} catch {
|
||
showToast('Não foi possível publicar a resposta.', 'error');
|
||
} finally {
|
||
setSendingReply(false);
|
||
}
|
||
};
|
||
|
||
const performDeleteComment = async () => {
|
||
if (!commentDeleteTarget) return;
|
||
try {
|
||
await moderateComment(commentDeleteTarget.id);
|
||
setCommentDeleteTarget(null);
|
||
showToast('Comentário removido.', 'success');
|
||
await loadData();
|
||
} catch {
|
||
showToast('Não foi possível remover o comentário.', 'error');
|
||
}
|
||
};
|
||
|
||
const published = useMemo(() => courses.filter((course) => course.status === 'published').length, [courses]);
|
||
const visibleComments = useMemo(() => allComments.filter(({ comment }) => {
|
||
if (commentFilter === 'unanswered') return !comment.reply;
|
||
if (commentFilter === 'answered') return Boolean(comment.reply);
|
||
return true;
|
||
}), [allComments, commentFilter]);
|
||
|
||
const listDialogs = <>
|
||
<ConfirmDialog open={Boolean(courseDeleteTarget)} title="Excluir curso" message={courseDeleteTarget ? `Excluir “${courseDeleteTarget.title}”? O curso será arquivado e removido da listagem.` : ''} confirmLabel="Excluir curso" onCancel={() => setCourseDeleteTarget(null)} onConfirm={() => void performDeleteCourse()} />
|
||
<ConfirmDialog open={Boolean(commentDeleteTarget)} title="Remover comentário" message="Remover este comentário permanentemente? A resposta do professor também será removida." confirmLabel="Remover comentário" onCancel={() => setCommentDeleteTarget(null)} onConfirm={() => void performDeleteComment()} />
|
||
</>;
|
||
|
||
if (editorOpen) return <CourseEditor initialData={editingCourse} categories={categories} onClose={closeEditor} onSaved={() => void saved()} />;
|
||
|
||
if (isMobile) return <main className="m-page m-gut enter">
|
||
<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>
|
||
: <><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>;
|
||
|
||
return <main className="wrap page enter">
|
||
<header className="ptitle"><div><h1>Gerenciar cursos</h1><p>{user?.role === 'superadmin' ? 'Todos os cursos da plataforma.' : 'Seus cursos.'}</p></div><button className="btn" type="button" onClick={openNew}><PlusMockIcon className="ph" /> Novo curso</button></header>
|
||
<div className="stats">
|
||
<div><small>Cursos publicados</small><b className="num">{published}</b></div>
|
||
<div><small>Rascunhos</small><b className="num">{courses.length - published}</b></div>
|
||
<div><small>Alunos matriculados</small><b className="num">{analytics?.learners ?? 0}</b></div>
|
||
<div><small>Perguntas sem resposta</small><b className="num">{analytics?.unansweredComments ?? 0}</b></div>
|
||
</div>
|
||
<div className="seg" role="group" aria-label="Gerenciar cursos" style={{ marginBottom: 24 }}>
|
||
<button type="button" aria-pressed={activeTab === 'courses'} onClick={() => setActiveTab('courses')}>Cursos</button>
|
||
<button type="button" aria-pressed={activeTab === 'comments'} onClick={() => setActiveTab('comments')}>Discussões <span className="num">{allComments.length}</span></button>
|
||
</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>)}
|
||
</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>;
|
||
};
|