/* Student endpoints against a real Postgres (see student-access.db.test.ts): absence notices, payment reports and authorization by linked attendee. */ import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; import { Prisma, PrismaClient } from '@generated/prisma/client'; import { PrismaPg } from '@prisma/adapter-pg'; import { UnitOfWork } from '@/lib/prisma'; import type { FileStorage } from '@/lib/storage'; import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case'; import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case'; import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case'; import { GetStudentMe } from '@/modules/student-portal/features/me/use-case'; import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]); function memoryStorage() { const objects = new Map(); const storage: FileStorage = { put: async (key, body) => void objects.set(key, body), signedUrl: (key) => `https://storage.test/${key}?sig=1`, remove: async (key) => void objects.delete(key), }; return { objects, storage }; } describe.skipIf(!url)('student portal (real database)', () => { let db: PrismaClient; let unitOfWork: UnitOfWork; const ids = { user: `t-user-${suffix}`, group: `t-group-${suffix}`, yoga: `t-yoga-${suffix}`, personAna: `t-p-ana-${suffix}`, personBeto: `t-p-beto-${suffix}`, ana: `t-ana-${suffix}`, anaYoga: `t-ana-yoga-${suffix}`, betoYoga: `t-beto-yoga-${suffix}`, beto: `t-beto-${suffix}`, accountAna: `t-acc-ana-${suffix}`, accountBeto: `t-acc-beto-${suffix}`, }; // Wednesday 2026-10-28 12:00 in Buenos Aires: the group meets Mon/Wed/Fri at 18:00. const NOW = new Date('2026-10-28T15:00:00.000Z'); const WED_18 = '2026-10-28T21:00:00.000Z'; const FRI_18 = '2026-10-30T21:00:00.000Z'; const MON_18 = '2026-10-26T21:00:00.000Z'; beforeAll(async () => { db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); unitOfWork = new UnitOfWork(db); await db.user.create({ data: { id: ids.user, name: 'Caro', email: `${ids.user}@test.local`, country: 'AR', transferAlias: 'caro.natacion', transferHolder: 'Carolina Gómez' }, }); await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' }, }); await db.group.create({ data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' }, }); await db.person.createMany({ data: [ { id: ids.personAna, createdById: ids.user, fullName: 'Ana' }, { id: ids.personBeto, createdById: ids.user, fullName: 'Beto' }, ], }); // Ana and Beto are in both groups. await db.attendee.createMany({ data: [ { id: ids.ana, groupId: ids.group, personId: ids.personAna }, { id: ids.beto, groupId: ids.group, personId: ids.personBeto }, { id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna }, { id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto }, ], }); await db.studentAccount.create({ data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } }, }); await db.studentAccount.create({ data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } }, }); await db.payment.createMany({ data: [ { id: `t-p1-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z'), description: 'Septiembre' }, { id: `t-p2-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z'), description: 'Noviembre' }, { id: `t-p3-${suffix}`, groupId: ids.group, attendeeId: ids.beto, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z') }, ], }); }); afterAll(async () => { await db.user.deleteMany({ where: { id: ids.user } }); await db.$disconnect(); }); it('lista las clases de la semana en la hora del profe', async () => { const result = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana); if (!result.ok) throw new Error('classes failed'); expect(result.value.timeZone).toBe('America/Argentina/Buenos_Aires'); const starts = result.value.classes.map((item) => item.startsAt); expect(starts.slice(0, 3)).toEqual([new Date(MON_18).toISOString(), new Date(WED_18).toISOString(), new Date(FRI_18).toISOString()]); expect(result.value.classes[0]?.started).toBe(true); expect(result.value.classes[1]?.started).toBe(false); }); it('avisar falta la justifica y deshacer la revierte', async () => { const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW, releaseHours: 12 }); const result = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18, FRI_18], reason: 'health', message: 'Fiebre' }); if (!result.ok) throw new Error(result.error.detail); expect(result.value.notified).toHaveLength(2); // Idempotent: notifying again creates nothing. const again = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18] }); expect(again).toEqual({ ok: true, value: { notified: [] } }); const attendances = await db.attendance.findMany({ where: { attendeeId: ids.ana } }); expect(attendances.map((row) => row.status)).toEqual(['EXCUSED', 'EXCUSED']); const classes = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana); if (!classes.ok) throw new Error('classes failed'); const wednesday = classes.value.classes.find((item) => item.startsAt === new Date(WED_18).toISOString()); expect(wednesday?.notice).toMatchObject({ reason: 'health', message: 'Fiebre' }); const noticeId = result.value.notified[1]?.id as string; expect((await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountAna, noticeId)).ok).toBe(true); expect(await db.attendance.count({ where: { attendeeId: ids.ana } })).toBe(1); }); it('no se puede avisar una clase que ya empezó ni una que no existe', async () => { const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW }); const started = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [MON_18] }); expect(!started.ok && started.error.status).toBe(409); const invented = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: ['2026-10-29T21:00:00.000Z'] }); expect(!invented.ok && invented.error.status).toBe(400); }); it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => { const me = await new GetStudentMe({ db }).execute(ids.accountAna); if (!me.ok) throw new Error('me failed'); expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([ [ids.ana, 'Natación'], [ids.anaYoga, 'Yoga'], ]); // Her membership in the second group is reachable; Beto's in that group is not. expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true); const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga); expect(foreign.ok).toBe(false); if (!foreign.ok) expect(foreign.error.status).toBe(404); }); it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => { expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); const notify = await new NotifyStudentAbsences({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.ana, startsAt: [FRI_18] }); expect(!notify.ok && notify.error.status).toBe(404); const anaNotice = await db.absenceNotice.findFirstOrThrow({ where: { attendeeId: ids.ana, cancelledAt: null } }); const cancel = await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, anaNotice.id); expect(!cancel.ok && cancel.error.status).toBe(404); const { storage } = memoryStorage(); // Beto's account reporting Ana's fee, and Beto reporting Ana's fee id under his own attendee. const asAna = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG }, }); expect(!asAna.ok && asAna.error.status).toBe(404); const crossFee = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.beto, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG }, }); expect(!crossFee.ok && crossFee.error.status).toBe(400); }); it('informar pago guarda el comprobante privado y marca las cuotas como informadas', async () => { const { objects, storage } = memoryStorage(); const report = new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }); const result = await report.execute(ids.accountAna, { attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`, `t-p2-${suffix}`], file: { name: 'captura.png', bytes: PNG }, }); if (!result.ok) throw new Error(result.error.detail); expect(objects.size).toBe(1); const row = await db.reportedPayment.findUniqueOrThrow({ where: { id: result.value.id } }); expect(row).toMatchObject({ status: 'REPORTED', receiptMime: 'image/png', currency: 'ARS' }); expect(row.totalAmount.toNumber()).toBe(30000); expect([...objects.keys()][0]).toBe(row.receiptKey as string); const fees = await new GetStudentFees({ db, now: NOW }).execute(ids.accountAna, ids.ana); if (!fees.ok) throw new Error('fees failed'); expect(fees.value.fees.map((fee) => fee.status)).toEqual(['reported', 'reported']); expect(fees.value.transfer).toEqual({ alias: 'caro.natacion', holder: 'Carolina Gómez' }); // The same fee can't be in two unreviewed reports; the orphan file is removed. const twice = await report.execute(ids.accountAna, { attendeeId: ids.ana, paymentIds: [`t-p2-${suffix}`], file: { name: 'otra.png', bytes: PNG }, }); expect(!twice.ok && twice.error.status).toBe(409); expect(objects.size).toBe(1); }); it('valida el tipo real del archivo, no el nombre', async () => { const { storage } = memoryStorage(); const fake = new TextEncoder().encode(''); const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.beto, paymentIds: [`t-p3-${suffix}`], file: { name: 'comprobante.png', bytes: fake }, }); expect(!result.ok && result.error.status).toBe(400); }); });