feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)

- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo
  atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys
  opcionales (SimpleWebAuthn) y mail de recuperación con rate limit.
- Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta,
  pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil.
- Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar),
  "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de
  grupo y datos para transferir en Ajustes.
- "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas.
- Zona horaria por defecto: Buenos Aires.
- Migración add_student_access, tests contra Postgres real (test:db) y docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-28 15:39:09 -03:00
parent b99bc4d519
commit 060a4f09e4
146 changed files with 7994 additions and 32 deletions

View File

@@ -0,0 +1,176 @@
/* 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 { 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<string, Uint8Array>();
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}`,
ana: `t-ana-${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.attendee.createMany({
data: [
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
],
});
await db.studentAccount.create({
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
});
await db.studentAccount.create({
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
});
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('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('<html><script>alert(1)</script></html>');
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);
});
});