diff --git a/docs/backend_arch.md b/docs/backend_arch.md index 0417568..3bbcf6c 100644 --- a/docs/backend_arch.md +++ b/docs/backend_arch.md @@ -197,7 +197,11 @@ pasa. ejecución, una asignación como `teacher`. - `Preparar y enviar entregas` (contenido y envío) queda reservado al `student` asignado o a un `admin`. Docentes, evaluadores, directivos y proponentes solo - configuran y revisan la entrega, aunque estén asignados al proyecto. + configuran y revisan la entrega, aunque estén asignados al proyecto. Mientras + la entrega esté `pending` o `rejected`, su contenido solo lo ven los + estudiantes asignados y los administradores; al enviarse queda visible para + los miembros del proyecto. La misma regla protege el stream de archivos y la + descarga de adjuntos vinculados a la entrega. - El `evaluator` de expo no tiene acceso global: solo participa en los proyectos donde se le asigna el rol de proyecto `evaluator`. En ellos conserva los permisos de revisión y aprobación de fase. diff --git a/docs/database_arch.md b/docs/database_arch.md index eb1042d..4132d1c 100644 --- a/docs/database_arch.md +++ b/docs/database_arch.md @@ -203,7 +203,10 @@ debe coincidir con el `type` de su entrega. Los tipos de texto y enlace usan `textContent`/`url`/`label`; los de archivo referencian un `ProjectAttachment` (`attachmentId`, único) y el binario vive en S3/RustFS. Cada fila guarda su autor y su fecha de creación. Solo el estudiante asignado al proyecto (o un -administrador) puede aportar contenido y enviar la entrega. +administrador) puede aportar contenido y enviar la entrega. Mientras la entrega +está `pending` o `rejected`, el contenido solo se expone a los estudiantes +asignados y a los administradores; tras el envío lo ven todos los miembros del +proyecto. ### MilestoneReportLink diff --git a/docs/frontend_arch.md b/docs/frontend_arch.md index 9778e9a..9f85500 100644 --- a/docs/frontend_arch.md +++ b/docs/frontend_arch.md @@ -133,7 +133,9 @@ La pestaña **Hitos** permite marcar hitos como **mínimos**, asignarles una fas no se puede completar hasta que todas estén aceptadas. Al elegir el estado «Finalizado» se avisa si aún quedan hitos mínimos pendientes o falta la evaluación de la fase. En las entregas se muestra a qué hitos están vinculadas y -se advierte antes de eliminar hitos o entregas que tienen vínculos. +se advierte antes de eliminar hitos o entregas que tienen vínculos. Cuando una +entrega aún no se ha enviado, quien no es estudiante asignado ve un aviso de +contenido privado en lugar de sus textos, enlaces y archivos. Los estudiantes ven los proyectos privados en `approved` mediante `ProjectPrivatePreview`: una vista con aviso de información limitada, descripción, diff --git a/hub-backend/src/attachments/attachments.service.spec.ts b/hub-backend/src/attachments/attachments.service.spec.ts new file mode 100644 index 0000000..a1247fc --- /dev/null +++ b/hub-backend/src/attachments/attachments.service.spec.ts @@ -0,0 +1,91 @@ +import { ForbiddenException } from '@nestjs/common'; +import { Readable } from 'node:stream'; +import { AttachmentsService } from './attachments.service'; + +describe('AttachmentsService', () => { + const user = { + id: 7, + fullName: 'Teacher', + email: 'teacher@example.com', + roles: ['teacher'], + } as never; + + function createService() { + const prisma = { + project: { findUnique: jest.fn() }, + projectAttachment: { findFirst: jest.fn() }, + }; + const storage = { read: jest.fn() }; + const authorization = { + assertProjectMember: jest.fn(), + assertCanViewReportContents: jest.fn(), + }; + + return { + service: new AttachmentsService( + prisma as never, + storage as never, + authorization as never, + ), + prisma, + storage, + authorization, + }; + } + + function selectedAttachment(overrides: Record = {}) { + return { + id: 55, + projectId: 10, + reportId: 3, + uploadedByUserId: 7, + originalName: 'documento.pdf', + storageKey: 'projects/10/documento.pdf', + mimeType: 'application/pdf', + sizeBytes: 1024, + createdAt: new Date('2026-09-13'), + uploadedBy: null, + ...overrides, + }; + } + + it('blocks downloading an attachment linked to a draft report', async () => { + const { service, prisma, storage, authorization } = createService(); + prisma.project.findUnique.mockResolvedValue({ id: 10 }); + prisma.projectAttachment.findFirst.mockResolvedValue( + selectedAttachment({ report: { status: 'pending' } }), + ); + authorization.assertCanViewReportContents.mockRejectedValue( + new ForbiddenException('Report contents are hidden'), + ); + + await expect( + service.downloadAttachment({ projectId: 10, attachmentId: 55, user }), + ).rejects.toBeInstanceOf(ForbiddenException); + + expect(authorization.assertCanViewReportContents).toHaveBeenCalledWith( + user, + 10, + { status: 'pending' }, + ); + expect(storage.read).not.toHaveBeenCalled(); + }); + + it('downloads an attachment once the report has been submitted', async () => { + const { service, prisma, storage } = createService(); + prisma.project.findUnique.mockResolvedValue({ id: 10 }); + prisma.projectAttachment.findFirst.mockResolvedValue( + selectedAttachment({ report: { status: 'submitted' } }), + ); + storage.read.mockResolvedValue({ stream: Readable.from([]) }); + + const result = await service.downloadAttachment({ + projectId: 10, + attachmentId: 55, + user, + }); + + expect(result.attachment.originalName).toBe('documento.pdf'); + expect(storage.read).toHaveBeenCalledWith('projects/10/documento.pdf'); + }); +}); diff --git a/hub-backend/src/attachments/attachments.service.ts b/hub-backend/src/attachments/attachments.service.ts index 5d72e6a..8aa2fa6 100644 --- a/hub-backend/src/attachments/attachments.service.ts +++ b/hub-backend/src/attachments/attachments.service.ts @@ -107,7 +107,10 @@ export class AttachmentsService { const attachment = await this.prisma.projectAttachment.findFirst({ where: { id: attachmentId, projectId }, - select: attachmentSelect, + select: { + ...attachmentSelect, + report: { select: { status: true } }, + }, }); if (!attachment) { @@ -116,6 +119,14 @@ export class AttachmentsService { ); } + if (attachment.report) { + await this.authorization.assertCanViewReportContents( + user, + projectId, + attachment.report, + ); + } + const stored = await this.storage.read(attachment.storageKey); return { attachment: mapAttachment(attachment), stream: stored.stream }; diff --git a/hub-backend/src/auth/authorization.service.spec.ts b/hub-backend/src/auth/authorization.service.spec.ts index 689c133..70a3841 100644 --- a/hub-backend/src/auth/authorization.service.spec.ts +++ b/hub-backend/src/auth/authorization.service.spec.ts @@ -1,5 +1,10 @@ import { ForbiddenException, NotFoundException } from '@nestjs/common'; -import { ActorRole, ProjectStatus, UserRole } from '../generated/prisma/client'; +import { + ActorRole, + ProjectStatus, + ReportStatus, + UserRole, +} from '../generated/prisma/client'; import { AuthorizationService } from './authorization.service'; describe('AuthorizationService', () => { @@ -624,6 +629,51 @@ describe('AuthorizationService', () => { }); }); + it('allows assigned students to view pending report contents', async () => { + const { service, findAssignment } = createService({ id: 5 }); + + await expect( + service.assertCanViewReportContents(user([UserRole.student]), 10, { + status: ReportStatus.pending, + }), + ).resolves.toBeUndefined(); + expect(findAssignment).toHaveBeenCalledWith({ + where: { projectId: 10, userId: 7, role: ActorRole.student }, + select: { id: true }, + }); + }); + + it('rejects pending report contents for users without a student assignment', async () => { + const { service } = createService(); + + await expect( + service.assertCanViewReportContents(user([UserRole.teacher]), 10, { + status: ReportStatus.pending, + }), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('hides rejected report contents again until they are resubmitted', async () => { + const { service } = createService(); + + await expect( + service.assertCanViewReportContents(user([UserRole.teacher]), 10, { + status: ReportStatus.rejected, + }), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('shows submitted report contents without checking the assignment', async () => { + const { service, findAssignment } = createService(); + + await expect( + service.assertCanViewReportContents(user([UserRole.teacher]), 10, { + status: ReportStatus.submitted, + }), + ).resolves.toBeUndefined(); + expect(findAssignment).not.toHaveBeenCalled(); + }); + describe('project visibility', () => { function visibilityPrisma(project: unknown) { return { diff --git a/hub-backend/src/auth/authorization.service.ts b/hub-backend/src/auth/authorization.service.ts index fdddf6a..b2a0afe 100644 --- a/hub-backend/src/auth/authorization.service.ts +++ b/hub-backend/src/auth/authorization.service.ts @@ -8,6 +8,7 @@ import { Prisma, UserRole, ProjectStatus, + ReportStatus, } from '../generated/prisma/client'; import { PrismaService } from '../prisma.service'; import { AuthenticatedUser } from './auth.types'; @@ -256,13 +257,16 @@ export class AuthorizationService { * Enviar entregas (y preparar su contenido) está reservado a * administradores y estudiantes asignados al proyecto. Docentes, * evaluadores y proponentes solo configuran y revisan la entrega. + * + * El mismo criterio decide quién puede ver el contenido de una entrega + * pendiente o rechazada. */ - async assertCanSubmitReports( + async canSubmitReports( user: AuthenticatedUser, projectId: number, - ): Promise { + ): Promise { if (user.roles.includes(UserRole.admin)) { - return; + return true; } const assignment = await this.prisma.projectActorAssignment.findFirst({ @@ -270,11 +274,46 @@ export class AuthorizationService { select: { id: true }, }); - if (!assignment) { - throw new ForbiddenException( - 'A project student assignment is required to submit reports', - ); + return Boolean(assignment); + } + + async assertCanSubmitReports( + user: AuthenticatedUser, + projectId: number, + ): Promise { + if (await this.canSubmitReports(user, projectId)) { + return; + } + + throw new ForbiddenException( + 'A project student assignment is required to submit reports', + ); + } + + /** + * El contenido de una entrega solo se expone a los miembros del proyecto + * cuando ya fue enviada. Mientras esté pendiente o rechazada, únicamente los + * estudiantes asignados (y los administradores) pueden consultarlo. + */ + async assertCanViewReportContents( + user: AuthenticatedUser, + projectId: number, + report: { status: ReportStatus }, + ): Promise { + if ( + report.status !== ReportStatus.pending && + report.status !== ReportStatus.rejected + ) { + return; } + + if (await this.canSubmitReports(user, projectId)) { + return; + } + + throw new ForbiddenException( + 'Report contents are only visible to assigned students until the report is submitted', + ); } assertCanCreateProject(user: AuthenticatedUser): void { diff --git a/hub-backend/src/projects/projects.select.ts b/hub-backend/src/projects/projects.select.ts index ccebb45..9914b8f 100644 --- a/hub-backend/src/projects/projects.select.ts +++ b/hub-backend/src/projects/projects.select.ts @@ -498,6 +498,16 @@ export function mapProjectDetailResponse( ): ProjectDetailResponse { const privatePreview = project.isPrivate && !canViewSensitiveData; const { canExpressInterest = false, viewerInterest = null } = viewerContext; + // Mismo criterio que `AuthorizationService.canSubmitReports`: el borrador de + // una entrega solo lo ve un administrador o un estudiante asignado. + const canViewDraftReportContents = + viewer != null && + (viewer.roles.includes(UserRole.admin) || + project.actorAssignments.some( + (assignment) => + assignment.userId === viewer.id && + assignment.role === ActorRole.student, + )); return { ...mapProjectListResponse(project, canViewSensitiveData), @@ -621,7 +631,7 @@ export function mapProjectDetailResponse( ? project.reports .slice() .sort(byDateThenId((report) => report.dueDate.getTime())) - .map(mapReport) + .map((report) => mapReport(report, canViewDraftReportContents)) : [], }; } diff --git a/hub-backend/src/reports/reports.select.ts b/hub-backend/src/reports/reports.select.ts index f20e751..dc05621 100644 --- a/hub-backend/src/reports/reports.select.ts +++ b/hub-backend/src/reports/reports.select.ts @@ -113,10 +113,25 @@ export type ProjectReportResponse = { createdBy: ReportUser | null; reviewedBy: ReportUser | null; milestones: { id: number; title: string }[]; + /** `false` mientras el contenido está oculto por no haberse enviado. */ + canViewContents: boolean; + /** Indica si existe contenido aunque `contents` venga oculto. */ + hasContents: boolean; contents: ProjectReportContentResponse[]; }; -export function mapReport(report: SelectedReport): ProjectReportResponse { +/** Estados en los que el estudiante aún puede editar el contenido. */ +export function isDraftReportStatus(status: ReportStatus): boolean { + return status === ReportStatus.pending || status === ReportStatus.rejected; +} + +export function mapReport( + report: SelectedReport, + canViewDraftContents = false, +): ProjectReportResponse { + const canViewContents = + !isDraftReportStatus(report.status) || canViewDraftContents; + return { id: report.id, projectId: report.projectId, @@ -138,6 +153,8 @@ export function mapReport(report: SelectedReport): ProjectReportResponse { id: link.milestone.id, title: link.milestone.title, })), - contents: report.contents.map(mapReportContent), + canViewContents, + hasContents: report.contents.length > 0, + contents: canViewContents ? report.contents.map(mapReportContent) : [], }; } diff --git a/hub-backend/src/reports/reports.service.spec.ts b/hub-backend/src/reports/reports.service.spec.ts index 5de9621..ab73c01 100644 --- a/hub-backend/src/reports/reports.service.spec.ts +++ b/hub-backend/src/reports/reports.service.spec.ts @@ -1,6 +1,7 @@ import { BadRequestException, ConflictException, + ForbiddenException, NotFoundException, } from '@nestjs/common'; import { ReportContentKind, ReportStatus } from '../generated/prisma/client'; @@ -118,6 +119,8 @@ describe('ReportsService', () => { assertProjectMember: jest.fn(), assertCanSubmitReports: jest.fn(), assertCanManageReports: jest.fn(), + assertCanViewReportContents: jest.fn(), + canSubmitReports: jest.fn().mockResolvedValue(false), }; const storage = { read: jest.fn(), @@ -137,6 +140,98 @@ describe('ReportsService', () => { }; } + it('hides draft contents from viewers who cannot submit reports', async () => { + const { service, prisma, authorization } = createService(); + prisma.project.findUnique.mockResolvedValue({ id: 10 }); + prisma.projectReport.findMany.mockResolvedValue([ + selectedReport({ + status: 'pending', + contents: [selectedContent()], + }), + selectedReport({ + id: 4, + status: 'rejected', + contents: [selectedContent({ id: 10, reportId: 4 })], + }), + selectedReport({ + id: 5, + status: 'submitted', + contents: [selectedContent({ id: 11, reportId: 5 })], + }), + ]); + + const result = await service.reportsByProject(10, user); + + expect(result[0]).toMatchObject({ + status: 'pending', + canViewContents: false, + hasContents: true, + contents: [], + }); + expect(result[1]).toMatchObject({ + status: 'rejected', + canViewContents: false, + hasContents: true, + contents: [], + }); + expect(result[2]).toMatchObject({ + status: 'submitted', + canViewContents: true, + hasContents: true, + }); + expect(result[2].contents).toHaveLength(1); + expect(authorization.canSubmitReports).toHaveBeenCalledWith(user, 10); + }); + + it('shows draft contents to assigned students', async () => { + const { service, prisma, authorization } = createService(); + prisma.project.findUnique.mockResolvedValue({ id: 10 }); + authorization.canSubmitReports.mockResolvedValue(true); + prisma.projectReport.findMany.mockResolvedValue([ + selectedReport({ + status: 'pending', + contents: [selectedContent()], + }), + ]); + + const result = await service.reportsByProject(10, user); + + expect(result[0]).toMatchObject({ + status: 'pending', + canViewContents: true, + hasContents: true, + }); + expect(result[0].contents).toHaveLength(1); + }); + + it('blocks streaming draft content when the viewer cannot submit reports', async () => { + const { service, prisma, authorization, storage } = createService(); + prisma.project.findUnique.mockResolvedValue({ id: 10 }); + prisma.projectReportContent.findFirst.mockResolvedValue({ + ...selectedContent({ kind: 'file' }), + report: { status: 'pending' }, + }); + authorization.assertCanViewReportContents.mockRejectedValue( + new ForbiddenException('Report contents are hidden'), + ); + + await expect( + service.openContentStream({ + projectId: 10, + reportId: 3, + contentId: 9, + user, + }), + ).rejects.toBeInstanceOf(ForbiddenException); + + expect(authorization.assertCanViewReportContents).toHaveBeenCalledWith( + user, + 10, + { status: 'pending' }, + ); + expect(storage.read).not.toHaveBeenCalled(); + }); + const FILE_MIME_TYPES = [ 'application/pdf', 'application/msword', diff --git a/hub-backend/src/reports/reports.service.ts b/hub-backend/src/reports/reports.service.ts index 0ebf6ff..da14691 100644 --- a/hub-backend/src/reports/reports.service.ts +++ b/hub-backend/src/reports/reports.service.ts @@ -38,6 +38,7 @@ import { import { ProjectReportContentResponse, ProjectReportResponse, + SelectedReport, mapReport, mapReportContent, reportContentSelect, @@ -77,13 +78,17 @@ export class ReportsService { ): Promise { await this.assertProjectAccess(projectId, user); + const canViewDraftContents = await this.authorization.canSubmitReports( + user, + projectId, + ); const reports = await this.prisma.projectReport.findMany({ where: { projectId }, orderBy: [{ dueDate: 'asc' }, { id: 'asc' }], select: reportSelect, }); - return reports.map(mapReport); + return reports.map((report) => mapReport(report, canViewDraftContents)); } async createReport(params: { @@ -114,7 +119,7 @@ export class ReportsService { select: reportSelect, }); - return mapReport(report); + return this.mapReportForViewer(report, user, projectId); } async updateReport(params: { @@ -174,7 +179,7 @@ export class ReportsService { select: reportSelect, }); - return mapReport(report); + return this.mapReportForViewer(report, user, projectId); } async deleteReport(params: { @@ -210,7 +215,7 @@ export class ReportsService { attachments.map((attachment) => this.safeDelete(attachment.storageKey)), ); - return mapReport(report); + return this.mapReportForViewer(report, user, projectId); } async submitReport(params: { @@ -253,7 +258,7 @@ export class ReportsService { select: reportSelect, }); - return mapReport(report); + return this.mapReportForViewer(report, user, projectId); } async reviewReport(params: { @@ -284,7 +289,7 @@ export class ReportsService { select: reportSelect, }); - return mapReport(report); + return this.mapReportForViewer(report, user, projectId); } async createContent(params: { @@ -491,7 +496,10 @@ export class ReportsService { const content = await this.prisma.projectReportContent.findFirst({ where: { id: contentId, reportId, report: { projectId } }, - select: reportContentSelect, + select: { + ...reportContentSelect, + report: { select: { status: true } }, + }, }); if (!content) { @@ -500,6 +508,12 @@ export class ReportsService { ); } + await this.authorization.assertCanViewReportContents( + user, + projectId, + content.report, + ); + if (!content.attachment) { throw new BadRequestException('Content has no file to stream'); } @@ -709,6 +723,19 @@ export class ReportsService { } } + private async mapReportForViewer( + report: SelectedReport, + user: AuthenticatedUser, + projectId: number, + ): Promise { + const canViewDraftContents = await this.authorization.canSubmitReports( + user, + projectId, + ); + + return mapReport(report, canViewDraftContents); + } + private async assertProjectAccess( projectId: number, user: AuthenticatedUser, diff --git a/hub-backend/test/helpers/projects.ts b/hub-backend/test/helpers/projects.ts index f923850..225cbc7 100644 --- a/hub-backend/test/helpers/projects.ts +++ b/hub-backend/test/helpers/projects.ts @@ -1,8 +1,19 @@ import { INestApplication } from '@nestjs/common'; import request from 'supertest'; import { App } from 'supertest/types'; -import { bearer, registerUser, uniqueEmail } from './auth'; -import { ActorRole, ProjectStatus } from '../../src/generated/prisma/client'; +import { + AuthSession, + adminSession, + bearer, + registerUser, + uniqueEmail, + userWithRole, +} from './auth'; +import { + ActorRole, + ProjectStatus, + UserRole, +} from '../../src/generated/prisma/client'; /** Crea un proyecto privado como el usuario indicado y devuelve su id. */ export async function createProject( @@ -82,6 +93,38 @@ export async function assignProjectActor( return (response.body as { id: number }).id; } +/** Crea un proyecto con un docente y un estudiante ya asignados. */ +export async function createProjectWithTeacherAndStudent( + app: INestApplication, +): Promise<{ + projectId: number; + admin: AuthSession; + teacher: AuthSession; + student: AuthSession; +}> { + const admin = await adminSession(app); + const teacher = await userWithRole(app, UserRole.teacher); + const student = await userWithRole(app, UserRole.student); + const { projectId } = await createProjectWithProposer(app); + + await assignProjectActor( + app, + projectId, + admin.accessToken, + teacher.user.id, + ActorRole.teacher, + ); + await assignProjectActor( + app, + projectId, + admin.accessToken, + student.user.id, + ActorRole.student, + ); + + return { projectId, admin, teacher, student }; +} + /** Envía una evaluación perfecta de la fase actual usando la rúbrica vigente. */ export async function submitCurrentPhaseEvaluation( app: INestApplication, diff --git a/hub-backend/test/helpers/reports.ts b/hub-backend/test/helpers/reports.ts new file mode 100644 index 0000000..498bc6f --- /dev/null +++ b/hub-backend/test/helpers/reports.ts @@ -0,0 +1,47 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { App } from 'supertest/types'; +import { bearer } from './auth'; +import { futureIsoDate } from './projects'; + +/** Crea una entrega de tipo texto y devuelve su id. */ +export async function createTextReport( + app: INestApplication, + projectId: number, + token: string, + title = 'Informe', +): Promise { + const created = await request(app.getHttpServer()) + .post(`/projects/${projectId}/reports`) + .set(bearer(token)) + .send({ title, dueDate: futureIsoDate(), type: 'text' }) + .expect(201); + + return (created.body as { id: number }).id; +} + +export async function addReportTextContent( + app: INestApplication, + projectId: number, + reportId: number, + token: string, + textContent: string, +): Promise { + await request(app.getHttpServer()) + .post(`/projects/${projectId}/reports/${reportId}/contents`) + .set(bearer(token)) + .send({ kind: 'text', textContent }) + .expect(201); +} + +export async function submitReport( + app: INestApplication, + projectId: number, + reportId: number, + token: string, +): Promise { + await request(app.getHttpServer()) + .post(`/projects/${projectId}/reports/${reportId}/submit`) + .set(bearer(token)) + .expect(201); +} diff --git a/hub-backend/test/reports.e2e-spec.ts b/hub-backend/test/reports.e2e-spec.ts index ff216aa..15b2f27 100644 --- a/hub-backend/test/reports.e2e-spec.ts +++ b/hub-backend/test/reports.e2e-spec.ts @@ -1,6 +1,4 @@ -import { INestApplication } from '@nestjs/common'; import request from 'supertest'; -import { App } from 'supertest/types'; import { useTestApp } from './helpers/e2e'; import { adminSession, @@ -9,9 +7,15 @@ import { uniqueEmail, userWithRole, } from './helpers/auth'; +import { + addReportTextContent, + createTextReport, + submitReport, +} from './helpers/reports'; import { assignProjectActor, createProjectWithProposer, + createProjectWithTeacherAndStudent, futureIsoDate, transitionProjectStatus, } from './helpers/projects'; @@ -24,21 +28,6 @@ import { describe('Reports (e2e)', () => { const getApp = useTestApp(); - /** Crea una entrega de tipo texto y devuelve su id. */ - async function createReport( - app: INestApplication, - projectId: number, - token: string, - ): Promise { - const created = await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports`) - .set(bearer(token)) - .send({ title: 'Informe final', dueDate: futureIsoDate(), type: 'text' }) - .expect(201); - - return (created.body as { id: number }).id; - } - it('un directivo gestiona y revisa entregas y un estudiante asignado las envía', async () => { const app = getApp(); const directivo = await userWithRole(app, UserRole.directivo); @@ -47,7 +36,11 @@ describe('Reports (e2e)', () => { // El directivo crea la entrega y asigna al estudiante sin estar asignado al // proyecto. - const reportId = await createReport(app, projectId, directivo.accessToken); + const reportId = await createTextReport( + app, + projectId, + directivo.accessToken, + ); await assignProjectActor( app, projectId, @@ -57,16 +50,14 @@ describe('Reports (e2e)', () => { ); // El estudiante asignado prepara el contenido y envía la entrega. - await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports/${reportId}/contents`) - .set(bearer(student.accessToken)) - .send({ kind: 'text', textContent: 'Contenido de prueba' }) - .expect(201); - - await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports/${reportId}/submit`) - .set(bearer(student.accessToken)) - .expect(201); + await addReportTextContent( + app, + projectId, + reportId, + student.accessToken, + 'Contenido de prueba', + ); + await submitReport(app, projectId, reportId, student.accessToken); // El directivo la revisa sin asignación. const reviewed = await request(app.getHttpServer()) @@ -78,13 +69,124 @@ describe('Reports (e2e)', () => { expect(reviewed.body).toMatchObject({ id: reportId, status: 'accepted' }); }); + it('oculta el contenido de entregas sin enviar a docentes y lo muestra a estudiantes asignados', async () => { + const app = getApp(); + const { projectId, admin, teacher, student } = + await createProjectWithTeacherAndStudent(app); + const reportId = await createTextReport(app, projectId, admin.accessToken); + + await addReportTextContent( + app, + projectId, + reportId, + student.accessToken, + 'Contenido privado', + ); + + type ReportBody = { + id: number; + canViewContents: boolean; + hasContents: boolean; + contents: { textContent: string | null }[]; + }; + + const reportFrom = (body: unknown): ReportBody => { + const report = (body as ReportBody[]).find(({ id }) => id === reportId); + + if (!report) { + throw new Error(`Report ${reportId} not found in response`); + } + + return report; + }; + + const teacherReports = await request(app.getHttpServer()) + .get(`/projects/${projectId}/reports`) + .set(bearer(teacher.accessToken)) + .expect(200); + + expect(reportFrom(teacherReports.body)).toMatchObject({ + status: 'pending', + canViewContents: false, + hasContents: true, + contents: [], + }); + + const studentReports = await request(app.getHttpServer()) + .get(`/projects/${projectId}/reports`) + .set(bearer(student.accessToken)) + .expect(200); + + expect(reportFrom(studentReports.body)).toMatchObject({ + canViewContents: true, + hasContents: true, + contents: [expect.objectContaining({ textContent: 'Contenido privado' })], + }); + + const teacherDetail = await request(app.getHttpServer()) + .get(`/projects/${projectId}`) + .set(bearer(teacher.accessToken)) + .expect(200); + + expect( + reportFrom((teacherDetail.body as { reports: unknown }).reports), + ).toMatchObject({ contents: [] }); + + const studentDetail = await request(app.getHttpServer()) + .get(`/projects/${projectId}`) + .set(bearer(student.accessToken)) + .expect(200); + + expect( + reportFrom((studentDetail.body as { reports: unknown }).reports).contents, + ).toHaveLength(1); + + await submitReport(app, projectId, reportId, student.accessToken); + + const teacherSubmitted = await request(app.getHttpServer()) + .get(`/projects/${projectId}/reports`) + .set(bearer(teacher.accessToken)) + .expect(200); + + expect(reportFrom(teacherSubmitted.body)).toMatchObject({ + canViewContents: true, + contents: [expect.objectContaining({ textContent: 'Contenido privado' })], + }); + + await request(app.getHttpServer()) + .post(`/projects/${projectId}/reports/${reportId}/review`) + .set(bearer(teacher.accessToken)) + .send({ decision: 'rejected', comment: 'Falta documentación' }) + .expect(201); + + const teacherRejected = await request(app.getHttpServer()) + .get(`/projects/${projectId}/reports`) + .set(bearer(teacher.accessToken)) + .expect(200); + + expect(reportFrom(teacherRejected.body)).toMatchObject({ + canViewContents: false, + contents: [], + }); + + const studentRejected = await request(app.getHttpServer()) + .get(`/projects/${projectId}/reports`) + .set(bearer(student.accessToken)) + .expect(200); + + expect(reportFrom(studentRejected.body)).toMatchObject({ + canViewContents: true, + contents: [expect.objectContaining({ textContent: 'Contenido privado' })], + }); + }); + it('rechaza preparar o enviar entregas a proponentes y docentes', async () => { const app = getApp(); const admin = await adminSession(app); const { proposerToken, projectId } = await createProjectWithProposer(app); const teacher = await userWithRole(app, UserRole.teacher); - const reportId = await createReport(app, projectId, admin.accessToken); + const reportId = await createTextReport(app, projectId, admin.accessToken); await assignProjectActor( app, projectId, diff --git a/hub-backend/test/stats.e2e-spec.ts b/hub-backend/test/stats.e2e-spec.ts index 82dd67f..e746352 100644 --- a/hub-backend/test/stats.e2e-spec.ts +++ b/hub-backend/test/stats.e2e-spec.ts @@ -4,8 +4,13 @@ import { adminSession, bearer, userWithRole } from './helpers/auth'; import { assignProjectActor, createProjectWithProposer, - futureIsoDate, + createProjectWithTeacherAndStudent, } from './helpers/projects'; +import { + addReportTextContent, + createTextReport, + submitReport, +} from './helpers/reports'; import { ActorRole, ProjectStatus, @@ -109,42 +114,22 @@ describe('Stats (e2e)', () => { it('cuenta las entregas pendientes de revisión de sus proyectos', async () => { const app = getApp(); - const admin = await adminSession(app); - const teacher = await userWithRole(app, UserRole.teacher); - const student = await userWithRole(app, UserRole.student); - const { projectId } = await createProjectWithProposer(app); - await assignProjectActor( + const { projectId, teacher, student } = + await createProjectWithTeacherAndStudent(app); + const reportId = await createTextReport( app, projectId, - admin.accessToken, - teacher.user.id, - ActorRole.teacher, + teacher.accessToken, ); - await assignProjectActor( + + await addReportTextContent( app, projectId, - admin.accessToken, - student.user.id, - ActorRole.student, + reportId, + student.accessToken, + 'Contenido', ); - - const created = await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports`) - .set(bearer(admin.accessToken)) - .send({ title: 'Informe', dueDate: futureIsoDate(), type: 'text' }) - .expect(201); - const reportId = (created.body as { id: number }).id; - - await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports/${reportId}/contents`) - .set(bearer(student.accessToken)) - .send({ kind: 'text', textContent: 'Contenido' }) - .expect(201); - - await request(app.getHttpServer()) - .post(`/projects/${projectId}/reports/${reportId}/submit`) - .set(bearer(student.accessToken)) - .expect(201); + await submitReport(app, projectId, reportId, student.accessToken); const response = await request(app.getHttpServer()) .get('/stats/kpis') diff --git a/hub-frontend/app/projects/[id]/project-reports-panel.tsx b/hub-frontend/app/projects/[id]/project-reports-panel.tsx index 4eb5ea7..0d69493 100644 --- a/hub-frontend/app/projects/[id]/project-reports-panel.tsx +++ b/hub-frontend/app/projects/[id]/project-reports-panel.tsx @@ -121,6 +121,17 @@ const REPORT_TYPE_OPTIONS: { { value: "file", label: "Archivo" }, ]; +function isReportConfigLocked( + report: ProjectReportItem | null, + pending: boolean, +): boolean { + return ( + pending || + (report !== null && + (report.status !== "pending" || report.hasContents)) + ); +} + function FormField({ htmlFor, label, @@ -590,7 +601,7 @@ export default function ProjectReportsPanel({ const reviewDialogTitle = reviewDecision === "accepted" ? "Aceptar entrega" : "No aceptar entrega"; const editingTextContent = contentEdit?.content.kind === "text"; - const configLocked = isPending || Boolean(editingReport?.contents.length); + const configLocked = isReportConfigLocked(editingReport, isPending); return ( diff --git a/hub-frontend/app/projects/[id]/reports/report-content.tsx b/hub-frontend/app/projects/[id]/reports/report-content.tsx index e67bf57..d6caf95 100644 --- a/hub-frontend/app/projects/[id]/reports/report-content.tsx +++ b/hub-frontend/app/projects/[id]/reports/report-content.tsx @@ -43,6 +43,7 @@ import { RiFileTextLine, RiImageLine, RiLinkM, + RiLockLine, RiPencilLine, RiVideoLine, } from "@remixicon/react"; @@ -521,6 +522,18 @@ export function ReportContents({ useState(null); const [deleteOpen, setDeleteOpen] = useState(false); + if (!report.canViewContents) { + return ( + + + + El contenido solo está visible para los estudiantes asignados mientras + la entrega esté pendiente o no aceptada. + + + ); + } + function confirmDelete() { const content = deleteTarget; diff --git a/hub-frontend/app/services/schemas.ts b/hub-frontend/app/services/schemas.ts index 77802fa..5cf75e8 100644 --- a/hub-frontend/app/services/schemas.ts +++ b/hub-frontend/app/services/schemas.ts @@ -165,6 +165,8 @@ export type ProjectReportItem = { email: string; } | null; milestones?: { id: number; title: string }[]; + canViewContents: boolean; + hasContents: boolean; contents: ProjectReportContentItem[]; };