feat: add reviews, notifications, notes and account hardening
All checks were successful
CI / Validate frontend and API (push) Successful in 59s
CI / Build and publish Docker images (push) Successful in 23s

This commit is contained in:
Cauê Faleiros
2026-11-05 17:27:36 -03:00
parent 21085e887d
commit fff63f5efa
32 changed files with 1109 additions and 84 deletions

71
App.tsx
View File

@@ -1,21 +1,22 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { ManageCourses } from './pages/ManageCourses';
import { MaterialsPage } from './pages/MaterialsPage';
import { AuthProvider, useAuth } from './context/AuthContext';
import { ToastProvider } from './context/ToastContext';
import { ThemeProvider } from './context/ThemeContext';
import { CatalogProvider } from './context/CatalogContext';
import { AppShell } from './components/shell/AppShell';
import { ErrorBoundary } from './components/ui/ErrorBoundary';
import { Course, UserRole } from './types';
import { SuperAdmin } from './pages/SuperAdmin';
import { AccessTokenPage } from './pages/AccessTokenPage';
import { MyLearning } from './pages/MyLearning';
import { ProfilePage } from './pages/ProfilePage';
import { NotificationsPage } from './pages/NotificationsPage';
import { InstructorProfile } from './pages/InstructorProfile';
import { TrailDetail } from './pages/TrailDetail';
import { TrailPage } from './pages/TrailPage';
import { AuthPage, homeFor } from './pages/AuthPage';
import { ForgotPasswordPage } from './pages/ForgotPasswordPage';
import { NotFoundPage } from './pages/NotFoundPage';
import { paths } from './lib/routes';
import { ExplorePage } from './pages/ExplorePage';
import { SearchPage } from './pages/SearchPage';
@@ -27,6 +28,10 @@ import { YouPage } from './pages/YouPage';
import { ContinueCourse, CoursePage } from './pages/CoursePage';
import { LessonPage } from './pages/LessonPage';
const ManageCourses = React.lazy(() => import('./pages/ManageCourses').then((module) => ({ default: module.ManageCourses })));
const SuperAdmin = React.lazy(() => import('./pages/SuperAdmin').then((module) => ({ default: module.SuperAdmin })));
const TrailDetail = React.lazy(() => import('./pages/TrailDetail').then((module) => ({ default: module.TrailDetail })));
/** Keeps old /#/... links (invites, password resets, bookmarks) working after moving off HashRouter. */
const LegacyHashRedirect: React.FC = () => {
const location = useLocation();
@@ -55,32 +60,36 @@ function AppContent() {
return (
<AppShell>
<Routes>
<Route path="/" element={<ExplorePage />} />
<Route path="/buscar" element={<SearchPage />} />
<Route path="/trilhas" element={<TrailsPage />} />
<Route path="/comunidade" element={<CommunityPage />} />
<Route path="/professores" element={<ProfessorsPage />} />
<Route path="/cursos/:courseId" element={<CoursePage />} />
<Route path="/cursos/:courseId/continuar" element={<ContinueCourse />} />
<Route path="/cursos/:courseId/aulas/:lessonId" element={<LessonPage />} />
<Route path="/entrar" element={<AuthPage mode="signin" />} />
<Route path="/criar-conta" element={<AuthPage mode="signup" />} />
<Route path="/materiais" element={<MaterialsPage onPlayCourse={setSelectedCourse} />} />
<Route path="/downloads" element={<ProtectedRoute><DownloadsPage /></ProtectedRoute>} />
<Route path="/voce" element={<YouPage />} />
<Route path="/gerenciar" element={<ProtectedRoute allowedRoles={['professor', 'superadmin']}><ManageCourses /></ProtectedRoute>} />
<Route path="/admin" element={<ProtectedRoute allowedRoles={['superadmin']}><SuperAdmin /></ProtectedRoute>} />
<Route path="/admin/trilhas/:trailId" element={<ProtectedRoute allowedRoles={['superadmin']}><div className="legacy-skin"><TrailDetail /></div></ProtectedRoute>} />
<Route path="/trilhas/:trailId" element={<TrailPage onPlay={setSelectedCourse} />} />
<Route path="/meu-aprendizado" element={<ProtectedRoute><MyLearning onPlay={setSelectedCourse} /></ProtectedRoute>} />
<Route path="/perfil" element={<ProtectedRoute><ProfilePage /></ProtectedRoute>} />
<Route path="/instrutores/:instructorId" element={<InstructorProfile onPlay={setSelectedCourse} />} />
<Route path="/perfis/:profileId" element={<InstructorProfile onPlay={setSelectedCourse} />} />
<Route path="/invite" element={<AccessTokenPage mode="invite" />} />
<Route path="/reset-password" element={<AccessTokenPage mode="reset" />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
<React.Suspense fallback={<main className="wrap page"><div className="loading">Carregando…</div></main>}>
<Routes>
<Route path="/" element={<ExplorePage />} />
<Route path="/buscar" element={<SearchPage />} />
<Route path="/trilhas" element={<TrailsPage />} />
<Route path="/comunidade" element={<CommunityPage />} />
<Route path="/professores" element={<ProfessorsPage />} />
<Route path="/cursos/:courseId" element={<CoursePage />} />
<Route path="/cursos/:courseId/continuar" element={<ContinueCourse />} />
<Route path="/cursos/:courseId/aulas/:lessonId" element={<LessonPage />} />
<Route path="/entrar" element={<AuthPage mode="signin" />} />
<Route path="/criar-conta" element={<AuthPage mode="signup" />} />
<Route path="/esqueci-senha" element={<ForgotPasswordPage />} />
<Route path="/materiais" element={<MaterialsPage onPlayCourse={setSelectedCourse} />} />
<Route path="/downloads" element={<ProtectedRoute><DownloadsPage /></ProtectedRoute>} />
<Route path="/voce" element={<YouPage />} />
<Route path="/gerenciar" element={<ProtectedRoute allowedRoles={['professor', 'superadmin']}><ManageCourses /></ProtectedRoute>} />
<Route path="/admin" element={<ProtectedRoute allowedRoles={['superadmin']}><SuperAdmin /></ProtectedRoute>} />
<Route path="/admin/trilhas/:trailId" element={<ProtectedRoute allowedRoles={['superadmin']}><div className="legacy-skin"><TrailDetail /></div></ProtectedRoute>} />
<Route path="/trilhas/:trailId" element={<TrailPage onPlay={setSelectedCourse} />} />
<Route path="/meu-aprendizado" element={<ProtectedRoute><MyLearning onPlay={setSelectedCourse} /></ProtectedRoute>} />
<Route path="/perfil" element={<ProtectedRoute><ProfilePage /></ProtectedRoute>} />
<Route path="/notificacoes" element={<ProtectedRoute><NotificationsPage /></ProtectedRoute>} />
<Route path="/instrutores/:instructorId" element={<InstructorProfile onPlay={setSelectedCourse} />} />
<Route path="/perfis/:profileId" element={<InstructorProfile onPlay={setSelectedCourse} />} />
<Route path="/invite" element={<AccessTokenPage mode="invite" />} />
<Route path="/reset-password" element={<AccessTokenPage mode="reset" />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</React.Suspense>
</AppShell>
);
}
@@ -93,7 +102,9 @@ function App() {
<AuthProvider>
<ToastProvider>
<CatalogProvider>
<AppContent />
<ErrorBoundary>
<AppContent />
</ErrorBoundary>
</CatalogProvider>
</ToastProvider>
</AuthProvider>

View File

@@ -0,0 +1,137 @@
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { StarIcon } from '@phosphor-icons/react';
import { useAuth } from '../../context/AuthContext';
import { useToast } from '../../context/ToastContext';
import { CourseReviewSummary, MyCourseReview, deleteMyCourseReview, getCourseReviews, getMyCourseReview, saveCourseReview } from '../../services/db';
import { ConfirmDialog } from '../ui/ConfirmDialog';
import { shortDate } from '../../lib/format';
import { paths } from '../../lib/routes';
const Stars: React.FC<{ value: number; label?: string }> = ({ value, label }) => (
<span className="review-stars" role="img" aria-label={label || `${value} de 5 estrelas`}>
{[1, 2, 3, 4, 5].map((star) => <StarIcon key={star} weight={star <= Math.round(value) ? 'fill' : 'regular'} />)}
</span>
);
export const CourseReviews: React.FC<{ courseId: string }> = ({ courseId }) => {
const { user } = useAuth();
const { showToast } = useToast();
const [summary, setSummary] = useState<CourseReviewSummary | null>(null);
const [mine, setMine] = useState<MyCourseReview | null>(null);
const [rating, setRating] = useState(0);
const [comment, setComment] = useState('');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const load = async () => {
setLoading(true);
try {
const [publicReviews, myReview] = await Promise.all([
getCourseReviews(courseId),
user ? getMyCourseReview(courseId).catch(() => null) : Promise.resolve(null),
]);
setSummary(publicReviews);
setMine(myReview);
setRating(myReview?.rating ?? 0);
setComment(myReview?.comment ?? '');
} catch {
setSummary(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, [courseId, user?.id]);
const submit = async (event: React.FormEvent) => {
event.preventDefault();
if (!rating) {
showToast('Escolha uma nota de 1 a 5 estrelas.', 'error');
return;
}
setSaving(true);
try {
const result = await saveCourseReview(courseId, rating, comment.trim());
setMine(result.review);
setSummary(result.summary);
setRating(result.review.rating);
setComment(result.review.comment);
showToast('Avaliação salva.', 'success');
} catch {
showToast('Não foi possível salvar sua avaliação.', 'error');
} finally {
setSaving(false);
}
};
const remove = async () => {
setDeleteOpen(false);
try {
await deleteMyCourseReview(courseId);
setMine(null);
setRating(0);
setComment('');
setSummary(await getCourseReviews(courseId));
showToast('Avaliação removida.', 'success');
} catch {
showToast('Não foi possível remover sua avaliação.', 'error');
}
};
const average = summary?.average ?? 0;
const count = summary?.count ?? 0;
return <section className="reviews">
<header className="reviews-header">
<h2>Avaliações</h2>
{count > 0 && <span className="count num">{count} {count === 1 ? 'avaliação' : 'avaliações'}</span>}
</header>
{loading ? <p className="muted">Carregando avaliações…</p> : <>
<div className="reviews-layout">
<div className="box review-summary">
<b className="review-average num">{count ? average.toFixed(1) : '—'}</b>
<Stars value={average} label={count ? `Média ${average.toFixed(1)} de 5` : 'Sem avaliações'} />
<small>{count ? `${count} ${count === 1 ? 'pessoa avaliou' : 'pessoas avaliaram'}` : 'Seja a primeira pessoa a avaliar'}</small>
</div>
{user ? <form className="box review-form" onSubmit={submit}>
<div>
<span className="review-form-label">{mine ? 'Sua avaliação' : 'Avalie este curso'}</span>
<div className="review-rating" role="group" aria-label="Escolha sua nota">
{[1, 2, 3, 4, 5].map((star) => <button key={star} type="button" aria-label={`${star} ${star === 1 ? 'estrela' : 'estrelas'}`} aria-pressed={rating === star} onClick={() => setRating(star)}><StarIcon weight={star <= rating ? 'fill' : 'regular'} /></button>)}
</div>
</div>
<div className="field">
<label htmlFor={`review-comment-${courseId}`}>Comentário <span className="faint">(opcional)</span></label>
<textarea id={`review-comment-${courseId}`} value={comment} onChange={(event) => setComment(event.target.value)} maxLength={2000} placeholder="Conte o que você achou do curso…" />
</div>
<div className="review-actions">
<button className="btn" type="submit" disabled={saving}>{saving ? 'Salvando…' : mine ? 'Atualizar avaliação' : 'Publicar avaliação'}</button>
{mine && <button className="link bad-text" type="button" onClick={() => setDeleteOpen(true)}>Remover minha avaliação</button>}
</div>
</form> : <div className="box review-signin">
<b>Gostou do curso?</b>
<p className="small">Entre na sua conta para avaliar e ajudar outras pessoas.</p>
<Link className="btn sec" to={paths.signIn}>Entrar para avaliar</Link>
</div>}
</div>
{summary?.reviews.length ? <div className="review-list">
{summary.reviews.map((review) => <article className="review-item" key={`${review.userName}-${review.updatedAt}`}>
<header>
<div><b>{review.userName}</b><Stars value={review.rating} /></div>
<small>{shortDate(review.updatedAt)}</small>
</header>
{review.comment && <p>{review.comment}</p>}
</article>)}
</div> : <p className="empty">Nenhuma avaliação publicada ainda.</p>}
</>}
<ConfirmDialog open={deleteOpen} title="Remover avaliação" message="Sua avaliação será removida permanentemente." confirmLabel="Remover avaliação" onCancel={() => setDeleteOpen(false)} onConfirm={() => void remove()} />
</section>;
};

View File

@@ -6,7 +6,7 @@ import {
MoonMockIcon, PathMockIcon, SearchMockIcon, SignOutMockIcon, SunMockIcon, TeacherMockIcon,
TrayMockIcon, UserMockIcon, VideoMockIcon,
} from '../ui/MockupIcons';
import { SidebarSimpleIcon } from '@phosphor-icons/react';
import { BellIcon, SidebarSimpleIcon } from '@phosphor-icons/react';
import { Logo } from '../Logo';
import { Avatar } from '../ui/Avatar';
import { useAuth } from '../../context/AuthContext';
@@ -15,6 +15,7 @@ import { useCatalog } from '../../context/CatalogContext';
import { NavKey, navKeyFor } from '../../lib/navigation';
import { paths } from '../../lib/routes';
import { readPreference, writePreference } from '../../lib/storage';
import { getNotifications } from '../../services/notifications';
const GROUPS_KEY = 'ca-groups';
const COLLAPSED_KEY = 'ca-side';
@@ -47,6 +48,7 @@ export const Sidebar: React.FC = () => {
const [shut, setShut] = useState<Record<string, boolean>>(readGroups);
const [collapsed, setCollapsed] = useState(() => readPreference(COLLAPSED_KEY) === '1');
const [menuOpen, setMenuOpen] = useState(false);
const [unreadNotifications, setUnreadNotifications] = useState(0);
const whoRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const [menuStyle, setMenuStyle] = useState<React.CSSProperties>({});
@@ -60,6 +62,20 @@ export const Sidebar: React.FC = () => {
useEffect(() => setMenuOpen(false), [location.pathname]);
useEffect(() => {
if (!user) { setUnreadNotifications(0); return; }
let cancelled = false;
const refresh = () => {
getNotifications().then((feed) => { if (!cancelled) setUnreadNotifications(feed.unread); }).catch(() => undefined);
};
refresh();
window.addEventListener('compor:notifications-updated', refresh);
return () => {
cancelled = true;
window.removeEventListener('compor:notifications-updated', refresh);
};
}, [user?.id, location.pathname]);
// The account menu lives on <body> with position: fixed, so the sidebar never clips it.
useLayoutEffect(() => {
if (!menuOpen || !whoRef.current) return;
@@ -131,6 +147,10 @@ export const Sidebar: React.FC = () => {
<button type="button" className="iconbtn" onClick={toggleCollapsed} aria-label={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'} title={collapsed ? 'Expandir barra lateral' : 'Recolher barra lateral'}>
<SidebarSimpleIcon className="ph" />
</button>
{user && <Link className="iconbtn notif" to={paths.notifications} aria-label={`Notificações${unreadNotifications ? `, ${unreadNotifications} não lidas` : ''}`} title="Notificações">
<BellIcon className="ph" />
{unreadNotifications > 0 && <span className="notif-badge">{unreadNotifications > 9 ? '9+' : unreadNotifications}</span>}
</Link>}
</div>
<Link to={paths.explore} className="logo" aria-label="Compor Academy, início">
<Logo width={96} />

View File

@@ -0,0 +1,31 @@
import React, { ReactNode } from 'react';
interface ErrorBoundaryState {
hasError: boolean;
}
export class ErrorBoundary extends React.Component<{ children: ReactNode }, ErrorBoundaryState> {
declare props: Readonly<{ children: ReactNode }>;
state: ErrorBoundaryState = { hasError: false };
static getDerivedStateFromError(): ErrorBoundaryState {
return { hasError: true };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('Unhandled application error', error, info);
}
render() {
if (this.state.hasError) {
return <main className="wrap page">
<div className="empty">
<h1>Algo deu errado</h1>
<p>Não foi possível exibir esta página. Recarregue para tentar novamente.</p>
<button className="btn" type="button" onClick={() => window.location.reload()} style={{ marginTop: 20 }}>Recarregar página</button>
</div>
</main>;
}
return this.props.children;
}
}

View File

@@ -16,9 +16,22 @@ interface SelectProps {
/** Custom listbox used instead of the browser's native select. */
export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLabel, disabled = false, variant = 'default' }) => {
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [position, setPosition] = useState<{ top: number; left: number; width: number } | null>(null);
const selected = options.find((option) => option.value === value);
const selectedIndex = Math.max(0, options.findIndex((option) => option.value === value));
const [highlight, setHighlight] = useState(selectedIndex);
const move = (delta: number) => {
if (!options.length) return;
setHighlight((current) => (current + delta + options.length) % options.length);
};
const closeMenu = (restoreFocus = false) => {
setOpen(false);
if (restoreFocus) triggerRef.current?.focus();
};
const place = () => {
const trigger = triggerRef.current;
@@ -35,14 +48,17 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
const toggle = () => {
if (disabled) return;
if (!open) place();
if (!open) {
place();
setHighlight(selectedIndex);
}
setOpen((current) => !current);
};
useEffect(() => {
if (!open) return;
const close = () => setOpen(false);
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false); };
const close = () => closeMenu();
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') closeMenu(true); };
window.addEventListener('resize', close);
window.addEventListener('scroll', close, true);
document.addEventListener('keydown', onKey);
@@ -53,6 +69,11 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
};
}, [open]);
useEffect(() => {
if (!open || !position) return;
menuRef.current?.querySelectorAll<HTMLButtonElement>('button[role="option"]')[highlight]?.focus();
}, [highlight, open, position]);
return <>
<button
ref={triggerRef}
@@ -63,14 +84,44 @@ export const Select: React.FC<SelectProps> = ({ value, options, onChange, ariaLa
aria-expanded={open}
aria-label={ariaLabel}
onClick={toggle}
onKeyDown={(event) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
if (!open) {
place();
setHighlight(selectedIndex);
setOpen(true);
} else {
move(event.key === 'ArrowDown' ? 1 : -1);
}
}
if (event.key === 'Escape' && open) {
event.preventDefault();
closeMenu();
}
}}
>
<span className="select-value">{selected?.label ?? ''}</span>
<ChevronDownMockIcon className="ph" />
</button>
{open && position && createPortal(<>
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => setOpen(false)} />
<div className="select-menu" role="listbox" aria-label={ariaLabel} style={{ top: position.top, left: position.left, width: position.width }}>
{options.map((option) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} onClick={() => { onChange(option.value); setOpen(false); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
<button type="button" className="menu-scrim" aria-label="Fechar lista" onClick={() => closeMenu(true)} />
<div
ref={menuRef}
className="select-menu"
role="listbox"
aria-label={ariaLabel}
style={{ top: position.top, left: position.left, width: position.width }}
onKeyDown={(event) => {
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
else if (event.key === 'Home') { event.preventDefault(); setHighlight(0); }
else if (event.key === 'End') { event.preventDefault(); setHighlight(options.length - 1); }
else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
else if (event.key === 'Tab') { closeMenu(); }
}}
>
{options.map((option, index) => <button key={option.value} type="button" role="option" aria-selected={option.value === value} tabIndex={-1} onFocus={() => setHighlight(index)} onClick={() => { onChange(option.value); closeMenu(true); }}><span>{option.label}</span>{option.value === value && <CheckMockIcon className="ph" />}</button>)}
</div>
</>, document.body)}
</>;

View File

@@ -13,6 +13,7 @@ export const paths = {
library: '/materiais',
downloads: '/downloads',
account: '/perfil',
notifications: '/notificacoes',
you: '/voce',
manage: '/gerenciar',
editCourse: (courseId: string) => `/gerenciar/${courseId}`,
@@ -21,4 +22,5 @@ export const paths = {
adminTrail: (trailId: string) => `/admin/trilhas/${trailId}`,
signIn: '/entrar',
signUp: '/criar-conta',
forgotPassword: '/esqueci-senha',
};

View File

@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { authApi, saveSession } from '../services/api';
import { paths } from '../lib/routes';
export const AccessTokenPage: React.FC<{ mode: 'invite' | 'reset' }> = ({ mode }) => {
const location = useLocation();
@@ -19,7 +20,7 @@ export const AccessTokenPage: React.FC<{ mode: 'invite' | 'reset' }> = ({ mode }
if (mode === 'invite') {
const session = await authApi.acceptInvitation(token, name, password);
saveSession(session); navigate(session.user.role === 'admin' ? '/admin' : session.user.role === 'instructor' ? '/gerenciar' : '/');
} else { await authApi.resetPassword(token, password); navigate('/'); }
} else { await authApi.resetPassword(token, password); navigate(paths.signIn, { replace: true }); }
} catch { setError('Este link é inválido, expirou ou não pôde ser usado.'); }
finally { setSaving(false); }
};

View File

@@ -76,6 +76,7 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
? <>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>
);

View File

@@ -5,8 +5,9 @@ import { Attachment, Course } from '../types';
import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useCatalog } from '../context/CatalogContext';
import { ArtImage, Cover, courseFraming, useCoverImage } from '../components/catalog/Artwork';
import { ArtImage, CourseCard, Cover, courseFraming, useCoverImage } from '../components/catalog/Artwork';
import { MaterialRow, 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';
@@ -40,12 +41,12 @@ export const CoursePage: React.FC = () => {
const { courseId } = useParams<{ courseId: string }>();
const { course, isLoading, missing } = useCourse(courseId);
const { user } = useAuth();
const { paths: trails } = useCatalog();
const { paths: trails, courses: catalogCourses } = useCatalog();
const progress = useLessonProgress(course);
const action = useMaterialAction();
const saved = useSavedCourses();
const isMobile = useIsMobile();
const [mobileTab, setMobileTab] = useState<'aulas' | 'materiais' | 'sobre'>('aulas');
const [mobileTab, setMobileTab] = useState<'aulas' | 'materiais' | 'sobre' | 'avaliacoes'>('aulas');
if (isLoading) return <main className="wrap page"><div className="loading"><CircleNotchIcon className="ph spin" /></div></main>;
if (missing || !course) return <main className="wrap page"><p className="empty">Este curso não está disponível.</p></main>;
@@ -55,18 +56,24 @@ export const CoursePage: React.FC = () => {
const next = progress.next;
const watchTo = (lessonId?: string) => (user && lessonId ? paths.lesson(course.id, lessonId) : paths.signUp);
const started = progress.doneCount > 0;
const related = catalogCourses
.filter((item) => item.id !== course.id && (item.category === course.category || (course.instructorId && item.instructorId === course.instructorId)))
.sort((a, b) => Number(b.category === course.category) - Number(a.category === course.category))
.slice(0, 4);
if (isMobile) return <main className="m-page has-cta enter">
<div className="m-gut">
<Cover course={course} progress={user ? Math.round(progress.doneCount / Math.max(course.lessons.length, 1) * 100) : undefined} className="m-cover" />
<header className="m-title"><h1>{course.title}</h1><p className="num">{[course.instructor, courseMeta(course)].filter(Boolean).join(' · ')}</p></header>
{user && progress.doneCount > 0 && <div className="m-progress"><span className="prog"><i style={{ width: `${Math.round(progress.doneCount / Math.max(course.lessons.length, 1) * 100)}%` }} /></span><span>{progress.doneCount} de {course.lessons.length} aulas</span></div>}
<div className="m-seg" role="tablist">{([['aulas', 'Aulas'], ['materiais', 'Materiais'], ['sobre', 'Sobre']] as const).map(([key, label]) => <button type="button" role="tab" key={key} aria-selected={mobileTab === key} onClick={() => setMobileTab(key)}>{label}</button>)}</div>
<div className="m-seg" role="tablist">{([['aulas', 'Aulas'], ['materiais', 'Materiais'], ['sobre', 'Sobre'], ['avaliacoes', 'Avaliações']] as const).map(([key, label]) => <button type="button" role="tab" key={key} aria-selected={mobileTab === key} onClick={() => setMobileTab(key)}>{label}</button>)}</div>
<div className="m-pane">
{mobileTab === 'aulas' && <section className="m-group"><div className="m-list">{course.lessons.map((lesson, index) => <Link className="m-row" key={lesson.id} to={watchTo(lesson.id)} state={user ? undefined : signUpState}><span className="m-n num">{progress.completed.has(lesson.id) ? <CheckIcon className="ph" /> : index + 1}</span><span className="m-rt"><b>{lesson.title}</b><small>{lessonDuration(lesson)}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>}
{mobileTab === 'materiais' && <section className="m-group"><div className="m-list">{materials.map((item) => <div className="m-row" key={item.attachment.id}><span className="m-ic">{attachmentIcon(item.attachment.type)}</span><span className="m-rt"><b>{item.attachment.name}</b><small>{item.detail} · {item.attachment.size}</small></span><MaterialButton attachment={item.attachment} action={action} label={false} className="m-icb" /></div>)}</div>{!materials.length && <p className="m-empty">Este curso não tem materiais para baixar.</p>}</section>}
{mobileTab === 'sobre' && <><p className="m-body">{course.description}</p>{course.instructorId && <section className="m-group"><h2>Professor</h2><div className="m-list"><Link className="m-row" to={paths.professor(course.instructorId)}><Avatar name={course.instructor || 'Professor'} size="sm" /><span className="m-rt"><b>{course.instructor}</b></span><CaretRightIcon className="m-chev" /></Link></div></section>}{trail && <section className="m-group"><h2>Trilha</h2><div className="m-list"><Link className="m-row" to={paths.trail(trail.id)}><span className="m-rt"><b>{trail.title}</b></span><CaretRightIcon className="m-chev" /></Link></div></section>}</>}
{mobileTab === 'avaliacoes' && <CourseReviews courseId={course.id} />}
</div>
{related.length > 0 && <section className="m-group"><h2>Cursos relacionados</h2><div className="m-list">{related.map((item) => <Link className="m-row" key={item.id} to={paths.course(item.id)}><span className="m-rt"><b>{item.title}</b><small>{item.instructor}</small></span><CaretRightIcon className="m-chev" /></Link>)}</div></section>}
</div>
<div className="m-cta">{user && <button type="button" className="btn sec m-half save-icon" onClick={() => saved.toggle(course.id)} aria-label={saved.isSaved(course.id) ? 'Remover dos salvos' : 'Salvar curso'} aria-pressed={saved.isSaved(course.id)}><BookmarkSimpleIcon className="ph" weight={saved.isSaved(course.id) ? 'fill' : 'regular'} /></button>}<Link className="btn m-big" to={user && next ? paths.lesson(course.id, next.id) : paths.signUp} state={user ? undefined : signUpState}>{user && started ? `Continuar aula ${progress.nextIndex + 1}` : user ? 'Assistir' : 'Criar conta para assistir'}</Link></div>
</main>;
@@ -115,6 +122,7 @@ export const CoursePage: React.FC = () => {
</ol>
)}
</section>
<CourseReviews courseId={course.id} />
</div>
<aside className="side">
{course.instructorId && (
@@ -142,6 +150,10 @@ export const CoursePage: React.FC = () => {
)}
</aside>
</div>
{related.length > 0 && <section className="shelf" style={{ marginTop: 36 }}>
<header><h2>Cursos relacionados</h2></header>
<div className="grid">{related.map((item) => <CourseCard key={item.id} course={item} />)}</div>
</section>}
</main>
);
};

View File

@@ -0,0 +1,40 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { authApi } from '../services/api';
import { paths } from '../lib/routes';
export const ForgotPasswordPage: React.FC = () => {
const [email, setEmail] = useState('');
const [sent, setSent] = useState(false);
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const submit = async (event: React.FormEvent) => {
event.preventDefault();
setError('');
if (!/^\S+@\S+\.\S+$/.test(email)) { setError('Informe um e-mail válido.'); return; }
setSending(true);
try {
await authApi.forgotPassword(email);
setSent(true);
} catch {
setError('Não foi possível solicitar a recuperação agora. Tente novamente.');
} finally {
setSending(false);
}
};
return <main className="wrap page enter"><div className="auth">
<h1>Recuperar senha</h1>
<p>Informe seu e-mail para receber um link de redefinição.</p>
{sent ? <>
<p className="formmsg ok" role="status">Se existir uma conta com esse e-mail, enviaremos o link de redefinição.</p>
<p className="alt"><Link className="link" to={paths.signIn}>Voltar para entrar</Link></p>
</> : <form noValidate onSubmit={submit}>
<div className="field"><label htmlFor="forgot-email">E-mail</label><input id="forgot-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={sending}>{sending ? 'Enviando…' : 'Enviar link'}</button>
<p className="alt"><Link className="link" to={paths.signIn}>Voltar para entrar</Link></p>
</form>}
</div></main>;
};

View File

@@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom';
import { CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
import { Comment, Course, Lesson } from '../types';
import { getComments, incrementViews, saveComment, saveLessonProgress } from '../services/db';
import { getComments, getLessonNote, incrementViews, saveComment, saveLessonNote, saveLessonProgress } from '../services/db';
import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
@@ -26,9 +26,34 @@ export const useLessonScreen = (course: Course | undefined, lesson: Lesson | und
const [comments, setComments] = useState<Comment[]>([]);
const [draft, setDraft] = useState('');
const [posting, setPosting] = useState(false);
const [note, setNote] = useState('');
const [noteSaving, setNoteSaving] = useState(false);
const advanceTimer = useRef<number>();
const trackedView = useRef<string>('');
useEffect(() => {
if (!user || !lesson) { setNote(''); return; }
let cancelled = false;
getLessonNote(lesson.id)
.then((data) => { if (!cancelled) setNote(data.body); })
.catch(() => { if (!cancelled) setNote(''); });
return () => { cancelled = true; };
}, [lesson?.id, user?.id]);
const saveNote = async () => {
if (!lesson) return;
setNoteSaving(true);
try {
const saved = await saveLessonNote(lesson.id, note);
setNote(saved.body);
showToast('Anotação salva.', 'success');
} catch {
showToast('Não foi possível salvar a anotação.', 'error');
} finally {
setNoteSaving(false);
}
};
useEffect(() => {
if (!user || !course || !lesson) return;
const key = `${course.id}:${lesson.id}`;
@@ -86,7 +111,7 @@ export const useLessonScreen = (course: Course | undefined, lesson: Lesson | und
const materials = lesson?.attachments || [];
const courseLevel = course?.attachments || [];
return { progress, comments, draft, setDraft, posting, postComment, onTime, onEnded, index, nextLesson, materials, courseLevel };
return { progress, comments, draft, setDraft, posting, postComment, onTime, onEnded, index, nextLesson, materials, courseLevel, note, setNote, noteSaving, saveNote };
};
export const CommentItem: React.FC<{ comment: Comment; lessonNumber?: number }> = ({ comment, lessonNumber }) => (
@@ -134,6 +159,7 @@ export const LessonPage: React.FC = () => {
{tab === 'materiais' && <section className="m-group"><div className="m-list">{[...screen.materials, ...screen.courseLevel].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>{attachment.size}</small></span><MaterialButton attachment={attachment} action={action} label={false} className="m-icb" /></div>)}</div>{screen.materials.length + screen.courseLevel.length === 0 && <p className="m-empty">Esta aula não tem materiais.</p>}</section>}
{tab === 'discussao' && <><form className="m-compose" onSubmit={screen.postComment}><textarea rows={1} value={screen.draft} onChange={(event) => screen.setDraft(event.target.value)} placeholder="Escreva uma pergunta" aria-label="Escrever comentário" /><button className="btn m-sm" type="submit" disabled={!screen.draft.trim() || screen.posting}>Enviar</button></form><div className="m-thread">{comments.map((comment) => <CommentItem key={comment.id} comment={comment} />)}{!comments.length && <p className="m-empty">Nenhuma pergunta ainda.</p>}</div></>}
</div>
<section className="m-group"><h2>Anotações</h2><div className="m-list"><label className="m-field col"><span>Suas anotações desta aula</span><textarea rows={4} value={screen.note} onChange={(event) => screen.setNote(event.target.value)} placeholder="Escreva aqui…" /></label></div><button className="link" type="button" style={{ marginTop: 10 }} onClick={() => void screen.saveNote()} disabled={screen.noteSaving}>{screen.noteSaving ? 'Salvando…' : 'Salvar anotação'}</button></section>
</div>
<div className="m-cta"><button type="button" className="btn sec m-half" onClick={() => progress.toggleCompleted(lesson.id)} aria-pressed={done}><CheckIcon className="ph" />{done ? 'Vista' : 'Marcar vista'}</button>{nextLesson ? <Link className="btn m-half" to={paths.lesson(course.id, nextLesson.id)}>Próxima aula</Link> : <Link className="btn m-half" to={paths.course(course.id)}>Concluir</Link>}</div>
</main>;
@@ -208,6 +234,7 @@ export const LessonPage: React.FC = () => {
<p className="small num" style={{ fontSize: 13 }}>{progress.doneCount} de {course.lessons.length} aulas concluídas</p>
</Link>
{lesson.description && <div className="box"><h3>Sobre esta aula</h3><p className="small" style={{ whiteSpace: 'pre-line' }}>{lesson.description}</p></div>}
<div className="box"><h3>Anotações</h3><div className="field"><textarea rows={4} value={screen.note} onChange={(event) => screen.setNote(event.target.value)} placeholder="Suas anotações desta aula…" aria-label="Anotações da aula" /></div><button className="btn sec" type="button" onClick={() => void screen.saveNote()} disabled={screen.noteSaving}>{screen.noteSaving ? 'Salvando…' : 'Salvar anotação'}</button></div>
</aside>
</div>
</main>

View File

@@ -358,6 +358,7 @@ export const ManageCourses: React.FC = () => {
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);
@@ -441,6 +442,11 @@ export const ManageCourses: React.FC = () => {
};
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()} />
@@ -454,7 +460,7 @@ export const ManageCourses: React.FC = () => {
<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>
: <section className="m-group"><div className="m-list multi">{allComments.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 && !allComments.length && <p className="m-empty">Nenhuma discussão 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>;
@@ -470,9 +476,10 @@ export const ManageCourses: React.FC = () => {
<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>) : allComments.length ? <div className="list">{allComments.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">Nenhuma discussão ainda.</p>}
</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>;
};

View File

@@ -2,22 +2,46 @@ import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { Course } from '../types';
import { getMyLearningCourses } from '../services/db';
import { LearningStats, getLearningStats, getMyLearningCourses } from '../services/db';
import { CourseCard, Cover, Thumb } from '../components/catalog/Artwork';
import { PlayMockIcon } from '../components/ui/MockupIcons';
import { Select } from '../components/ui/Select';
import { useSavedCourses } from '../hooks/useSavedCourses';
import { useCatalog } from '../context/CatalogContext';
import { useIsMobile } from '../hooks/useMediaQuery';
import { readPreference, writePreference } from '../lib/storage';
import { paths } from '../lib/routes';
export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = () => {
const [courses, setCourses] = useState<Course[]>([]);
const [stats, setStats] = useState<LearningStats | null>(null);
const [loading, setLoading] = useState(true);
const [tab, setTab] = useState<'andamento' | 'concluidos' | 'salvos'>('andamento');
const [weeklyGoal, setWeeklyGoal] = useState(() => {
const stored = Number(readPreference('ca-weekly-goal'));
return [3, 5, 7, 10].includes(stored) ? stored : 3;
});
const saved = useSavedCourses();
const isMobile = useIsMobile();
const { courses: catalogCourses } = useCatalog();
useEffect(() => { getMyLearningCourses().then(setCourses).catch(() => setCourses([])).finally(() => setLoading(false)); }, []);
useEffect(() => {
getMyLearningCourses().then(setCourses).catch(() => setCourses([])).finally(() => setLoading(false));
getLearningStats().then(setStats).catch(() => setStats(null));
}, []);
const updateGoal = (value: string) => {
const next = Number(value);
if (![3, 5, 7, 10].includes(next)) return;
setWeeklyGoal(next);
writePreference('ca-weekly-goal', String(next));
};
const formatWatchTime = (seconds: number) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return hours ? `${hours}h ${minutes}min` : `${minutes}min`;
};
const weeklyCompleted = stats?.weeklyCompleted ?? 0;
const goalPct = Math.min(100, Math.round((weeklyCompleted / weeklyGoal) * 100));
const goalOptions = [3, 5, 7, 10].map((value) => ({ value: String(value), label: `${value} aulas` }));
const going = courses.filter((course) => (course.progress || 0) < 100);
const done = courses.filter((course) => (course.progress || 0) >= 100);
const savedCourses = catalogCourses.filter((course) => saved.isSaved(course.id));
@@ -30,6 +54,13 @@ export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = () =>
if (isMobile) {
const chosen = tab === 'andamento' ? going : tab === 'concluidos' ? done : savedCourses;
return <main className="m-page m-gut enter"><header className="m-large"><h1>Minha aprendizagem</h1></header>
<div className="m-stats num">
<div><b>{stats?.streakDays ?? 0}</b><small>dias seguidos</small></div>
<div><b>{Math.floor((stats?.watchedSeconds ?? 0) / 60)}</b><small>min assistidos</small></div>
<div><b>{stats?.completedLessons ?? 0}</b><small>aulas concluídas</small></div>
<div><b>{weeklyCompleted}/{weeklyGoal}</b><small>meta semanal</small></div>
</div>
<section className="m-group"><h2>Meta da semana</h2><div className="m-list"><div className="m-row"><span className="m-rt"><b className="num">{weeklyCompleted} de {weeklyGoal} aulas</b><small>{goalPct}% concluído</small></span><Select variant="mobile" value={String(weeklyGoal)} options={goalOptions} onChange={updateGoal} ariaLabel="Meta semanal de aulas" /></div></div><span className="m-bar" style={{ display: 'block', marginTop: 10 }}><i style={{ width: `${goalPct}%` }} /></span></section>
<div className="m-seg" role="tablist">{[['andamento', 'Em andamento'], ['concluidos', 'Concluídos'], ['salvos', 'Salvos']].map(([key, label]) => <button type="button" role="tab" key={key} aria-selected={tab === key} onClick={() => setTab(key as typeof tab)}>{label}</button>)}</div>
{chosen.length ? <section className="m-group"><div className="m-list">{chosen.map((course) => {
const progress = course.progress || 0;
@@ -44,6 +75,12 @@ export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = () =>
return <main className="wrap page enter">
<div className="ptitle"><div><h1>Minha aprendizagem</h1></div></div>
{stats && <div className="stats">
<div><small>Sequência de estudos</small><b className="num">{stats.streakDays} {stats.streakDays === 1 ? 'dia' : 'dias'}</b></div>
<div><small>Tempo assistido</small><b className="num">{formatWatchTime(stats.watchedSeconds)}</b></div>
<div><small>Aulas concluídas</small><b className="num">{stats.completedLessons}</b></div>
<div><small>Cursos com atividade</small><b className="num">{stats.activeCourses}</b></div>
</div>}
{first && <Link className="box contbox" to={paths.continueCourse(first.id)}>
<Cover course={first} variant="mini" />
<div>
@@ -53,6 +90,11 @@ export const MyLearning: React.FC<{ onPlay: (course: Course) => void }> = () =>
</div>
<span className="btn"><PlayMockIcon className="ph" /> Continuar</span>
</Link>}
<div className="box week-goal">
<div><h3>Meta da semana</h3><p className="small num">{weeklyCompleted} de {weeklyGoal} aulas concluídas</p></div>
<Select value={String(weeklyGoal)} options={goalOptions} onChange={updateGoal} ariaLabel="Meta semanal de aulas" />
<span className="prog"><i style={{ width: `${goalPct}%` }} /></span>
</div>
<section className="shelf"><header><h2>Em andamento</h2></header><div className="grid">{going.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>
<section className="shelf"><header><h2>Concluídos</h2></header><div className="grid">{done.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>
<section className="shelf"><header><h2>Salvos</h2></header><div className="grid">{savedCourses.map((course) => <CourseCard key={course.id} course={course} />)}</div></section>

13
pages/NotFoundPage.tsx Normal file
View File

@@ -0,0 +1,13 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { paths } from '../lib/routes';
export const NotFoundPage: React.FC = () => (
<main className="wrap page enter">
<div className="empty">
<h1>Página não encontrada</h1>
<p>O endereço acessado não existe ou foi movido.</p>
<Link className="btn" to={paths.explore} style={{ marginTop: 20 }}>Voltar para Explorar</Link>
</div>
</main>
);

View File

@@ -0,0 +1,72 @@
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 { 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));
export const NotificationsPage: React.FC = () => {
const { showToast } = useToast();
const isMobile = useIsMobile();
const [feed, setFeed] = useState<NotificationFeed | null>(null);
const [loading, setLoading] = useState(true);
const load = async () => {
setLoading(true);
try {
setFeed(await getNotifications());
} catch {
setFeed({ items: [], unread: 0 });
showToast('Não foi possível carregar suas notificações.', 'error');
} finally {
setLoading(false);
}
};
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);
window.dispatchEvent(new Event('compor:notifications-updated'));
} catch {
showToast('Não foi possível marcar as notificações como lidas.', 'error');
}
};
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);
};
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>}
</div>
{list}
</main>;
};

View File

@@ -68,6 +68,7 @@ export const SuperAdmin: React.FC = () => {
const [audit, setAudit] = useState<AuditEntry[]>([]);
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
const [auditQuery, setAuditQuery] = useState('');
const [busyUserId, setBusyUserId] = useState<string | null>(null);
const [openMenu, setOpenMenu] = useState<{ account: ManagedUser; top: number; right: number } | null>(null);
const [inviteOpen, setInviteOpen] = useState(false);
@@ -105,6 +106,32 @@ export const SuperAdmin: React.FC = () => {
const normalized = query.trim().toLowerCase();
return normalized ? users.filter((account) => account.name.toLowerCase().includes(normalized) || account.email.toLowerCase().includes(normalized)) : users;
}, [query, users]);
const visibleAudit = useMemo(() => {
const normalized = auditQuery.trim().toLowerCase();
if (!normalized) return audit;
return audit.filter((entry) => [entry.actorName, describeAction(entry), dateTime(entry.createdAt)].some((value) => value.toLowerCase().includes(normalized)));
}, [audit, auditQuery]);
const exportUsersCsv = () => {
const rows = [
['Nome', 'E-mail', 'Papel', 'Status', 'Cadastro', 'Último acesso'],
...filteredUsers.map((account) => [
account.name,
account.email,
roleLabel[account.role],
account.isActive ? 'Ativo' : 'Desativado',
dateTime(account.createdAt),
account.lastAccessAt ? dateTime(account.lastAccessAt) : '',
]),
];
const csv = rows.map((row) => row.map((value) => `"${String(value).replace(/"/g, '""')}"`).join(',')).join('\r\n');
const url = URL.createObjectURL(new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8' }));
const link = document.createElement('a');
link.href = url;
link.download = `usuarios-compor-hub-${new Date().toISOString().slice(0, 10)}.csv`;
link.click();
URL.revokeObjectURL(url);
};
const publishedCourses = useMemo(() => home?.courses.filter((course) => course.status === 'published') || [], [home]);
const homeCourses = useMemo(() => {
@@ -249,7 +276,7 @@ export const SuperAdmin: React.FC = () => {
{contentTab === 'trilhas' && <TrailManager onChanged={() => void loadData()} />}
{contentTab === 'categorias' && <CategoryManager onChanged={() => void loadData()} />}
</>}
{tab === 'auditoria' && <section className="m-group"><div className="m-list multi">{audit.map((entry) => <div className="m-row" key={entry.id}><span className="m-rt"><b>{describeAction(entry)}</b><small>{entry.actorName} · {dateTime(entry.createdAt)}</small></span></div>)}</div>{!audit.length && <p className="m-empty">Nenhuma atividade recente.</p>}</section>}
{tab === 'auditoria' && <><label className="m-search"><SearchMockIcon className="ph" /><input type="search" value={auditQuery} onChange={(event) => setAuditQuery(event.target.value)} placeholder="Filtrar atividade" aria-label="Filtrar registro de atividades" /></label><section className="m-group"><div className="m-list multi">{visibleAudit.map((entry) => <div className="m-row" key={entry.id}><span className="m-rt"><b>{describeAction(entry)}</b><small>{entry.actorName} · {dateTime(entry.createdAt)}</small></span></div>)}</div>{!visibleAudit.length && <p className="m-empty">{audit.length ? 'Nenhuma atividade com esse filtro.' : 'Nenhuma atividade recente.'}</p>}</section></>}
{inviteOpen && <div className="scrim" role="dialog" aria-modal="true" aria-label="Convidar instrutor" onMouseDown={(event) => { if (event.target === event.currentTarget) setInviteOpen(false); }}>
<div className="dialog" style={{ maxWidth: 440 }}>
@@ -299,6 +326,7 @@ 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" />
<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>
@@ -335,10 +363,15 @@ export const SuperAdmin: React.FC = () => {
{contentTab === 'categorias' && <CategoryManager onChanged={() => void loadData()} />}
</>}
{tab === 'auditoria' && <div className="tablewrap"><table><thead><tr><th>Quando</th><th>Quem</th><th>Ação</th></tr></thead><tbody>
{audit.map((entry) => <tr key={entry.id}><td className="num" style={{ color: 'var(--fg-2)', whiteSpace: 'nowrap' }}>{dateTime(entry.createdAt)}</td><td>{entry.actorName}</td><td>{describeAction(entry)}</td></tr>)}
{!audit.length && <tr><td colSpan={3}><p className="empty">Nenhuma atividade recente.</p></td></tr>}
</tbody></table></div>}
{tab === 'auditoria' && <>
<div className="toolbar">
<label className="search"><SearchMockIcon className="ph" /><input type="search" value={auditQuery} onChange={(event) => setAuditQuery(event.target.value)} placeholder="Filtrar por pessoa, ação ou data" aria-label="Filtrar registro de atividades" /></label>
</div>
<div className="tablewrap"><table><thead><tr><th>Quando</th><th>Quem</th><th>Ação</th></tr></thead><tbody>
{visibleAudit.map((entry) => <tr key={entry.id}><td className="num" style={{ color: 'var(--fg-2)', whiteSpace: 'nowrap' }}>{dateTime(entry.createdAt)}</td><td>{entry.actorName}</td><td>{describeAction(entry)}</td></tr>)}
{!visibleAudit.length && <tr><td colSpan={3}><p className="empty">{audit.length ? 'Nenhuma atividade com esse filtro.' : 'Nenhuma atividade recente.'}</p></td></tr>}
</tbody></table></div>
</>}
{inviteOpen && <div className="scrim" role="dialog" aria-modal="true" aria-label="Convidar instrutor" onMouseDown={(event) => { if (event.target === event.currentTarget) setInviteOpen(false); }}>
<div className="dialog" style={{ maxWidth: 440 }}>

View File

@@ -1,6 +1,6 @@
import React from 'react';
import { Link, Navigate, useNavigate } from 'react-router-dom';
import { BooksIcon, CaretRightIcon, DownloadSimpleIcon, FolderIcon, GearIcon, MoonIcon, SignOutIcon, UserIcon, VideoCameraIcon } from '@phosphor-icons/react';
import { BellIcon, BooksIcon, CaretRightIcon, DownloadSimpleIcon, FolderIcon, GearIcon, MoonIcon, SignOutIcon, UserIcon, VideoCameraIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { useTheme } from '../context/ThemeContext';
import { Avatar } from '../components/ui/Avatar';
@@ -21,7 +21,7 @@ export const YouPage: React.FC = () => {
{user ? <><Link className="m-me" to={paths.account}><Avatar name={user.name} src={user.avatar} /><span><b>{user.name}</b><small>{user.email}</small></span><CaretRightIcon className="m-chev" /></Link>
<Group title="Aprendizado" entries={[{ label: 'Minha aprendizagem', to: paths.learning, icon: BooksIcon }, { label: 'Meus downloads', to: paths.downloads, icon: DownloadSimpleIcon }, { label: 'Biblioteca', to: paths.library, icon: FolderIcon }]} />
{canTeach && <Group title="Gestão" entries={[{ label: 'Gerenciar cursos', to: paths.manage, icon: VideoCameraIcon }, ...(user.role === 'superadmin' ? [{ label: 'Administração', to: paths.admin, icon: GearIcon }] : [])]} />}
<Group title="Conta" entries={[{ label: 'Dados pessoais', to: paths.account, icon: UserIcon }]} />
<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>}

View File

@@ -0,0 +1,29 @@
-- Session version so password changes can invalidate existing JWTs.
alter table users
add column if not exists token_version integer not null default 0;
-- One view per learner per course per day, used to keep the view counter honest.
create table if not exists course_views (
course_id uuid not null references courses(id) on delete cascade,
user_id uuid not null references users(id) on delete cascade,
viewed_on date not null default current_date,
created_at timestamptz not null default now(),
primary key (course_id, user_id, viewed_on)
);
create index if not exists course_views_course_index on course_views (course_id, viewed_on);
-- Private lesson notes.
create table if not exists lesson_notes (
user_id uuid not null references users(id) on delete cascade,
lesson_id uuid not null references lessons(id) on delete cascade,
body text not null default '',
updated_at timestamptz not null default now(),
primary key (user_id, lesson_id)
);
create index if not exists lesson_notes_user_index on lesson_notes (user_id, updated_at desc);
-- Useful indexes for the community feed and user moderation screens.
create index if not exists comments_created_index on comments (created_at desc);
create index if not exists comments_author_index on comments (author_id);

View File

@@ -0,0 +1,12 @@
-- One review per learner per course.
create table if not exists course_reviews (
user_id uuid not null references users(id) on delete cascade,
course_id uuid not null references courses(id) on delete cascade,
rating smallint not null check (rating between 1 and 5),
comment text not null default '',
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
primary key (user_id, course_id)
);
create index if not exists course_reviews_course_index on course_reviews (course_id, updated_at desc);

View File

@@ -0,0 +1,14 @@
-- In-app notifications for questions and replies.
create table if not exists notifications (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references users(id) on delete cascade,
kind text not null,
title text not null,
body text not null default '',
href text not null,
read_at timestamptz,
created_at timestamptz not null default now()
);
create index if not exists notifications_user_index on notifications (user_id, created_at desc);
create index if not exists notifications_unread_index on notifications (user_id) where read_at is null;

View File

@@ -15,6 +15,7 @@ import { profileRoutes } from './routes/profiles.js';
import { savedCourseRoutes } from './routes/saved-courses.js';
import { downloadRoutes } from './routes/downloads.js';
import { searchRoutes } from './routes/search.js';
import { notificationRoutes } from './routes/notifications.js';
export function buildApp() {
const app = Fastify({ logger: true, trustProxy: true });
@@ -25,6 +26,7 @@ export function buildApp() {
app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (request, body, done) => {
const rawBody = Buffer.isBuffer(body) ? body : Buffer.from(body);
(request as typeof request & { rawBody?: Buffer }).rawBody = rawBody;
if (rawBody.length === 0) return done(null, undefined);
try {
done(null, JSON.parse(rawBody.toString('utf8')));
} catch {
@@ -86,6 +88,7 @@ export function buildApp() {
app.register(savedCourseRoutes, { prefix: '/api/v1/saved-courses' });
app.register(downloadRoutes, { prefix: '/api/v1/downloads' });
app.register(searchRoutes, { prefix: '/api/v1/search' });
app.register(notificationRoutes, { prefix: '/api/v1/notifications' });
app.register(manageCourseRoutes, { prefix: '/api/v1/manage/courses' });
app.register(mediaRoutes, { prefix: '/api/v1/manage/media' });
app.register(bunnyWebhookRoutes, { prefix: '/api/v1/webhooks' });

View File

@@ -11,6 +11,7 @@ export interface AuthUser {
email: string;
role: UserRole;
name: string;
tokenVersion: number;
}
declare module '@fastify/jwt' {
@@ -38,8 +39,8 @@ const registerAuth: FastifyPluginAsync = async (app) => {
return false;
}
const result = await pool.query<{ role: UserRole; display_name: string }>(
'select role, display_name from users where id = $1 and is_active = true',
const result = await pool.query<{ role: UserRole; display_name: string; token_version: number }>(
'select role, display_name, token_version from users where id = $1 and is_active = true',
[request.user.id],
);
const account = result.rows[0];
@@ -48,8 +49,14 @@ const registerAuth: FastifyPluginAsync = async (app) => {
return false;
}
if ((request.user.tokenVersion ?? 0) !== account.token_version) {
reply.code(401).send({ error: 'Sua sessão expirou. Entre novamente.' });
return false;
}
request.user.role = account.role;
request.user.name = account.display_name;
request.user.tokenVersion = account.token_version;
return true;
};

View File

@@ -5,6 +5,7 @@ import { pool } from '../db/pool.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import { config } from '../config.js';
import { recordAudit } from '../audit.js';
import { sendInvitationEmail, sendPasswordResetEmail } from '../services/email.js';
const userParamsSchema = z.object({
userId: z.string().uuid(),
@@ -373,7 +374,14 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
[input.email, input.role, hashToken(rawToken), config.INVITATION_TTL_HOURS, request.user.id],
);
await recordAudit({ actorId: request.user.id, action: 'invitation.created', subjectType: 'invitation', metadata: { email: input.email, role: input.role }, ipAddress: request.ip });
return reply.code(201).send({ data: { inviteUrl: `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}` } });
const inviteUrl = `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}`;
try {
const sent = await sendInvitationEmail({ email: input.email, inviteUrl });
if (!sent && config.SMTP_HOST) request.log.warn({ email: input.email }, 'Invitation email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Invitation email could not be sent');
}
return reply.code(201).send({ data: { inviteUrl } });
});
app.post('/users/:userId/password-reset', adminAccess, async (request, reply) => {
@@ -387,7 +395,14 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
[account.rows[0].email, account.rows[0].role, hashToken(rawToken), config.PASSWORD_RESET_TTL_HOURS, request.user.id],
);
await recordAudit({ actorId: request.user.id, action: 'password_reset.created', subjectType: 'user', subjectId: userId, metadata: { email: account.rows[0].email }, ipAddress: request.ip });
return { data: { resetUrl: `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}` } };
const resetUrl = `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}`;
try {
const sent = await sendPasswordResetEmail({ email: account.rows[0].email, resetUrl });
if (!sent && config.SMTP_HOST) request.log.warn({ email: account.rows[0].email }, 'Password reset email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Password reset email could not be sent');
}
return { data: { resetUrl } };
});
app.patch('/users/:userId', adminAccess, async (request, reply) => {

View File

@@ -1,11 +1,11 @@
import type { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { hashPassword, verifyPassword } from '../auth/passwords.js';
import { hashToken } from '../auth/account-tokens.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import type { AuthUser } from '../auth/plugin.js';
import { pool } from '../db/pool.js';
import { config } from '../config.js';
import { sendWelcomeEmail } from '../services/email.js';
import { sendPasswordResetEmail, sendWelcomeEmail } from '../services/email.js';
const credentialsSchema = z.object({
email: z.string().email().transform((email) => email.toLowerCase()),
@@ -16,6 +16,9 @@ const registerSchema = credentialsSchema.extend({
name: z.string().trim().min(2).max(120),
});
const tokenPasswordSchema = z.object({ token: z.string().min(20), password: z.string().min(8).max(200), name: z.string().trim().min(2).max(120).optional() });
const forgotPasswordSchema = z.object({
email: z.string().email().transform((email) => email.toLowerCase()),
});
type UserRow = {
id: string;
@@ -24,6 +27,7 @@ type UserRow = {
role: AuthUser['role'];
password_hash: string;
is_active: boolean;
token_version: number;
};
const serializeUser = (user: UserRow): AuthUser => ({
@@ -31,6 +35,7 @@ const serializeUser = (user: UserRow): AuthUser => ({
email: user.email,
name: user.display_name,
role: user.role,
tokenVersion: user.token_version,
});
export const authRoutes: FastifyPluginAsync = async (app) => {
@@ -78,7 +83,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
}
const result = await client.query<UserRow>(
`insert into users (email, password_hash, display_name, role) values ($1, $2, $3, $4)
returning id, email, display_name, role, password_hash, is_active`,
returning id, email, display_name, role, password_hash, is_active, token_version`,
[token.rows[0].email, await hashPassword(input.password), input.name, token.rows[0].role],
);
await client.query('commit');
@@ -107,7 +112,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
await client.query('rollback');
return reply.code(400).send({ error: 'Este link de redefinição é inválido ou expirou.' });
}
await client.query('update users set password_hash = $2 where email = $1', [token.rows[0].email, await hashPassword(input.password)]);
await client.query('update users set password_hash = $2, token_version = token_version + 1 where email = $1', [token.rows[0].email, await hashPassword(input.password)]);
await client.query('commit');
return reply.code(204).send();
} catch (error) {
@@ -117,6 +122,34 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
client.release();
}
});
app.post('/forgot-password', async (request, reply) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = forgotPasswordSchema.parse(request.body);
const account = await pool.query<{ id: string; role: AuthUser['role'] }>(
'select id, role from users where email = $1 and is_active = true',
[input.email],
);
// Always answer 204 so the endpoint cannot be used to enumerate accounts.
if (account.rows[0]) {
const rawToken = createRawToken();
await pool.query(
`insert into account_access_tokens (email, role, purpose, token_hash, expires_at, created_by)
values ($1, $2::user_role, 'password_reset', $3, now() + ($4::int * interval '1 hour'), $5)`,
[input.email, account.rows[0].role, hashToken(rawToken), config.PASSWORD_RESET_TTL_HOURS, account.rows[0].id],
);
const resetUrl = `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}`;
try {
const sent = await sendPasswordResetEmail({ email: input.email, resetUrl });
if (!sent && config.SMTP_HOST) request.log.warn({ email: input.email }, 'Password reset email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Password reset email could not be sent');
}
}
return reply.code(204).send();
});
app.post('/register', async (request, reply) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = registerSchema.parse(request.body);
@@ -126,7 +159,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
const result = await pool.query<UserRow>(
`insert into users (email, password_hash, display_name)
values ($1, $2, $3)
returning id, email, display_name, role, password_hash, is_active`,
returning id, email, display_name, role, password_hash, is_active, token_version`,
[input.email, passwordHash, input.name],
);
const user = serializeUser(result.rows[0]);
@@ -150,7 +183,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = credentialsSchema.parse(request.body);
const result = await pool.query<UserRow>(
`select id, email, display_name, role, password_hash, is_active from users where email = $1`,
`select id, email, display_name, role, password_hash, is_active, token_version from users where email = $1`,
[input.email],
);
const account = result.rows[0];

View File

@@ -15,6 +15,10 @@ const coverParamsSchema = z.object({
filename: z.string().regex(/^[0-9a-f]{8}-[0-9a-f-]{27}\.(?:jpg|png|webp)$/i),
});
const assetParamsSchema = z.object({ assetId: z.string().uuid() });
const reviewSchema = z.object({
rating: z.number().int().min(1).max(5),
comment: z.string().trim().max(2000).default(''),
});
export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) => `
select
@@ -117,6 +121,31 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
}
};
const publishedCourseExists = async (courseId: string) => {
const result = await pool.query("select 1 from courses where id = $1 and status = 'published'", [courseId]);
return result.rowCount === 1;
};
const reviewSummary = async (courseId: string) => {
const [summary, reviews] = await Promise.all([
pool.query<{ average: number; count: number }>(
`select coalesce(avg(rating)::float8, 0) as average, count(*)::int as count
from course_reviews where course_id = $1`,
[courseId],
),
pool.query<{ rating: number; comment: string; updatedAt: string; userName: string }>(
`select r.rating, r.comment, r.updated_at as "updatedAt", u.display_name as "userName"
from course_reviews r
join users u on u.id = r.user_id
where r.course_id = $1
order by r.updated_at desc
limit 30`,
[courseId],
),
]);
return { ...summary.rows[0], reviews: reviews.rows };
};
app.get('/categories', async () => {
const result = await pool.query<{ name: string }>(`select name from course_categories where is_active order by position, name`);
return { data: result.rows.map((row) => row.name) };
@@ -272,17 +301,66 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
return { data: result.rows };
});
app.get('/me/learning/stats', { preHandler: app.authenticate }, async (request) => {
const [summary, days] = await Promise.all([
pool.query<{ watchedSeconds: number; completedLessons: number; activeCourses: number; weeklyCompleted: number }>(
`select coalesce(sum(lp.watched_seconds), 0)::int as "watchedSeconds",
count(*) filter (where lp.completed_at is not null)::int as "completedLessons",
count(distinct l.course_id)::int as "activeCourses",
count(*) filter (where lp.completed_at >= date_trunc('week', now()))::int as "weeklyCompleted"
from lesson_progress lp
join lessons l on l.id = lp.lesson_id
join courses c on c.id = l.course_id and c.status = 'published'
where lp.user_id = $1`,
[request.user.id],
),
pool.query<{ day: string }>(
`select distinct to_char(lp.updated_at at time zone 'America/Sao_Paulo', 'YYYY-MM-DD') as day
from lesson_progress lp
join lessons l on l.id = lp.lesson_id
join courses c on c.id = l.course_id and c.status = 'published'
where lp.user_id = $1
order by day desc
limit 90`,
[request.user.id],
),
]);
const dayKeys = new Set(days.rows.map((row) => row.day));
const keyFor = (date: Date) => new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Sao_Paulo' }).format(date);
let cursor = new Date();
if (!dayKeys.has(keyFor(cursor))) cursor = new Date(cursor.getTime() - 86_400_000);
let streakDays = 0;
while (dayKeys.has(keyFor(cursor))) {
streakDays += 1;
cursor = new Date(cursor.getTime() - 86_400_000);
}
return { data: { ...summary.rows[0], streakDays } };
});
app.post('/:courseId/view', { preHandler: app.authenticate }, async (request, reply) => {
const { courseId } = paramsSchema.parse(request.params);
const result = await pool.query<{ views: number }>(
`update courses
set view_count = view_count + 1
where id = $1 and status = 'published'
returning view_count as views`,
[courseId],
const course = await pool.query("select id from courses where id = $1 and status = 'published'", [courseId]);
if (!course.rowCount) return reply.code(404).send({ error: 'Curso não encontrado.' });
const inserted = await pool.query(
`insert into course_views (course_id, user_id) values ($1, $2)
on conflict (course_id, user_id, viewed_on) do nothing
returning course_id`,
[courseId, request.user.id],
);
if (!result.rows[0]) return reply.code(404).send({ error: 'Curso não encontrado.' });
return { data: result.rows[0] };
if (inserted.rowCount) {
const updated = await pool.query<{ views: number }>(
`update courses set view_count = view_count + 1 where id = $1 returning view_count as views`,
[courseId],
);
return { data: updated.rows[0] };
}
const current = await pool.query<{ views: number }>('select view_count as views from courses where id = $1', [courseId]);
return { data: current.rows[0] };
});
app.get('/:courseId', async (request, reply) => {
@@ -298,6 +376,43 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
return { data: authenticated ? course : withoutProtectedMedia(course) };
});
app.get('/:courseId/reviews', async (request, reply) => {
const { courseId } = paramsSchema.parse(request.params);
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
return { data: await reviewSummary(courseId) };
});
app.get('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
const { courseId } = paramsSchema.parse(request.params);
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
const result = await pool.query<{ rating: number; comment: string; updatedAt: string }>(
`select rating, comment, updated_at as "updatedAt" from course_reviews
where course_id = $1 and user_id = $2`,
[courseId, request.user.id],
);
return { data: result.rows[0] || null };
});
app.put('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
const { courseId } = paramsSchema.parse(request.params);
const input = reviewSchema.parse(request.body);
if (!(await publishedCourseExists(courseId))) return reply.code(404).send({ error: 'Curso não encontrado.' });
const result = await pool.query<{ rating: number; comment: string; updatedAt: string }>(
`insert into course_reviews (user_id, course_id, rating, comment)
values ($1, $2, $3, $4)
on conflict (user_id, course_id) do update set rating = excluded.rating, comment = excluded.comment, updated_at = now()
returning rating, comment, updated_at as "updatedAt"`,
[request.user.id, courseId, input.rating, input.comment],
);
return { data: { review: result.rows[0], summary: await reviewSummary(courseId) } };
});
app.delete('/:courseId/reviews/mine', { preHandler: app.authenticate }, async (request, reply) => {
const { courseId } = paramsSchema.parse(request.params);
await pool.query('delete from course_reviews where course_id = $1 and user_id = $2', [courseId, request.user.id]);
return reply.code(204).send();
});
app.get('/:courseId/lessons/:lessonId/playback', { preHandler: app.authenticate }, async (request, reply) => {
const { courseId, lessonId } = playbackParamsSchema.parse(request.params);
const result = await pool.query<{

View File

@@ -22,6 +22,7 @@ const commentSchema = z.object({
});
const commentParamsSchema = z.object({ commentId: z.string().uuid() });
const replySchema = z.object({ text: z.string().trim().min(1).max(4000) });
const noteSchema = z.object({ body: z.string().max(20_000) });
const communityQuerySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(50),
offset: z.coerce.number().int().min(0).default(0),
@@ -42,6 +43,54 @@ const canViewCourseComments = async (courseId: string, user: { id: string; role:
};
export const learningRoutes: FastifyPluginAsync = async (app) => {
const createNotification = async (input: { userId: string; kind: string; title: string; body: string; href: string }) => {
await pool.query(
'insert into notifications (user_id, kind, title, body, href) values ($1, $2, $3, $4, $5)',
[input.userId, input.kind, input.title, input.body, input.href],
);
};
const lessonAccessible = async (lessonId: string, user: { id: string; role: string }) => {
const result = await pool.query(
`select l.id
from lessons l
join courses c on c.id = l.course_id
where l.id = $1 and (c.status = 'published' or c.instructor_id = $2 or $3 = 'admin')`,
[lessonId, user.id, user.role],
);
return result.rowCount === 1;
};
app.get('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
const { lessonId } = lessonParamsSchema.parse(request.params);
if (!(await lessonAccessible(lessonId, request.user))) return reply.code(404).send({ error: 'Aula não encontrada.' });
const result = await pool.query<{ body: string; updatedAt: string | null }>(
'select body, updated_at as "updatedAt" from lesson_notes where user_id = $1 and lesson_id = $2',
[request.user.id, lessonId],
);
return { data: result.rows[0] || { body: '', updatedAt: null } };
});
app.put('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
const { lessonId } = lessonParamsSchema.parse(request.params);
const input = noteSchema.parse(request.body);
if (!(await lessonAccessible(lessonId, request.user))) return reply.code(404).send({ error: 'Aula não encontrada.' });
const result = await pool.query<{ body: string; updatedAt: string }>(
`insert into lesson_notes (user_id, lesson_id, body)
values ($1, $2, $3)
on conflict (user_id, lesson_id) do update set body = excluded.body, updated_at = now()
returning body, updated_at as "updatedAt"`,
[request.user.id, lessonId, input.body],
);
return { data: result.rows[0] };
});
app.delete('/lessons/:lessonId/note', { preHandler: app.authenticate }, async (request, reply) => {
const { lessonId } = lessonParamsSchema.parse(request.params);
await pool.query('delete from lesson_notes where user_id = $1 and lesson_id = $2', [request.user.id, lessonId]);
return reply.code(204).send();
});
// Public, paginated feed used by the community screen. Individual course
// threads remain authenticated because they are part of the lesson area.
app.get('/community/comments', async (request) => {
@@ -165,6 +214,26 @@ export const learningRoutes: FastifyPluginAsync = async (app) => {
join users u on u.id = $3`,
[courseId, input.lessonId || null, request.user.id, input.text],
);
const course = await pool.query<{ instructorId: string; title: string }>(
'select instructor_id as "instructorId", title from courses where id = $1',
[courseId],
);
const owner = course.rows[0];
if (owner && owner.instructorId !== request.user.id) {
try {
await createNotification({
userId: owner.instructorId,
kind: 'question',
title: `Nova pergunta em ${owner.title}`,
body: `${request.user.name}: ${input.text.slice(0, 180)}`,
href: input.lessonId ? `/cursos/${courseId}/aulas/${input.lessonId}` : '/comunidade',
});
} catch (error) {
request.log.error(error, 'Could not create question notification');
}
}
return reply.code(201).send({ data: result.rows[0] });
});
@@ -178,6 +247,28 @@ export const learningRoutes: FastifyPluginAsync = async (app) => {
on conflict (comment_id) do update set author_id = excluded.author_id, body = excluded.body`,
[commentId, request.user.id, input.text],
);
const target = await pool.query<{ authorId: string; courseId: string; lessonId: string | null; courseTitle: string }>(
`select c.author_id as "authorId", c.course_id as "courseId", c.lesson_id as "lessonId", co.title as "courseTitle"
from comments c
join courses co on co.id = c.course_id
where c.id = $1`,
[commentId],
);
const comment = target.rows[0];
if (comment && comment.authorId !== request.user.id) {
try {
await createNotification({
userId: comment.authorId,
kind: 'reply',
title: 'Seu comentário recebeu uma resposta',
body: `${request.user.name}: ${input.text.slice(0, 180)}`,
href: comment.lessonId ? `/cursos/${comment.courseId}/aulas/${comment.lessonId}` : '/comunidade',
});
} catch (error) {
request.log.error(error, 'Could not create reply notification');
}
}
await recordAudit({ actorId: request.user.id, action: 'comment.replied', subjectType: 'comment', subjectId: commentId, ipAddress: request.ip });
return { data: { id: commentId } };
});

View File

@@ -0,0 +1,36 @@
import type { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { pool } from '../db/pool.js';
const notificationParamsSchema = z.object({ notificationId: z.string().uuid() });
export const notificationRoutes: FastifyPluginAsync = async (app) => {
app.get('/', { preHandler: app.authenticate }, async (request) => {
const [items, unread] = await Promise.all([
pool.query<{ id: string; kind: string; title: string; body: string; href: string; readAt: string | null; createdAt: string }>(
`select id, kind, title, body, href, read_at as "readAt", created_at as "createdAt"
from notifications
where user_id = $1
order by created_at desc
limit 50`,
[request.user.id],
),
pool.query<{ count: number }>(
'select count(*)::int as count from notifications where user_id = $1 and read_at is null',
[request.user.id],
),
]);
return { data: { items: items.rows, unread: unread.rows[0].count } };
});
app.post('/read-all', { preHandler: app.authenticate }, async (request, reply) => {
await pool.query('update notifications set read_at = now() where user_id = $1 and read_at is null', [request.user.id]);
return reply.code(204).send();
});
app.post('/:notificationId/read', { preHandler: app.authenticate }, async (request, reply) => {
const { notificationId } = notificationParamsSchema.parse(request.params);
await pool.query('update notifications set read_at = coalesce(read_at, now()) where id = $1 and user_id = $2', [notificationId, request.user.id]);
return reply.code(204).send();
});
};

View File

@@ -1,23 +1,43 @@
import { config } from '../config.js';
import nodemailer from 'nodemailer';
type WelcomeRecipient = { name: string; email: string };
const isConfigured = () => Boolean(config.SMTP_HOST && config.SMTP_PORT && config.SMTP_USER && config.SMTP_PASS && config.MAIL_FROM);
export async function sendWelcomeEmail(recipient: WelcomeRecipient) {
if (!config.SMTP_HOST || !config.SMTP_PORT || !config.SMTP_USER || !config.SMTP_PASS || !config.MAIL_FROM) return false;
const escapedName = recipient.name.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[character] || character));
const sendEmail = async (to: string, subject: string, html: string) => {
if (!isConfigured()) return false;
const transporter = nodemailer.createTransport({
host: config.SMTP_HOST,
port: config.SMTP_PORT,
secure: config.SMTP_PORT === 465,
auth: { user: config.SMTP_USER, pass: config.SMTP_PASS },
});
await transporter.sendMail({
from: config.MAIL_FROM,
to: recipient.email,
subject: 'Bem-vindo(a) ao Compor HUB',
html: `<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Bem-vindo(a), ${escapedName}!</h1><p>Sua conta no <strong>Compor HUB</strong> já está pronta.</p><p>Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.</p><p><a href="${config.FRONTEND_ORIGIN}" style="display:inline-block;background:#f97316;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Acessar Compor HUB</a></p></main>`,
});
await transporter.sendMail({ from: config.MAIL_FROM, to, subject, html });
return true;
};
const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[character] || character));
export async function sendWelcomeEmail(recipient: { name: string; email: string }) {
const escapedName = escapeHtml(recipient.name);
return sendEmail(
recipient.email,
'Bem-vindo(a) ao Compor HUB',
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Bem-vindo(a), ${escapedName}!</h1><p>Sua conta no <strong>Compor HUB</strong> já está pronta.</p><p>Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.</p><p><a href="${config.FRONTEND_ORIGIN}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Acessar Compor HUB</a></p></main>`,
);
}
export async function sendInvitationEmail(recipient: { email: string; inviteUrl: string }) {
return sendEmail(
recipient.email,
'Você foi convidado para o Compor HUB',
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Convite para o Compor HUB</h1><p>Você recebeu acesso como professor à plataforma.</p><p>Defina seu nome e sua senha para começar.</p><p><a href="${recipient.inviteUrl}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Aceitar convite</a></p><p style="color:#6e6e73;font-size:13px">Este link expira em ${config.INVITATION_TTL_HOURS} horas.</p></main>`,
);
}
export async function sendPasswordResetEmail(recipient: { email: string; resetUrl: string }) {
return sendEmail(
recipient.email,
'Redefinição de senha do Compor HUB',
`<main style="font-family:Arial,sans-serif;color:#18181b;line-height:1.55"><h1>Redefinir senha</h1><p>Recebemos um pedido para redefinir a senha da sua conta.</p><p><a href="${recipient.resetUrl}" style="display:inline-block;background:#0a84ff;color:#fff;padding:12px 18px;border-radius:8px;text-decoration:none;font-weight:700">Escolher nova senha</a></p><p style="color:#6e6e73;font-size:13px">Se você não pediu isso, ignore este e-mail. O link expira em ${config.PASSWORD_RESET_TTL_HOURS} horas.</p></main>`,
);
}

View File

@@ -220,6 +220,9 @@ export const authApi = {
async resetPassword(token: string, password: string) {
return apiRequest<void>('/auth/reset-password', { method: 'POST', body: JSON.stringify({ token, password }) });
},
async forgotPassword(email: string) {
return apiRequest<void>('/auth/forgot-password', { method: 'POST', body: JSON.stringify({ email }) });
},
};
export const adminApi = {

View File

@@ -420,3 +420,72 @@ export const getCommunityComments = async (limit = 100, offset = 0): Promise<Com
const response = await apiRequest<{ data: ApiComment[] }>(`/community/comments?limit=${limit}&offset=${offset}`);
return response.data.map(toComment);
};
export type LearningStats = {
watchedSeconds: number;
completedLessons: number;
activeCourses: number;
weeklyCompleted: number;
streakDays: number;
};
export const getLearningStats = async (): Promise<LearningStats> => {
const response = await apiRequest<{ data: LearningStats }>('/courses/me/learning/stats');
return response.data;
};
export type CourseReview = {
rating: number;
comment: string;
updatedAt: string;
userName: string;
};
export type MyCourseReview = {
rating: number;
comment: string;
updatedAt: string;
};
export type CourseReviewSummary = {
average: number;
count: number;
reviews: CourseReview[];
};
export const getCourseReviews = async (courseId: string): Promise<CourseReviewSummary> => {
const response = await apiRequest<{ data: CourseReviewSummary }>(`/courses/${courseId}/reviews`);
return response.data;
};
export const getMyCourseReview = async (courseId: string): Promise<MyCourseReview | null> => {
const response = await apiRequest<{ data: MyCourseReview | null }>(`/courses/${courseId}/reviews/mine`);
return response.data;
};
export const saveCourseReview = async (courseId: string, rating: number, comment: string): Promise<{ review: MyCourseReview; summary: CourseReviewSummary }> => {
const response = await apiRequest<{ data: { review: MyCourseReview; summary: CourseReviewSummary } }>(`/courses/${courseId}/reviews/mine`, {
method: 'PUT',
body: JSON.stringify({ rating, comment }),
});
return response.data;
};
export const deleteMyCourseReview = async (courseId: string): Promise<void> => {
await apiRequest<void>(`/courses/${courseId}/reviews/mine`, { method: 'DELETE' });
};
export type LessonNote = { body: string; updatedAt: string | null };
export const getLessonNote = async (lessonId: string): Promise<LessonNote> => {
const response = await apiRequest<{ data: LessonNote }>(`/lessons/${lessonId}/note`);
return response.data;
};
export const saveLessonNote = async (lessonId: string, body: string): Promise<LessonNote> => {
const response = await apiRequest<{ data: LessonNote }>(`/lessons/${lessonId}/note`, {
method: 'PUT',
body: JSON.stringify({ body }),
});
return response.data;
};

29
services/notifications.ts Normal file
View File

@@ -0,0 +1,29 @@
import { apiRequest } from './api';
export type NotificationItem = {
id: string;
kind: string;
title: string;
body: string;
href: string;
readAt: string | null;
createdAt: string;
};
export type NotificationFeed = {
items: NotificationItem[];
unread: number;
};
export const getNotifications = async (): Promise<NotificationFeed> => {
const response = await apiRequest<{ data: NotificationFeed }>('/notifications');
return response.data;
};
export const markNotificationRead = async (notificationId: string): Promise<void> => {
await apiRequest<void>(`/notifications/${notificationId}/read`, { method: 'POST' });
};
export const markAllNotificationsRead = async (): Promise<void> => {
await apiRequest<void>('/notifications/read-all', { method: 'POST' });
};

View File

@@ -898,3 +898,52 @@ a.m-row:active, button.m-row:active { background: var(--bg-3) }
.auth { margin-top: 0; min-height: calc(100svh - 170px); display: flex; flex-direction: column; justify-content: center }
.auth form { width: 100% }
}
/* ---------- course reviews ---------- */
.reviews { margin-top: 40px }
.reviews-header { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-bottom: 16px }
.reviews-header h2 { font-size: 24px; font-weight: 700; letter-spacing: -.025em }
.reviews-header .count { color: var(--fg-2); font-size: 14px }
.reviews-layout { display: grid; grid-template-columns: minmax(150px, .32fr) minmax(0, 1fr); gap: 12px; margin-bottom: 14px }
.review-summary { display: flex; flex-direction: column; align-items: flex-start; justify-content: center; gap: 5px }
.review-average { font-size: 44px; font-weight: 700; letter-spacing: -.05em; line-height: 1 }
.review-summary small { color: var(--fg-2); font-size: 13px }
.review-stars { display: inline-flex; align-items: center; gap: 2px; color: var(--blue) }
.review-stars svg { width: 16px; height: 16px }
.review-form { display: grid; gap: 12px }
.review-form-label { display: block; font-size: 13px; font-weight: 600; margin-bottom: 7px }
.review-rating { display: flex; align-items: center; gap: 2px }
.review-rating button { display: inline-flex; padding: 2px; border-radius: 6px; color: var(--fg-3); transition: color .15s, transform .15s }
.review-rating button svg { width: 24px; height: 24px }
.review-rating button:hover, .review-rating button[aria-pressed="true"] { color: var(--blue) }
.review-rating button:active { transform: scale(.92) }
.review-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap }
.review-signin { display: flex; flex-direction: column; align-items: flex-start; gap: 8px }
.review-list { display: grid; gap: 8px }
.review-item { padding: 14px 16px; border-radius: var(--r-s); background: var(--bg-2) }
.review-item header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 5px }
.review-item header b { font-size: 14px; font-weight: 600 }
.review-item header small { color: var(--fg-3); font-size: 12px; flex: none }
.review-item p { font-size: 14px; color: var(--fg-2); white-space: pre-line }
.week-goal { display: grid; grid-template-columns: minmax(0, 1fr) 140px; gap: 10px 16px; align-items: center; margin-top: 16px }
.week-goal .prog { grid-column: 1 / -1; display: block; margin: 0 }
/* ---------- notifications ---------- */
.side-top .notif { position: relative; margin-left: auto; color: var(--fg-2) }
:root.collapsed .side-top .notif { margin-left: 0 }
.notif-badge { position: absolute; top: 2px; right: 2px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; background: var(--blue); color: var(--white); font-size: 10px; font-weight: 700; line-height: 1; display: grid; place-items: center }
.notification-list { display: grid; gap: 8px; max-width: 860px }
.notification { display: flex; align-items: flex-start; gap: 12px; padding: 16px; border-radius: var(--r-s); background: var(--bg-2); transition: background-color .2s, transform .15s }
@media (hover: hover) { .notification:hover { background: var(--bg-3); transform: translateY(-1px) } }
.notification.unread { background: var(--bg-3); box-shadow: inset 3px 0 0 var(--blue) }
.notification .n-ic { width: 36px; height: 36px; flex: none; border-radius: 50%; display: grid; place-items: center; background: var(--blue-soft); color: var(--blue) }
.notification .n-copy { flex: 1; min-width: 0 }
.notification b { display: block; font-size: 15px; font-weight: 600 }
.notification p { margin-top: 3px; color: var(--fg-2); font-size: 14px }
.notification small { flex: none; color: var(--fg-3); font-size: 12px; white-space: nowrap }
.notification-empty .ph { width: 36px; height: 36px; color: var(--fg-3); margin-bottom: 8px }
.notification-empty h2 { font-size: 20px; margin-bottom: 6px }
@media (max-width: 760px) {
.reviews-layout { grid-template-columns: 1fr }
.review-average { font-size: 36px }
}