diff --git a/pages/YouPage.tsx b/pages/YouPage.tsx
index 83affda..6002a4e 100644
--- a/pages/YouPage.tsx
+++ b/pages/YouPage.tsx
@@ -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 ? <>
{user.name}{user.email}
{canTeach &&
}
-
+
> : <>
Entre para continuar
Com uma conta gratuita você assiste aos cursos, salva o progresso e participa da comunidade.
Criar conta
Entrar
>}
{user &&
}
diff --git a/server/migrations/017_account_views_notes.sql b/server/migrations/017_account_views_notes.sql
new file mode 100644
index 0000000..9a7e351
--- /dev/null
+++ b/server/migrations/017_account_views_notes.sql
@@ -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);
diff --git a/server/migrations/018_course_reviews.sql b/server/migrations/018_course_reviews.sql
new file mode 100644
index 0000000..19f42fb
--- /dev/null
+++ b/server/migrations/018_course_reviews.sql
@@ -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);
diff --git a/server/migrations/019_notifications.sql b/server/migrations/019_notifications.sql
new file mode 100644
index 0000000..e330cad
--- /dev/null
+++ b/server/migrations/019_notifications.sql
@@ -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;
diff --git a/server/src/app.ts b/server/src/app.ts
index 15789a8..874e282 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -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' });
diff --git a/server/src/auth/plugin.ts b/server/src/auth/plugin.ts
index e6c46b5..fc52795 100644
--- a/server/src/auth/plugin.ts
+++ b/server/src/auth/plugin.ts
@@ -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;
};
diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts
index 0734187..6e4e012 100644
--- a/server/src/routes/admin.ts
+++ b/server/src/routes/admin.ts
@@ -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) => {
diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts
index cd04ea2..b83fde1 100644
--- a/server/src/routes/auth.ts
+++ b/server/src/routes/auth.ts
@@ -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
(
`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(
`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(
- `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];
diff --git a/server/src/routes/courses.ts b/server/src/routes/courses.ts
index 7b36e90..14048de 100644
--- a/server/src/routes/courses.ts
+++ b/server/src/routes/courses.ts
@@ -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<{
diff --git a/server/src/routes/learning.ts b/server/src/routes/learning.ts
index cbc50bb..ae80340 100644
--- a/server/src/routes/learning.ts
+++ b/server/src/routes/learning.ts
@@ -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 } };
});
diff --git a/server/src/routes/notifications.ts b/server/src/routes/notifications.ts
new file mode 100644
index 0000000..713eaa6
--- /dev/null
+++ b/server/src/routes/notifications.ts
@@ -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();
+ });
+};
diff --git a/server/src/services/email.ts b/server/src/services/email.ts
index 5251745..872c3db 100644
--- a/server/src/services/email.ts
+++ b/server/src/services/email.ts
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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: `Bem-vindo(a), ${escapedName}!
Sua conta no Compor HUB já está pronta.
Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.
Acessar Compor HUB
`,
- });
+ await transporter.sendMail({ from: config.MAIL_FROM, to, subject, html });
return true;
+};
+
+const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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',
+ `Bem-vindo(a), ${escapedName}!
Sua conta no Compor HUB já está pronta.
Agora você pode acessar cursos, acompanhar suas aulas e baixar materiais complementares.
Acessar Compor HUB
`,
+ );
+}
+
+export async function sendInvitationEmail(recipient: { email: string; inviteUrl: string }) {
+ return sendEmail(
+ recipient.email,
+ 'Você foi convidado para o Compor HUB',
+ `Convite para o Compor HUB
Você recebeu acesso como professor à plataforma.
Defina seu nome e sua senha para começar.
Aceitar convite
Este link expira em ${config.INVITATION_TTL_HOURS} horas.
`,
+ );
+}
+
+export async function sendPasswordResetEmail(recipient: { email: string; resetUrl: string }) {
+ return sendEmail(
+ recipient.email,
+ 'Redefinição de senha do Compor HUB',
+ `Redefinir senha
Recebemos um pedido para redefinir a senha da sua conta.
Escolher nova senha
Se você não pediu isso, ignore este e-mail. O link expira em ${config.PASSWORD_RESET_TTL_HOURS} horas.
`,
+ );
}
diff --git a/services/api.ts b/services/api.ts
index 7bf6bbe..c97b78d 100644
--- a/services/api.ts
+++ b/services/api.ts
@@ -220,6 +220,9 @@ export const authApi = {
async resetPassword(token: string, password: string) {
return apiRequest('/auth/reset-password', { method: 'POST', body: JSON.stringify({ token, password }) });
},
+ async forgotPassword(email: string) {
+ return apiRequest('/auth/forgot-password', { method: 'POST', body: JSON.stringify({ email }) });
+ },
};
export const adminApi = {
diff --git a/services/db.ts b/services/db.ts
index becfea0..081d1a5 100644
--- a/services/db.ts
+++ b/services/db.ts
@@ -420,3 +420,72 @@ export const getCommunityComments = async (limit = 100, offset = 0): Promise(`/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 => {
+ 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 => {
+ const response = await apiRequest<{ data: CourseReviewSummary }>(`/courses/${courseId}/reviews`);
+ return response.data;
+};
+
+export const getMyCourseReview = async (courseId: string): Promise => {
+ 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 => {
+ await apiRequest(`/courses/${courseId}/reviews/mine`, { method: 'DELETE' });
+};
+
+export type LessonNote = { body: string; updatedAt: string | null };
+
+export const getLessonNote = async (lessonId: string): Promise => {
+ const response = await apiRequest<{ data: LessonNote }>(`/lessons/${lessonId}/note`);
+ return response.data;
+};
+
+export const saveLessonNote = async (lessonId: string, body: string): Promise => {
+ const response = await apiRequest<{ data: LessonNote }>(`/lessons/${lessonId}/note`, {
+ method: 'PUT',
+ body: JSON.stringify({ body }),
+ });
+ return response.data;
+};
diff --git a/services/notifications.ts b/services/notifications.ts
new file mode 100644
index 0000000..0502141
--- /dev/null
+++ b/services/notifications.ts
@@ -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 => {
+ const response = await apiRequest<{ data: NotificationFeed }>('/notifications');
+ return response.data;
+};
+
+export const markNotificationRead = async (notificationId: string): Promise => {
+ await apiRequest(`/notifications/${notificationId}/read`, { method: 'POST' });
+};
+
+export const markAllNotificationsRead = async (): Promise => {
+ await apiRequest('/notifications/read-all', { method: 'POST' });
+};
diff --git a/styles/app.css b/styles/app.css
index bbf63b1..aa50668 100644
--- a/styles/app.css
+++ b/styles/app.css
@@ -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 }
+}