Files
compor-academy/services/db.ts
Cauê Faleiros 21085e887d
All checks were successful
CI / Validate frontend and API (push) Successful in 2m22s
CI / Build and publish Docker images (push) Successful in 1m6s
feat: finalize academy redesign and production readiness
Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
2026-11-05 15:06:53 -03:00

423 lines
15 KiB
TypeScript

import { Attachment, AttachmentType, Comment, Course, Lesson, LessonMedia } from '../types';
import { apiRequest, courseApi, downloadApi, DownloadRecord, InstructorSummary } from './api';
export const initDB = async (): Promise<void> => undefined;
type ApiAsset = {
id: string;
name: string;
kind: 'document' | 'spreadsheet' | 'archive' | 'image' | 'link';
url: string;
sizeBytes: number | null;
createdAt: string;
description: string;
};
export type ApiCourse = {
id: string;
title: string;
description: string;
category: string;
coverImageUrl: string | null;
coverImageZoom: number;
coverImagePositionX: number;
coverImagePositionY: number;
status: 'draft' | 'published' | 'archived';
progress?: number;
views?: number;
learners?: number;
updatedAt?: string;
lastActivity?: string | null;
instructor: { id: string; name: string };
lessons: Array<{
id: string;
title: string;
description: string;
durationSeconds: number | null;
accessLevel: 'public' | 'enrolled';
media: Array<{
id: string;
provider: string;
externalId: string;
playbackUrl: string | null;
embedUrl: string | null;
status: 'processing' | 'ready' | 'failed';
durationSeconds: number | null;
}>;
assets: ApiAsset[];
}>;
assets: ApiAsset[];
};
export type PublicLearningPath = {
id: string;
title: string;
description: string;
coverImageUrl: string | null;
coverImageZoom: number;
coverImagePositionX: number;
coverImagePositionY: number;
courses: Array<{
id: string;
title: string;
category: string;
coverImageUrl: string | null;
position: number;
}>;
};
export type PublicHomeBanner = {
id: string;
kind: 'course' | 'custom';
courseId: string | null;
imageUrl: string | null;
title: string;
description: string;
position: number;
courseTitle: string | null;
courseDescription: string | null;
courseImageUrl: string | null;
coverImageZoom: number | null;
coverImagePositionX: number | null;
coverImagePositionY: number | null;
};
const toAttachmentType = (kind: ApiAsset['kind']): AttachmentType => {
if (kind === 'document') return 'doc';
if (kind === 'archive') return 'zip';
return kind;
};
const toAttachment = (asset: ApiAsset): Attachment => ({
id: asset.id,
name: asset.name,
type: toAttachmentType(asset.kind),
url: asset.url,
size: asset.sizeBytes === null ? undefined : formatBytes(asset.sizeBytes),
sizeBytes: asset.sizeBytes ?? undefined,
createdAt: asset.createdAt,
description: asset.description,
});
const formatBytes = (bytes: number) => {
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 toDuration = (seconds: number | null) => {
if (!seconds || seconds < 1) return '—';
const totalSeconds = Math.round(seconds);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const remainingSeconds = totalSeconds % 60;
if (hours) return `${hours}h ${String(minutes).padStart(2, '0')}min`;
if (minutes) return `${minutes}min`;
return `${remainingSeconds}s`;
};
const toCourseDuration = (lessons: ApiCourse['lessons']) => {
const seconds = lessons.reduce((total, lesson) => total + (lesson.media[0]?.durationSeconds ?? lesson.durationSeconds ?? 0), 0);
if (seconds) return toDuration(seconds);
return lessons.length ? 'Processando' : '—';
};
export const toCourse = (course: ApiCourse): Course => ({
id: course.id,
title: course.title,
description: course.description,
category: course.category,
thumbnail: course.coverImageUrl || '/course-placeholder.svg',
coverImageZoom: course.coverImageZoom || 1,
coverImagePositionX: course.coverImagePositionX ?? 50,
coverImagePositionY: course.coverImagePositionY ?? 50,
instructor: course.instructor.name,
instructorId: course.instructor.id,
status: course.status === 'draft' ? 'draft' : 'published',
progress: course.progress,
views: course.views,
learners: course.learners,
updatedAt: course.updatedAt,
lastActivity: course.lastActivity || undefined,
duration: toCourseDuration(course.lessons),
lessons: course.lessons.map((lesson): Lesson => {
const media: LessonMedia[] = lesson.media.map((item) => ({
id: item.id,
provider: item.provider,
externalId: item.externalId,
playbackUrl: item.playbackUrl,
embedUrl: item.embedUrl,
status: item.status,
durationSeconds: item.durationSeconds,
}));
return {
id: lesson.id,
title: lesson.title,
description: lesson.description,
duration: toDuration(media[0]?.durationSeconds ?? lesson.durationSeconds),
isFree: lesson.accessLevel === 'public',
videoUrl: media[0]?.playbackUrl || media[0]?.embedUrl || '',
mediaProvider: media[0]?.provider,
media,
attachments: lesson.assets.map(toAttachment),
};
}),
attachments: course.assets.map(toAttachment),
});
const toSeconds = (duration: string) => {
const hours = Number(duration.match(/(\d+)h/)?.[1] || 0);
const minutes = Number(duration.match(/(\d+)m/)?.[1] || 0);
const seconds = hours * 3600 + minutes * 60;
return seconds || null;
};
const toAssetKind = (type: AttachmentType): ApiAsset['kind'] => {
if (type === 'doc' || type === 'pdf') return 'document';
if (type === 'zip') return 'archive';
if (type === 'video') return 'link';
return type;
};
const toAssetPayload = (attachment: Attachment) => ({
name: attachment.name,
kind: toAssetKind(attachment.type),
url: attachment.url,
sizeBytes: attachment.sizeBytes ?? parseSizeBytes(attachment.size),
description: attachment.description || '',
accessLevel: 'enrolled' as const,
});
const parseSizeBytes = (value?: string) => {
if (!value) return null;
const match = value.trim().replace(',', '.').match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$/i);
if (!match) return null;
const units: Record<string, number> = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3 };
return Math.round(Number(match[1]) * units[match[2].toUpperCase()]);
};
const toCoursePayload = (course: Course) => ({
title: course.title,
description: course.description,
category: course.category,
coverImageUrl: course.thumbnail && /^https?:\/\//.test(course.thumbnail) ? course.thumbnail : null,
coverImageZoom: course.coverImageZoom || 1,
coverImagePositionX: course.coverImagePositionX ?? 50,
coverImagePositionY: course.coverImagePositionY ?? 50,
status: course.status || 'published',
assets: (course.attachments || []).filter((attachment) => attachment.url && attachment.url !== '#').map(toAssetPayload),
lessons: course.lessons.map((lesson) => ({
id: /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(lesson.id) ? lesson.id : undefined,
title: lesson.title,
description: lesson.description || '',
durationSeconds: lesson.media?.[0]?.durationSeconds ?? toSeconds(lesson.duration),
accessLevel: lesson.isFree ? 'public' as const : 'enrolled' as const,
media: lesson.media?.length
? lesson.media.map((media) => ({
provider: media.provider,
externalId: media.externalId,
playbackUrl: media.playbackUrl || null,
embedUrl: media.embedUrl || null,
status: media.status,
durationSeconds: media.durationSeconds || null,
}))
: lesson.videoUrl && !lesson.videoUrl.startsWith('blob:')
? [{ provider: lesson.mediaProvider || 'external', externalId: lesson.videoUrl, playbackUrl: lesson.videoUrl, status: 'ready' as const }]
: [],
assets: (lesson.attachments || []).filter((attachment) => attachment.url && attachment.url !== '#').map(toAssetPayload),
})),
});
export const getCourses = async (): Promise<Course[]> => {
const response = await apiRequest<{ data: ApiCourse[] }>('/courses');
return response.data.map(toCourse);
};
export type InstructorProfileData = {
id: string;
name: string;
role: 'student' | 'instructor' | 'admin';
avatarImageUrl: string | null;
headline: string;
bio: string;
websiteUrl: string | null;
linkedinUrl: string | null;
instagramUrl: string | null;
youtubeUrl: string | null;
courses: Course[];
};
export const getInstructorProfile = async (instructorId: string): Promise<InstructorProfileData> => {
const response = await apiRequest<{ data: Omit<InstructorProfileData, 'courses'> & { courses: ApiCourse[] } }>(`/profiles/instructors/${instructorId}`);
return { ...response.data, courses: response.data.courses.map(toCourse) };
};
export const getPublicProfile = async (profileId: string): Promise<InstructorProfileData> => {
const response = await apiRequest<{ data: Omit<InstructorProfileData, 'courses'> & { courses: ApiCourse[] } }>(`/profiles/${profileId}`);
return { ...response.data, courses: response.data.courses.map(toCourse) };
};
export const getLearningPaths = async (): Promise<PublicLearningPath[]> => {
const response = await apiRequest<{ data: PublicLearningPath[] }>('/courses/paths');
return response.data;
};
export const getHomeBanners = async (): Promise<PublicHomeBanner[]> => {
const response = await apiRequest<{ data: PublicHomeBanner[] }>('/courses/home-banners');
return response.data;
};
export const getManagedCourses = async (): Promise<Course[]> => {
const response = await apiRequest<{ data: ApiCourse[] }>('/manage/courses');
return response.data.map(toCourse);
};
export const getMyLearningCourses = async (): Promise<Course[]> => {
const response = await apiRequest<{ data: ApiCourse[] }>('/courses/me/learning');
return response.data.map(toCourse);
};
export const getCourseById = async (id: string): Promise<Course | null> => {
try {
const response = await apiRequest<{ data: ApiCourse }>(`/courses/${id}`);
return toCourse(response.data);
} catch {
return null;
}
};
export const saveCourse = async (course: Course): Promise<void> => {
const payload = toCoursePayload(course);
const isExisting = /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(course.id);
if (isExisting) {
await apiRequest(`/manage/courses/${course.id}`, { method: 'PATCH', body: JSON.stringify(payload) });
} else {
await apiRequest('/manage/courses', { method: 'POST', body: JSON.stringify(payload) });
}
};
export const deleteCourse = async (id: string): Promise<void> => {
await apiRequest(`/manage/courses/${id}`, { method: 'DELETE' });
};
export const duplicateCourse = async (id: string): Promise<void> => {
await apiRequest(`/manage/courses/${id}/duplicate`, { method: 'POST' });
};
type ApiComment = {
id: string;
courseId: string;
lessonId: string | null;
user: string;
text: string;
createdAt: string;
reply?: string | null;
replyCreatedAt?: string | null;
};
const toComment = (comment: ApiComment): Comment => ({
id: comment.id,
courseId: comment.courseId,
lessonId: comment.lessonId || undefined,
user: comment.user,
text: comment.text,
date: new Intl.DateTimeFormat('pt-BR').format(new Date(comment.createdAt)),
reply: comment.reply || undefined,
replyDate: comment.replyCreatedAt
? new Intl.DateTimeFormat('pt-BR').format(new Date(comment.replyCreatedAt))
: undefined,
});
export const getComments = async (courseId: string): Promise<Comment[]> => {
const response = await apiRequest<{ data: ApiComment[] }>(`/courses/${courseId}/comments`);
return response.data.map(toComment);
};
export const saveComment = async (comment: Pick<Comment, 'courseId' | 'lessonId' | 'text'>): Promise<Comment> => {
const response = await apiRequest<{ data: ApiComment }>(`/courses/${comment.courseId}/comments`, {
method: 'POST',
body: JSON.stringify({ lessonId: comment.lessonId || null, text: comment.text }),
});
return toComment(response.data);
};
export const replyToComment = async (commentId: string, text: string): Promise<void> => {
await apiRequest(`/comments/${commentId}/reply`, { method: 'PUT', body: JSON.stringify({ text }) });
};
export const moderateComment = async (commentId: string): Promise<void> => {
await apiRequest(`/comments/${commentId}`, { method: 'DELETE' });
};
export const getCompletedLessonIds = async (courseId: string): Promise<string[]> => {
const progress = await getLessonProgress(courseId);
return progress.filter((item) => item.completedAt).map((item) => item.lessonId);
};
export type LessonProgress = { lessonId: string; watchedSeconds: number; completedAt: string | null };
export const getLessonProgress = async (courseId: string): Promise<LessonProgress[]> => {
const response = await apiRequest<{ data: LessonProgress[] }>(`/courses/${courseId}/progress`);
return response.data;
};
export const saveLessonCompletion = async (lessonId: string, completed: boolean, watchedSeconds?: number): Promise<void> => {
await apiRequest(`/lessons/${lessonId}/progress`, {
method: 'PUT',
body: JSON.stringify({ completed, watchedSeconds }),
});
};
export const saveLessonProgress = async (lessonId: string, watchedSeconds: number): Promise<void> => {
await apiRequest(`/lessons/${lessonId}/progress`, { method: 'PUT', body: JSON.stringify({ watchedSeconds }) });
};
export const incrementViews = async (courseId: string): Promise<void> => {
await courseApi.trackView(courseId).catch(() => undefined);
};
export type SearchResults = {
courses: Course[];
paths: PublicLearningPath[];
professors: InstructorSummary[];
};
export const searchCatalog = async (query: string, area = ''): Promise<SearchResults> => {
const params = new URLSearchParams({ q: query });
if (area) params.set('area', area);
const response = await apiRequest<{ data: { courses: ApiCourse[]; paths: PublicLearningPath[]; professors: InstructorSummary[] } }>(`/search?${params.toString()}`);
return {
...response.data,
courses: response.data.courses.map(toCourse),
};
};
export type DownloadHistoryEntry = {
attachment: Attachment;
courseId: string;
courseTitle: string;
lessonNumber: number | null;
downloadedAt: string;
};
export const getDownloadHistory = async (): Promise<DownloadHistoryEntry[]> => {
const response = await downloadApi.list();
return response.data.map((record: DownloadRecord) => ({
attachment: toAttachment(record),
courseId: record.courseId || '',
courseTitle: record.courseTitle || 'Curso removido',
lessonNumber: record.lessonNumber,
downloadedAt: record.downloadedAt,
}));
};
export const recordDownloadHistory = async (assetId: string): Promise<void> => {
await downloadApi.record(assetId);
};
export const getCommunityComments = async (limit = 100, offset = 0): Promise<Comment[]> => {
const response = await apiRequest<{ data: ApiComment[] }>(`/community/comments?limit=${limit}&offset=${offset}`);
return response.data.map(toComment);
};