refactor: consolidate formations into trails
All checks were successful
CI / Validate frontend and API (push) Successful in 43s
CI / Build and publish Docker images (push) Successful in 17s

This commit is contained in:
Cauê Faleiros
2026-09-04 17:04:26 -03:00
parent 895b0dd00e
commit c18e63f0e4
7 changed files with 21 additions and 21 deletions

View File

@@ -17,8 +17,8 @@ export const LearningPathRow: React.FC<LearningPathRowProps> = ({ paths, courses
return <>
<section className="mx-auto w-full max-w-[1440px] px-6 py-6 md:px-12">
<div className="mb-4 flex items-baseline gap-3">
<h2 className="font-display text-xl font-bold text-gray-100 md:text-2xl">Formações</h2>
<span className="text-xs font-semibold uppercase tracking-wider text-gray-500">{paths.length} {paths.length === 1 ? 'formação' : 'formações'}</span>
<h2 className="font-display text-xl font-bold text-gray-100 md:text-2xl">Trilhas</h2>
<span className="text-xs font-semibold uppercase tracking-wider text-gray-500">{paths.length} {paths.length === 1 ? 'trilha' : 'trilhas'}</span>
</div>
<div className="flex gap-5 overflow-x-auto pb-4 hide-scrollbar snap-x snap-mandatory">
{paths.map((path) => <button key={path.id} onClick={() => setSelectedPath(path)} className="group relative w-[300px] shrink-0 snap-start overflow-hidden rounded-xl border border-white/10 bg-zinc-950 text-left shadow-xl transition hover:-translate-y-1 hover:border-orange-500/60">
@@ -27,7 +27,7 @@ export const LearningPathRow: React.FC<LearningPathRowProps> = ({ paths, courses
<div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
<span className="absolute bottom-3 left-3 rounded-full bg-black/60 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-white backdrop-blur">{path.courses.length} {path.courses.length === 1 ? 'curso' : 'cursos'}</span>
</div>
<div className="p-4"><h3 className="truncate font-semibold text-white group-hover:text-orange-300">{path.title}</h3><p className="mt-1 line-clamp-2 min-h-10 text-sm leading-relaxed text-gray-500">{path.description || 'Uma trilha organizada para avançar passo a passo.'}</p><span className="mt-3 inline-flex items-center gap-1 text-sm font-semibold text-orange-400">Ver formação <ArrowRight className="h-4 w-4" /></span></div>
<div className="p-4"><h3 className="truncate font-semibold text-white group-hover:text-orange-300">{path.title}</h3><p className="mt-1 line-clamp-2 min-h-10 text-sm leading-relaxed text-gray-500">{path.description || 'Uma trilha organizada para avançar passo a passo.'}</p><span className="mt-3 inline-flex items-center gap-1 text-sm font-semibold text-orange-400">Ver trilha <ArrowRight className="h-4 w-4" /></span></div>
</button>)}
</div>
</section>

View File

@@ -8,12 +8,12 @@ import { useNavigate } from 'react-router-dom';
const roleLabel: Record<ManagedUser['role'], string> = { admin: 'Superadmin', instructor: 'Instrutor', student: 'Aluno' };
type CourseOption = { id: string; title: string; status: string };
type HomeConfiguration = { featuredCourseId: string | null; courseOrder: string[]; defaultCoverImageUrl: string | null; courses: CourseOption[] };
const emptyPathInput = (): LearningPathInput => ({ title: '', description: '', coverImageUrl: null, coverImageZoom: 1, coverImagePositionX: 50, coverImagePositionY: 50, status: 'draft', kind: 'trail', courseIds: [] });
const pathToInput = (path: LearningPath): LearningPathInput => ({ title: path.title, description: path.description, coverImageUrl: path.coverImageUrl, coverImageZoom: path.coverImageZoom, coverImagePositionX: path.coverImagePositionX, coverImagePositionY: path.coverImagePositionY, status: path.status === 'published' ? 'published' : 'draft', kind: path.kind, courseIds: path.courses.map((course) => course.id) });
const emptyPathInput = (): LearningPathInput => ({ title: '', description: '', coverImageUrl: null, coverImageZoom: 1, coverImagePositionX: 50, coverImagePositionY: 50, status: 'draft', courseIds: [] });
const pathToInput = (path: LearningPath): LearningPathInput => ({ title: path.title, description: path.description, coverImageUrl: path.coverImageUrl, coverImageZoom: path.coverImageZoom, coverImagePositionX: path.coverImagePositionX, coverImagePositionY: path.coverImagePositionY, status: path.status === 'published' ? 'published' : 'draft', courseIds: path.courses.map((course) => course.id) });
export const SuperAdmin: React.FC = () => {
const { user } = useAuth(); const { showToast } = useToast(); const navigate = useNavigate();
const [activeTab, setActiveTab] = useState<'courses' | 'trails' | 'formations' | 'home' | 'access'>('courses');
const [activeTab, setActiveTab] = useState<'courses' | 'trails' | 'home' | 'access'>('courses');
const [users, setUsers] = useState<ManagedUser[]>([]); const [analytics, setAnalytics] = useState<PlatformAnalytics | null>(null);
const [categories, setCategories] = useState<Array<{ id: string; name: string; position: number; isActive: boolean }>>([]);
const [homeConfiguration, setHomeConfiguration] = useState<HomeConfiguration | null>(null); const [paths, setPaths] = useState<LearningPath[]>([]);
@@ -36,7 +36,7 @@ export const SuperAdmin: React.FC = () => {
const moveHomeCourse = (courseId: string, direction: -1 | 1) => setHomeConfiguration((current) => { if (!current) return current; const published = current.courses.filter((course) => course.status === 'published'); const order = new Map<string, number>(current.courseOrder.map((id, index): [string, number] => [id, index])); const arranged = [...published].sort((a, b) => (order.get(a.id) ?? 999_999) - (order.get(b.id) ?? 999_999) || a.title.localeCompare(b.title)); const index = arranged.findIndex((course) => course.id === courseId); const target = index + direction; if (index < 0 || target < 0 || target >= arranged.length) return current; [arranged[index], arranged[target]] = [arranged[target], arranged[index]]; return { ...current, courseOrder: arranged.map((course) => course.id) }; });
const showUserDetail = async (account: ManagedUser) => { setLoadingDetailId(account.id); try { const response = await adminApi.userDetail(account.id); setSelectedUser(response.data); } catch { showToast('Não foi possível carregar os detalhes do usuário.', 'error'); } finally { setLoadingDetailId(null); } };
const exportUsers = () => { const csv = ['Nome,E-mail,Perfil,Status,Cadastro', ...filteredUsers.map((account) => [account.name, account.email, roleLabel[account.role], account.isActive ? 'Ativo' : 'Desativado', new Intl.DateTimeFormat('pt-BR').format(new Date(account.createdAt))].map((value) => `"${value.replaceAll('"', '""')}"`).join(','))].join('\n'); const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' })); const link = document.createElement('a'); link.href = url; link.download = 'usuarios-compor-hub.csv'; link.click(); URL.revokeObjectURL(url); };
const openNewPath = (kind: 'trail' | 'formation') => { setEditingPath(null); setPathInput({ ...emptyPathInput(), kind }); setIsPathEditorOpen(true); }; const openEditPath = (path: LearningPath) => { setEditingPath(path); setPathInput(pathToInput(path)); setIsPathEditorOpen(true); }; const closePathEditor = () => { if (!isSavingPath) setIsPathEditorOpen(false); };
const openNewPath = () => { setEditingPath(null); setPathInput(emptyPathInput()); setIsPathEditorOpen(true); }; const openEditPath = (path: LearningPath) => { setEditingPath(path); setPathInput(pathToInput(path)); setIsPathEditorOpen(true); }; const closePathEditor = () => { if (!isSavingPath) setIsPathEditorOpen(false); };
const togglePathCourse = (courseId: string) => setPathInput((current) => ({ ...current, courseIds: current.courseIds.includes(courseId) ? current.courseIds.filter((id) => id !== courseId) : [...current.courseIds, courseId] }));
const movePathCourse = (courseId: string, direction: -1 | 1) => setPathInput((current) => { const index = current.courseIds.indexOf(courseId); const target = index + direction; if (index < 0 || target < 0 || target >= current.courseIds.length) return current; const courseIds = [...current.courseIds]; [courseIds[index], courseIds[target]] = [courseIds[target], courseIds[index]]; return { ...current, courseIds }; });
const uploadPathCover = async (file: File) => { if (!file.type.startsWith('image/')) { showToast('Selecione uma imagem JPG, PNG ou WebP.', 'error'); return; } setIsUploadingCover(true); try { const response = await instructorApi.uploadCover(file); setPathInput((current) => ({ ...current, coverImageUrl: response.data.coverImageUrl })); showToast('Capa da formação enviada.', 'success'); } catch { showToast('Não foi possível enviar a capa.', 'error'); } finally { setIsUploadingCover(false); } };
@@ -47,10 +47,9 @@ export const SuperAdmin: React.FC = () => {
return <main className="min-h-screen pt-28 pb-20 px-6 md:px-12 max-w-[1440px] mx-auto">
<div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-8"><div><div className="flex items-center gap-2 text-orange-400 text-xs font-bold uppercase tracking-wider mb-3"><ShieldCheck className="w-4 h-4" /> Superadmin</div><h1 className="text-3xl md:text-4xl font-bold text-white">Painel Administrativo</h1><p className="text-gray-400 mt-2">Organize conteúdo, formações e acessos da plataforma.</p></div><div className="flex flex-wrap gap-3"><button onClick={() => navigate('/gerenciar')} className="inline-flex items-center justify-center gap-2 rounded-full px-5 py-3 text-sm font-semibold bg-orange-500 hover:bg-orange-600 text-white transition-colors">Gerenciar cursos</button><button onClick={() => void loadData()} className="inline-flex items-center justify-center gap-2 rounded-full px-5 py-3 text-sm font-semibold bg-white/10 hover:bg-white/15 text-white transition-colors"><RefreshCw className="w-4 h-4" /> Atualizar</button></div></div>
<div className="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-8"><StatCard icon={<Users className="w-5 h-5" />} label="Usuários" 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" value={instructorUsers} /><StatCard icon={<FolderKanban 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>
<div className="mb-8 flex gap-1 overflow-x-auto border-b border-white/10"><TabButton active={activeTab === 'courses'} onClick={() => setActiveTab('courses')} label="Cursos" /><TabButton active={activeTab === 'trails'} onClick={() => setActiveTab('trails')} label="Trilhas" /><TabButton active={activeTab === 'formations'} onClick={() => setActiveTab('formations')} label="Formações" /><TabButton active={activeTab === 'home'} onClick={() => setActiveTab('home')} label="Página inicial" /><TabButton active={activeTab === 'access'} onClick={() => setActiveTab('access')} label="Acessos" /></div>
<div className="mb-8 flex gap-1 overflow-x-auto border-b border-white/10"><TabButton active={activeTab === 'courses'} onClick={() => setActiveTab('courses')} label="Cursos" /><TabButton active={activeTab === 'trails'} onClick={() => setActiveTab('trails')} label="Trilhas" /><TabButton active={activeTab === 'home'} onClick={() => setActiveTab('home')} label="Página inicial" /><TabButton active={activeTab === 'access'} onClick={() => setActiveTab('access')} label="Acessos" /></div>
{activeTab === 'courses' && <CoursesPanel courses={homeConfiguration?.courses || []} onManage={() => navigate('/gerenciar')} />}
{activeTab === 'trails' && <PathManager title="Trilhas" description="Sequências guiadas de cursos existentes." paths={paths.filter((path) => path.kind === 'trail')} onNew={() => openNewPath('trail')} onEdit={openEditPath} onDelete={deletePath} />}
{activeTab === 'formations' && <PathManager title="Formações" description="Currículos organizados a partir de cursos existentes." paths={paths.filter((path) => path.kind === 'formation')} onNew={() => openNewPath('formation')} onEdit={openEditPath} onDelete={deletePath} />}
{activeTab === 'trails' && <PathManager title="Trilhas" description="Sequências guiadas de cursos existentes." paths={paths} onNew={openNewPath} onEdit={openEditPath} onDelete={deletePath} />}
{activeTab === 'home' && <><BannerManager courses={homeConfiguration?.courses || []} /><HomePanel homeConfiguration={homeConfiguration} homeCourses={homeCourses} categories={categories} newCategory={newCategory} setNewCategory={setNewCategory} setHomeConfiguration={setHomeConfiguration} onCreateCategory={createCategory} onToggleCategory={toggleCategory} onMoveHomeCourse={moveHomeCourse} onSaveHome={saveHomeConfiguration} /></>}
{activeTab === 'access' && <PeoplePanel users={filteredUsers} isLoading={isLoading} query={query} setQuery={setQuery} accessLink={accessLink} inviteEmail={inviteEmail} setInviteEmail={setInviteEmail} inviteRole={inviteRole} setInviteRole={setInviteRole} selectedUser={selectedUser} setSelectedUser={setSelectedUser} updatingUserId={updatingUserId} loadingDetailId={loadingDetailId} currentUserId={user?.id} onInvite={createInvite} onUpdateUser={updateUser} onShowDetail={showUserDetail} onResetPassword={resetPassword} onExport={exportUsers} />}
{isPathEditorOpen && <PathEditor input={pathInput} setInput={setPathInput} courses={homeConfiguration?.courses || []} selectedCourses={selectedPathCourses} editing={Boolean(editingPath)} isSaving={isSavingPath} isUploadingCover={isUploadingCover} coverInputRef={coverInputRef} onClose={closePathEditor} onSave={savePath} onUpload={uploadPathCover} onToggleCourse={togglePathCourse} onMoveCourse={movePathCourse} />}

View File

@@ -0,0 +1,5 @@
-- Trilhas and Formações described the same object: an ordered collection of
-- existing courses. Preserve every record while collapsing the duplicate type.
update learning_paths set kind = 'trail' where kind = 'formation';
drop index if exists learning_paths_kind_index;
alter table learning_paths drop column kind;

View File

@@ -56,7 +56,6 @@ const learningPathSchema = z.object({
coverImagePositionX: z.number().min(0).max(100).default(50),
coverImagePositionY: z.number().min(0).max(100).default(50),
status: z.enum(['draft', 'published']).default('draft'),
kind: z.enum(['trail', 'formation']).default('trail'),
courseIds: z.array(z.string().uuid()).min(1).max(100),
});
@@ -69,7 +68,7 @@ const getLearningPaths = async () => {
p.cover_image_zoom as "coverImageZoom",
p.cover_image_position_x as "coverImagePositionX",
p.cover_image_position_y as "coverImagePositionY",
p.status, p.kind, p.published_at as "publishedAt", p.created_at as "createdAt",
p.status, p.published_at as "publishedAt", p.created_at as "createdAt",
coalesce(jsonb_agg(jsonb_build_object(
'id', c.id, 'title', c.title, 'status', c.status,
'coverImageUrl', c.cover_image_url, 'position', pc.position
@@ -176,10 +175,10 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
const courseIds = await validatePathCourses(client, input);
const path = await client.query<{ id: string }>(
`insert into learning_paths (
title, description, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, kind, published_at
) values ($1, $2, $3, $4, $5, $6, $7::course_status, $8, case when $7 = 'published' then now() else null end)
title, description, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, published_at
) values ($1, $2, $3, $4, $5, $6, $7::course_status, case when $7 = 'published' then now() else null end)
returning id`,
[input.title, input.description, input.coverImageUrl, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, input.kind],
[input.title, input.description, input.coverImageUrl, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status],
);
await writePathCourses(client, path.rows[0].id, courseIds);
await client.query('commit');
@@ -205,11 +204,11 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
const path = await client.query<{ id: string }>(
`update learning_paths set
title = $2, description = $3, cover_image_url = $4, cover_image_zoom = $5,
cover_image_position_x = $6, cover_image_position_y = $7, status = $8::course_status, kind = $9,
cover_image_position_x = $6, cover_image_position_y = $7, status = $8::course_status,
published_at = case when $8 = 'published' then coalesce(published_at, now()) else null end
where id = $1
returning id`,
[pathId, input.title, input.description, input.coverImageUrl, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, input.kind],
[pathId, input.title, input.description, input.coverImageUrl, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status],
);
if (!path.rows[0]) {
await client.query('rollback');

View File

@@ -153,7 +153,7 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
app.get('/paths', async () => {
const result = await pool.query(
`select
p.id, p.title, p.description, p.kind,
p.id, p.title, p.description,
coalesce(p.cover_image_url, (
select value #>> '{}' from platform_settings where key = 'media.defaultCoverImageUrl'
)) as "coverImageUrl",

View File

@@ -43,7 +43,6 @@ export interface LearningPath {
coverImagePositionX: number;
coverImagePositionY: number;
status: 'draft' | 'published' | 'archived';
kind: 'trail' | 'formation';
publishedAt: string | null;
createdAt: string;
courses: LearningPathCourse[];
@@ -56,7 +55,6 @@ export interface LearningPathInput {
coverImagePositionX: number;
coverImagePositionY: number;
status: 'draft' | 'published';
kind: 'trail' | 'formation';
courseIds: string[];
}
export interface HomeBannerInput {

View File

@@ -48,7 +48,6 @@ export type PublicLearningPath = {
id: string;
title: string;
description: string;
kind: 'trail' | 'formation';
coverImageUrl: string | null;
coverImageZoom: number;
coverImagePositionX: number;