284 lines
13 KiB
TypeScript
284 lines
13 KiB
TypeScript
import type { FastifyPluginAsync } from 'fastify';
|
|
import { z } from 'zod';
|
|
import { pool } from '../db/pool.js';
|
|
import { recordAudit } from '../audit.js';
|
|
|
|
const courseParamsSchema = z.object({
|
|
courseId: z.string().uuid(),
|
|
});
|
|
|
|
const lessonParamsSchema = z.object({
|
|
lessonId: z.string().uuid(),
|
|
});
|
|
|
|
const completionSchema = z.object({
|
|
completed: z.boolean().optional(),
|
|
watchedSeconds: z.coerce.number().int().min(0).optional(),
|
|
}).refine((input) => input.completed !== undefined || input.watchedSeconds !== undefined, { message: 'Informe o progresso ou o status de conclusão.' });
|
|
|
|
const commentSchema = z.object({
|
|
lessonId: z.string().uuid().nullable().optional(),
|
|
text: z.string().trim().min(1).max(4000),
|
|
});
|
|
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),
|
|
});
|
|
|
|
const ensurePublishedCourse = async (courseId: string) => {
|
|
const result = await pool.query(
|
|
"select id from courses where id = $1 and status = 'published'",
|
|
[courseId],
|
|
);
|
|
return result.rowCount === 1;
|
|
};
|
|
|
|
const canViewCourseComments = async (courseId: string, user: { id: string; role: string }) => {
|
|
const result = await pool.query<{ status: string; instructor_id: string }>('select status, instructor_id from courses where id = $1', [courseId]);
|
|
const course = result.rows[0];
|
|
return Boolean(course && (course.status === 'published' || user.role === 'admin' || course.instructor_id === user.id));
|
|
};
|
|
|
|
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) => {
|
|
const { limit, offset } = communityQuerySchema.parse(request.query);
|
|
const result = await pool.query(
|
|
`select c.id, c.course_id as "courseId", c.lesson_id as "lessonId", c.body as text,
|
|
c.created_at as "createdAt", u.display_name as "user",
|
|
cr.body as reply, cr.created_at as "replyCreatedAt"
|
|
from comments c
|
|
join users u on u.id = c.author_id
|
|
join courses co on co.id = c.course_id and co.status = 'published'
|
|
left join comment_replies cr on cr.comment_id = c.id
|
|
order by c.created_at desc
|
|
limit $1 offset $2`,
|
|
[limit, offset],
|
|
);
|
|
return { data: result.rows };
|
|
});
|
|
|
|
const canModerateComment = async (commentId: string, user: { id: string; role: string }) => {
|
|
const result = await pool.query<{ instructor_id: string }>(
|
|
`select c.instructor_id
|
|
from comments cm join courses c on c.id = cm.course_id
|
|
where cm.id = $1`,
|
|
[commentId],
|
|
);
|
|
const comment = result.rows[0];
|
|
return Boolean(comment && (user.role === 'admin' || comment.instructor_id === user.id));
|
|
};
|
|
app.get('/courses/:courseId/progress', { preHandler: app.authenticate }, async (request, reply) => {
|
|
const { courseId } = courseParamsSchema.parse(request.params);
|
|
if (!(await ensurePublishedCourse(courseId))) {
|
|
return reply.code(404).send({ error: 'Curso não encontrado.' });
|
|
}
|
|
|
|
const result = await pool.query(
|
|
`select lp.lesson_id as "lessonId", lp.watched_seconds as "watchedSeconds",
|
|
lp.completed_at as "completedAt", lp.updated_at as "updatedAt"
|
|
from lesson_progress lp
|
|
join lessons l on l.id = lp.lesson_id
|
|
where lp.user_id = $1 and l.course_id = $2
|
|
order by l.position`,
|
|
[request.user.id, courseId],
|
|
);
|
|
return { data: result.rows };
|
|
});
|
|
|
|
app.put('/lessons/:lessonId/progress', { preHandler: app.authenticate }, async (request, reply) => {
|
|
const { lessonId } = lessonParamsSchema.parse(request.params);
|
|
const input = completionSchema.parse(request.body);
|
|
const lesson = 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'`,
|
|
[lessonId],
|
|
);
|
|
|
|
if (lesson.rowCount !== 1) {
|
|
return reply.code(404).send({ error: 'Aula não encontrada.' });
|
|
}
|
|
|
|
const result = await pool.query(
|
|
`insert into lesson_progress (lesson_id, user_id, watched_seconds, completed_at)
|
|
values ($1, $2, $3, case when $4 is true then now() else null end)
|
|
on conflict (lesson_id, user_id) do update set
|
|
watched_seconds = greatest(lesson_progress.watched_seconds, excluded.watched_seconds),
|
|
completed_at = case when $4 is true then coalesce(lesson_progress.completed_at, now())
|
|
when $4 is false then null
|
|
else lesson_progress.completed_at end
|
|
returning lesson_id as "lessonId", watched_seconds as "watchedSeconds",
|
|
completed_at as "completedAt", updated_at as "updatedAt"`,
|
|
[lessonId, request.user.id, input.watchedSeconds || 0, input.completed ?? null],
|
|
);
|
|
return { data: result.rows[0] };
|
|
});
|
|
|
|
app.get('/courses/:courseId/comments', { preHandler: app.authenticate }, async (request, reply) => {
|
|
const { courseId } = courseParamsSchema.parse(request.params);
|
|
if (!(await canViewCourseComments(courseId, request.user))) {
|
|
return reply.code(404).send({ error: 'Curso não encontrado.' });
|
|
}
|
|
|
|
const result = await pool.query(
|
|
`select c.id, c.course_id as "courseId", c.lesson_id as "lessonId", c.body as text,
|
|
c.created_at as "createdAt", u.display_name as "user",
|
|
cr.body as reply, cr.created_at as "replyCreatedAt"
|
|
from comments c
|
|
join users u on u.id = c.author_id
|
|
left join comment_replies cr on cr.comment_id = c.id
|
|
where c.course_id = $1
|
|
order by c.created_at desc`,
|
|
[courseId],
|
|
);
|
|
return { data: result.rows };
|
|
});
|
|
|
|
app.post('/courses/:courseId/comments', { preHandler: app.authenticate }, async (request, reply) => {
|
|
const { courseId } = courseParamsSchema.parse(request.params);
|
|
const input = commentSchema.parse(request.body);
|
|
if (!(await ensurePublishedCourse(courseId))) {
|
|
return reply.code(404).send({ error: 'Curso não encontrado.' });
|
|
}
|
|
|
|
if (input.lessonId) {
|
|
const lesson = await pool.query('select id from lessons where id = $1 and course_id = $2', [input.lessonId, courseId]);
|
|
if (lesson.rowCount !== 1) {
|
|
return reply.code(400).send({ error: 'Esta aula não pertence ao curso.' });
|
|
}
|
|
}
|
|
|
|
const result = await pool.query(
|
|
`with inserted as (
|
|
insert into comments (course_id, lesson_id, author_id, body)
|
|
values ($1, $2, $3, $4)
|
|
returning id, course_id, lesson_id, body, created_at
|
|
)
|
|
select inserted.id, inserted.course_id as "courseId", inserted.lesson_id as "lessonId",
|
|
inserted.body as text, inserted.created_at as "createdAt", u.display_name as "user"
|
|
from inserted
|
|
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] });
|
|
});
|
|
|
|
app.put('/comments/:commentId/reply', { preHandler: app.requireRoles(['instructor', 'admin']) }, async (request, reply) => {
|
|
const { commentId } = commentParamsSchema.parse(request.params);
|
|
const input = replySchema.parse(request.body);
|
|
if (!(await canModerateComment(commentId, request.user))) return reply.code(403).send({ error: 'Você não pode responder a este comentário.' });
|
|
await pool.query(
|
|
`insert into comment_replies (comment_id, author_id, body)
|
|
values ($1, $2, $3)
|
|
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 } };
|
|
});
|
|
|
|
app.delete('/comments/:commentId', { preHandler: app.requireRoles(['instructor', 'admin']) }, async (request, reply) => {
|
|
const { commentId } = commentParamsSchema.parse(request.params);
|
|
if (!(await canModerateComment(commentId, request.user))) return reply.code(403).send({ error: 'Você não pode moderar este comentário.' });
|
|
await pool.query('delete from comments where id = $1', [commentId]);
|
|
await recordAudit({ actorId: request.user.id, action: 'comment.deleted', subjectType: 'comment', subjectId: commentId, ipAddress: request.ip });
|
|
return reply.code(204).send();
|
|
});
|
|
};
|