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,144 @@
/* Teacher review of reported payments against a real Postgres (see
student-access.db.test.ts): confirm/reject/undo, the overdue alert and access
between teachers. */
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 { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case';
import { ReportedPayments } from '@/modules/payments/features/reported/use-case';
import { sendReviewNotification } from '@/modules/payments/lib/review-notifications';
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]);
const storage: FileStorage = {
put: async () => {},
signedUrl: (key, ttl) => `https://storage.test/${key}?ttl=${ttl}`,
remove: async () => {},
};
describe.skipIf(!url)('payment review (real database)', () => {
let db: PrismaClient;
let unitOfWork: UnitOfWork;
const notified: string[] = [];
const ids = {
teacher: `r-teacher-${suffix}`,
other: `r-other-${suffix}`,
group: `r-group-${suffix}`,
ana: `r-ana-${suffix}`,
account: `r-acc-${suffix}`,
fee: `r-fee-${suffix}`,
};
const NOW = new Date('2026-10-28T15:00:00.000Z');
const reviews = (now = NOW) =>
new ReportedPayments({ db, unitOfWork, storage, now, notify: (id) => void notified.push(id) });
const overdueFor = async () => {
const overview = await new GetAttentionOverview({ db: db as never, now: NOW }).execute(ids.teacher);
if (!overview.ok) throw new Error('overview failed');
const member = overview.value.groups.flatMap((group) => group.members).find((item) => item.attendeeId === ids.ana);
return { alerts: member?.alerts.map((alert) => alert.tipo) ?? [], overdue: member?.overduePayments.length ?? 0 };
};
const report = async () => {
const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.account, {
attendeeId: ids.ana,
paymentIds: [ids.fee],
file: { name: 'captura.png', bytes: PNG },
});
if (!result.ok) throw new Error(result.error.detail);
return result.value.id;
};
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
unitOfWork = new UnitOfWork(db);
await db.user.createMany({
data: [
{ id: ids.teacher, name: 'Caro', email: `${ids.teacher}@test.local`, country: 'AR' },
{ id: ids.other, name: 'Otro', email: `${ids.other}@test.local`, country: 'AR' },
],
});
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } });
await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } });
await db.studentAccount.create({
data: {
id: ids.account,
name: 'Ana',
createdById: ids.teacher,
recoveryEmail: 'ana@test.local',
recoveryEmailVerifiedAt: NOW,
attendees: { create: { attendeeId: ids.ana } },
},
});
await db.payment.create({
data: { id: ids.fee, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z') },
});
});
afterAll(async () => {
await db.user.deleteMany({ where: { id: { in: [ids.teacher, ids.other] } } });
await db.$disconnect();
});
it('un pago informado saca la cuota de la alerta y otro profe no lo ve', async () => {
expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 });
const reportId = await report();
expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 });
const mine = await reviews().list(ids.teacher);
if (!mine.ok) throw new Error('list failed');
expect(mine.value.data.map((item) => item.id)).toEqual([reportId]);
expect(mine.value.data[0]?.receipt.thumbnailUrl).toContain('ttl=300');
const theirs = await reviews().list(ids.other);
expect(theirs).toEqual({ ok: true, value: { data: [] } });
const foreign = await reviews().confirm(ids.other, reportId);
expect(!foreign.ok && foreign.error.status).toBe(404);
const foreignReceipt = await reviews().receiptUrl(ids.other, reportId);
expect(foreignReceipt.ok).toBe(false);
});
it('rechazar devuelve la alerta y deshacer la vuelve a sacar', async () => {
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
const rejected = await reviews().reject(ids.teacher, reportId, 'No se ve el monto');
expect(rejected.ok && rejected.value.status).toBe('rejected');
expect(notified).toContain(reportId);
expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 });
const again = await reviews().confirm(ids.teacher, reportId);
expect(!again.ok && again.error.status).toBe(409);
const undone = await reviews().undo(ids.teacher, reportId);
expect(undone.ok && undone.value.status).toBe('reported');
expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 });
});
it('confirmar marca las cuotas como pagadas; deshacer las vuelve a vencidas', async () => {
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
const confirmed = await reviews().confirm(ids.teacher, reportId);
expect(confirmed.ok && confirmed.value.status).toBe('confirmed');
expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'PAID', paidAt: NOW });
// Email only if the review still stands.
const sent: string[] = [];
const email = { sendStudentPaymentReviewed: async (data: { email: string }) => void sent.push(data.email) };
expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(true);
expect(sent).toEqual(['ana@test.local']);
const undone = await reviews().undo(ids.teacher, reportId);
expect(undone.ok).toBe(true);
expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'OVERDUE', paidAt: null });
expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(false);
});
it('deshacer vence a los pocos minutos', async () => {
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
expect((await reviews().confirm(ids.teacher, reportId)).ok).toBe(true);
const late = await reviews(new Date(NOW.getTime() + 11 * 60 * 1000)).undo(ids.teacher, reportId);
expect(!late.ok && late.error.status).toBe(409);
});
});

View File

@@ -0,0 +1,149 @@
/* Against a real Postgres: the single-use guarantee lives in the database
(conditional UPDATE under concurrency), so a mock can't prove it. Skipped
unless DB_TESTS=1 (`bun run test:db`), which uses DATABASE_URL from .env.
Creates its own teacher/group/attendee and deletes them at the end. */
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import { PrismaClient } from '@generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case';
import { InviteStudent } from '@/modules/student-access/features/invite/use-case';
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { hashToken } from '@/modules/student-portal/lib/tokens';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
describe.skipIf(!url)('student access (real database)', () => {
let db: PrismaClient;
// Same contract as UnitOfWork.executeResult, built on this file's own client
// (other test files mock '@/lib/prisma').
let unitOfWork: { executeResult: unknown };
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` };
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
unitOfWork = {
executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => {
const rollback = Symbol('rollback');
try {
return await db.$transaction(async (tx) => {
const result = await callback(tx);
if (!result.ok) throw { [rollback]: result };
return result;
});
} catch (error) {
if (error && typeof error === 'object' && rollback in error) {
return (error as Record<symbol, unknown>)[rollback];
}
throw error;
}
}) as never,
};
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } });
});
afterAll(async () => {
await db.user.deleteMany({ where: { id: ids.user } });
await db.$disconnect();
});
const invite = (now = new Date()) =>
new InviteStudent({ db, unitOfWork: unitOfWork as never, now }).execute(ids.group, ids.attendee, ids.user);
const tokenOf = (link: string) => link.split('/i/')[1] as string;
const consume = (token: string, now = new Date()) =>
new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now }).execute({
token,
ip: '203.0.113.7',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1',
});
it('guarda solo el hash del token', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
expect(token).toHaveLength(43);
expect(await db.studentAccessToken.count({ where: { tokenHash: token } })).toBe(0);
expect(await db.studentAccessToken.count({ where: { tokenHash: hashToken(token) } })).toBe(1);
});
it('el GET no consume el link', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
for (let i = 0; i < 3; i++) {
const info = await new GetStudentLinkInfo({ db }).execute(token);
expect(info).toMatchObject({ ok: true, value: { status: 'valid', name: 'Ana Pérez', teacherName: 'Profe Test', groupName: 'Natación' } });
}
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
expect(row.usedAt).toBeNull();
});
it('bajo concurrencia, solo un dispositivo consume el link', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
const attempts = await Promise.all(Array.from({ length: 10 }, () => consume(token)));
const winners = attempts.filter((attempt) => attempt.ok);
const losers = attempts.filter((attempt) => !attempt.ok);
expect(winners).toHaveLength(1);
expect(losers).toHaveLength(9);
for (const loser of losers) {
if (!loser.ok) expect(loser.error.status).toBe(410);
}
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
expect(sessions).toHaveLength(1);
expect(sessions[0]?.device).toBe('iPhone · Safari');
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
expect(row.usedIp).toBe('203.0.113.7');
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
});
it('un link vencido no sirve', async () => {
const past = new Date(Date.now() - 73 * 60 * 60 * 1000);
const result = await invite(past);
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
const attempt = await consume(token);
expect(attempt.ok).toBe(false);
});
it('reinvitar revoca las sesiones y los links anteriores', async () => {
const first = await invite();
if (!first.ok) throw new Error('invite failed');
const consumed = await consume(tokenOf(first.value.url));
expect(consumed.ok).toBe(true);
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
await db.studentPasskey.create({
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
});
const pendingOld = await invite();
// A lost phone must not keep a way in: passkeys go too.
expect(await db.studentPasskey.count({ where: { accountId: linked.accountId } })).toBe(0);
if (!pendingOld.ok) throw new Error('invite failed');
const access = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(access).toMatchObject({ ok: true, value: { status: 'invited', devices: [] } });
// Both previous links are dead: the consumed one and the pending one.
expect((await consume(tokenOf(first.value.url))).ok).toBe(false);
const reinvite = await invite();
if (!reinvite.ok) throw new Error('invite failed');
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
});
});

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);
});
});

View File

@@ -214,7 +214,7 @@ describe('GetHomeSummary', () => {
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
]);
// 10:23 in Buenos Aires, but the default zone is CDMX → 07:23 CDMX (not started yet).
// 10:23 in Buenos Aires, the default zone: the 10:00 class already started.
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
const result = await useCase.execute(userId);
@@ -222,8 +222,8 @@ describe('GetHomeSummary', () => {
if (!result.ok) return;
expect(result.value.nextClass).toMatchObject({
occurrenceAt: '2026-09-23T16:00:00.000Z',
isNow: false,
occurrenceAt: '2026-09-23T13:00:00.000Z',
isNow: true,
});
});

View File

@@ -0,0 +1,394 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { Hono } from 'hono';
import { isPublicApiRequest } from '@/http/session-auth';
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { StudentPasskeys } from '@/modules/student-portal/features/passkeys/use-case';
import {
RECOVERY_LIMIT_PER_EMAIL,
RECOVERY_LIMIT_PER_IP,
RequestRecoveryLink,
} from '@/modules/student-portal/features/request-recovery/use-case';
import { describeDevice } from '@/modules/student-portal/lib/device';
import { hashToken } from '@/modules/student-portal/lib/tokens';
import { requireStudentSession, studentOriginGuard } from '@/modules/student-portal/middleware';
const NOW = new Date('2026-10-27T15:00:00.000Z');
const WEB = process.env.WEB_URL ?? 'http://localhost:6173';
/* In-memory rate limit table: enough to count hits by key and window. */
function fakeRateLimit() {
let rows: { key: string; createdAt: Date }[] = [];
return {
deleteMany: mock(async ({ where }: { where: { key: string; createdAt: { lt: Date } } }) => {
rows = rows.filter((row) => !(row.key === where.key && row.createdAt < where.createdAt.lt));
return { count: 0 };
}),
count: mock(async ({ where }: { where: { key: string; createdAt: { gte: Date } } }) =>
rows.filter((row) => row.key === where.key && row.createdAt >= where.createdAt.gte).length),
create: mock(async ({ data }: { data: { key: string; createdAt: Date } }) => {
rows.push(data);
return data;
}),
};
}
describe('link del alumno', () => {
it('un token mal formado es inválido sin tocar la base', async () => {
const db = { studentAccessToken: { findUnique: mock() } };
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute('abc');
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
expect(db.studentAccessToken.findUnique).not.toHaveBeenCalled();
});
it('usado, revocado o vencido responde lo mismo, sin datos del dueño', async () => {
const token = 'a'.repeat(43);
const base = {
kind: 'INVITATION',
usedAt: null,
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000),
account: { name: 'Ana', attendees: [] },
};
for (const row of [
{ ...base, usedAt: NOW },
{ ...base, revokedAt: NOW },
{ ...base, expiresAt: NOW },
{ ...base, kind: 'EMAIL_CONFIRMATION' },
null,
]) {
const db = { studentAccessToken: { findUnique: mock(async () => row) } };
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
}
});
it('el GET solo lee: busca por hash y nunca actualiza', async () => {
const token = 'b'.repeat(43);
const db = {
studentAccessToken: {
findUnique: mock(async () => ({
kind: 'INVITATION',
usedAt: null,
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000),
account: {
name: 'Ana',
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
},
})),
updateMany: mock(),
},
};
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
expect(result).toEqual({
ok: true,
value: { status: 'valid', kind: 'invitation', name: 'Ana', teacherName: 'Caro', groupName: 'Natación' },
});
expect(db.studentAccessToken.findUnique.mock.calls[0]?.[0]).toMatchObject({ where: { tokenHash: hashToken(token) } });
expect(db.studentAccessToken.updateMany).not.toHaveBeenCalled();
});
it('el POST consume con un update condicional y reemplaza la sesión del dispositivo', async () => {
const tx = {
studentAccessToken: {
updateMany: mock(async () => ({ count: 1 })),
findUniqueOrThrow: mock(async () => ({ accountId: 'acc-1', account: { welcomedAt: null } })),
},
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 1 })) },
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
token: 'tok',
ip: '1.2.3.4',
userAgent: 'UA',
currentSessionToken: 'old-session',
});
expect(result.ok && result.value.firstLogin).toBe(true);
expect(tx.studentAccessToken.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: { tokenHash: hashToken('tok'), usedAt: null, revokedAt: null, expiresAt: { gt: NOW } },
});
expect(tx.studentSession.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: { tokenHash: hashToken('old-session') },
});
// A new identifier: the stored hash is not the old session's.
const created = (tx.studentSession.create.mock.calls[0] as unknown as [{ data: { tokenHash: string } }])[0];
expect(created.data.tokenHash).not.toBe(hashToken('old-session'));
});
it('si otro dispositivo ganó, responde 410 y no crea sesión', async () => {
const tx = {
studentAccessToken: { updateMany: mock(async () => ({ count: 0 })), findUniqueOrThrow: mock() },
studentSession: { create: mock() },
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
token: 'tok',
ip: null,
userAgent: null,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.status).toBe(410);
expect(tx.studentSession.create).not.toHaveBeenCalled();
});
});
describe('pedir un link al mail', () => {
function setup(accounts: { id: string; name: string }[]) {
const db = {
rateLimitEvent: fakeRateLimit(),
studentAccount: { findMany: mock(async () => accounts) },
studentAccessToken: { create: mock(async () => ({})) },
};
const email = { sendStudentRecoveryLinks: mock(async () => {}) };
const tasks: Promise<void>[] = [];
const useCase = new RequestRecoveryLink({
db: db as never,
email,
now: NOW,
defer: (task) => tasks.push(task()),
});
return { db, email, useCase, flush: () => Promise.all(tasks) };
}
it('responde idéntico exista o no el mail', async () => {
const known = setup([{ id: 'acc-1', name: 'Ana' }]);
const unknown = setup([]);
const a = await known.useCase.execute({ email: 'ana@mail.com', ip: '1.1.1.1' });
const b = await unknown.useCase.execute({ email: 'nadie@mail.com', ip: '1.1.1.1' });
expect(a).toEqual(b);
await Promise.all([known.flush(), unknown.flush()]);
expect(known.email.sendStudentRecoveryLinks).toHaveBeenCalledTimes(1);
expect(unknown.email.sendStudentRecoveryLinks).not.toHaveBeenCalled();
// Only verified emails recover.
expect(known.db.studentAccount.findMany.mock.calls[0]?.[0]).toMatchObject({
where: { recoveryEmail: 'ana@mail.com', recoveryEmailVerifiedAt: { not: null } },
});
const sent = (known.email.sendStudentRecoveryLinks.mock.calls[0] as unknown as [{ links: { url: string }[] }])[0];
expect(sent.links[0]?.url).toStartWith(`${WEB}/i/`);
});
it(`limita a ${RECOVERY_LIMIT_PER_EMAIL} pedidos por mail, exista o no`, async () => {
for (const accounts of [[{ id: 'acc-1', name: 'Ana' }], []]) {
const { useCase } = setup(accounts);
for (let i = 0; i < RECOVERY_LIMIT_PER_EMAIL; i++) {
expect((await useCase.execute({ email: 'x@mail.com', ip: `10.0.0.${i}` })).ok).toBe(true);
}
const blocked = await useCase.execute({ email: 'x@mail.com', ip: '10.0.0.99' });
expect(blocked.ok).toBe(false);
if (!blocked.ok) expect(blocked.error.status).toBe(429);
}
});
it(`limita a ${RECOVERY_LIMIT_PER_IP} pedidos por IP`, async () => {
const { useCase } = setup([]);
for (let i = 0; i < RECOVERY_LIMIT_PER_IP; i++) {
expect((await useCase.execute({ email: `u${i}@mail.com`, ip: '9.9.9.9' })).ok).toBe(true);
}
expect((await useCase.execute({ email: 'otro@mail.com', ip: '9.9.9.9' })).ok).toBe(false);
});
});
describe('passkeys', () => {
function setup() {
const challenges = new Map<string, Record<string, unknown>>();
let nextId = 0;
const db = {
rateLimitEvent: fakeRateLimit(),
studentAccount: {
findUniqueOrThrow: mock(async () => ({ name: 'Ana', passkeys: [] })),
},
studentWebauthnChallenge: {
deleteMany: mock(async ({ where }: { where: { id?: string } }) => {
if (!where.id) return { count: 0 };
return { count: challenges.delete(where.id) ? 1 : 0 };
}),
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
const id = `ch-${nextId++}`;
challenges.set(id, { id, ...data });
return { id };
}),
findUnique: mock(async ({ where }: { where: { id: string } }) => challenges.get(where.id) ?? null),
},
studentPasskey: {
upsert: mock(async () => ({})),
findUnique: mock(async () => ({
id: 'pk-1',
accountId: 'acc-1',
credentialId: 'cred-1',
publicKey: new Uint8Array([1, 2, 3]),
counter: 4,
transports: ['internal'],
})),
update: mock(async () => ({})),
deleteMany: mock(async () => ({ count: 1 })),
},
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 0 })) },
};
const webauthn = {
generateRegistrationOptions: mock(async () => ({ challenge: 'reg-challenge' })),
verifyRegistrationResponse: mock(async () => ({
verified: true,
registrationInfo: { credential: { id: 'cred-1', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'] } },
})),
generateAuthenticationOptions: mock(async () => ({ challenge: 'login-challenge' })),
verifyAuthenticationResponse: mock(async () => ({ verified: true, authenticationInfo: { newCounter: 5 } })),
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(db) };
const passkeys = new StudentPasskeys({
db: db as never,
webauthn: webauthn as never,
unitOfWork: unitOfWork as never,
now: NOW,
});
return { db, webauthn, passkeys };
}
it('registra una passkey con preferred en residentKey y userVerification', async () => {
const { db, webauthn, passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
expect(webauthn.generateRegistrationOptions.mock.calls[0]?.[0]).toMatchObject({
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
});
const iPhone = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1';
const result = await passkeys.verifyRegistration('acc-1', { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, iPhone);
expect(result.ok).toBe(true);
expect(webauthn.verifyRegistrationResponse.mock.calls[0]?.[0]).toMatchObject({ expectedChallenge: 'reg-challenge' });
expect(db.studentPasskey.upsert.mock.calls[0]?.[0]).toMatchObject({
create: { accountId: 'acc-1', credentialId: 'cred-1', device: 'iPhone · Safari' },
});
});
it('el challenge sirve una sola vez y solo para su cuenta', async () => {
const { passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
const input = { challengeId: options.value.challengeId, response: { id: 'cred-1' } };
expect((await passkeys.verifyRegistration('acc-2', input, null)).ok).toBe(false);
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(true);
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(false);
});
it('el login con passkey crea una sesión nueva y actualiza el contador', async () => {
const { db, passkeys } = setup();
const options = await passkeys.loginOptions('1.1.1.1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(true);
expect(db.studentPasskey.update.mock.calls[0]?.[0]).toMatchObject({ data: { counter: 5 } });
expect(db.studentSession.create.mock.calls[0]?.[0]).toMatchObject({ data: { accountId: 'acc-1' } });
});
it('un challenge de registro no sirve para login', async () => {
const { passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(false);
});
it('una firma inválida no inicia sesión', async () => {
const { db, webauthn, passkeys } = setup();
webauthn.verifyAuthenticationResponse.mockImplementationOnce(async () => {
throw new Error('bad signature');
});
const options = await passkeys.loginOptions('1.1.1.1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(false);
expect(db.studentSession.create).not.toHaveBeenCalled();
});
});
describe('separación de roles y CSRF', () => {
const session = (overrides: Record<string, unknown> = {}) => ({
id: 'ses-1',
accountId: 'acc-1',
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000 * 60 * 60 * 24),
lastUsedAt: NOW,
...overrides,
});
let db: { studentSession: { findUnique: ReturnType<typeof mock>; update: ReturnType<typeof mock> } };
function app() {
const hono = new Hono();
hono.use('*', studentOriginGuard);
hono.get('/me', requireStudentSession({ db: db as never, now: () => NOW }), (c) => c.json(c.get('student')));
hono.post('/action', (c) => c.json({ ok: true }));
return hono;
}
beforeEach(() => {
db = { studentSession: { findUnique: mock(async () => session()), update: mock(async () => ({})) } };
});
it('las rutas del alumno quedan fuera del middleware del profe, y las del profe no', () => {
expect(isPublicApiRequest('GET', '/api/v1/student-portal/me')).toBe(true);
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/students/status')).toBe(false);
});
it('la cookie de sesión del profe no sirve en las rutas del alumno', async () => {
const res = await app().request('/me', {
headers: { Cookie: 'better-auth.session_token=teacher-token' },
});
expect(res.status).toBe(401);
expect(db.studentSession.findUnique).not.toHaveBeenCalled();
});
it('con la cookie del alumno setea su cuenta', async () => {
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ accountId: 'acc-1', sessionId: 'ses-1' });
expect(db.studentSession.findUnique.mock.calls[0]?.[0]).toEqual({ where: { tokenHash: hashToken('student-token') } });
});
it('una sesión revocada o vencida no entra', async () => {
for (const row of [session({ revokedAt: NOW }), session({ expiresAt: NOW })]) {
db.studentSession.findUnique.mockImplementationOnce(async () => row);
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(401);
}
});
it('la sesión se desliza: con más de una hora sin uso se renueva por 90 días', async () => {
db.studentSession.findUnique.mockImplementationOnce(async () =>
session({ lastUsedAt: new Date(NOW.getTime() - 2 * 60 * 60 * 1000) }));
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(200);
expect(db.studentSession.update.mock.calls[0]?.[0]).toMatchObject({
data: { lastUsedAt: NOW, expiresAt: new Date(NOW.getTime() + 90 * 24 * 60 * 60 * 1000) },
});
expect(res.headers.get('Set-Cookie')).toContain('HttpOnly');
expect(res.headers.get('Set-Cookie')).toContain('SameSite=Lax');
});
it('un POST sin Origin o de otro origen se rechaza', async () => {
expect((await app().request('/action', { method: 'POST' })).status).toBe(403);
expect((await app().request('/action', { method: 'POST', headers: { Origin: 'https://evil.test' } })).status).toBe(403);
expect((await app().request('/action', { method: 'POST', headers: { Origin: WEB } })).status).toBe(200);
});
});
describe('dispositivo legible', () => {
it('describe navegador y plataforma', () => {
expect(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/130.0 Mobile/15E148 Safari/604.1')).toBe('iPhone · Chrome');
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36')).toBe('Android · Chrome');
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/26.0 Chrome/122.0 Mobile Safari/537.36')).toBe('Android · Samsung Internet');
expect(describeDevice(null)).toBe('Dispositivo desconocido');
});
});

View File

@@ -0,0 +1,67 @@
import { describe, expect, it } from 'bun:test';
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
import type { FileStorage } from '@/lib/storage';
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
const pad = (head: number[]) => new Uint8Array([...head, ...new Array(16).fill(0)]);
const ascii = (text: string) => [...text].map((char) => char.charCodeAt(0));
describe('tipo real del comprobante (magic bytes)', () => {
it('reconoce JPG, PNG, WEBP, HEIC y PDF', () => {
expect(detectReceiptType(pad([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg');
expect(detectReceiptType(pad([0x89, ...ascii('PNG'), 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png');
expect(detectReceiptType(pad([...ascii('RIFF'), 0, 0, 0, 0, ...ascii('WEBP')]))).toBe('image/webp');
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypheic')]))).toBe('image/heic');
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypmif1')]))).toBe('image/heic');
expect(detectReceiptType(pad(ascii('%PDF-1.7')))).toBe('application/pdf');
});
it('rechaza lo demás aunque se llame .png', () => {
expect(detectReceiptType(pad(ascii('<svg xmlns=')))).toBeNull();
expect(detectReceiptType(pad(ascii('GIF89a')))).toBeNull();
expect(detectReceiptType(pad([0x50, 0x4b, 0x03, 0x04]))).toBeNull(); // zip/docx
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypmp42')]))).toBeNull(); // video
expect(detectReceiptType(new Uint8Array([0xff, 0xd8]))).toBeNull();
});
it('valida tamaño y tipo antes de tocar el storage', async () => {
const puts: string[] = [];
const storage: FileStorage = { put: async (key) => void puts.push(key), signedUrl: () => '', remove: async () => {} };
const attendee = {
id: 'a1',
groupId: 'g1',
group: { createdById: 't1', owner: { country: 'AR' } },
};
const db = { attendee: { findFirst: async () => attendee }, payment: { findMany: async () => [] } };
const useCase = new ReportStudentPayment({ db: db as never, storage });
const big = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: new Uint8Array(RECEIPT_MAX_BYTES + 1) } });
expect(!big.ok && big.error.errors).toEqual({ file: ['too_large'] });
const html = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.png', bytes: pad(ascii('<html>')) } });
expect(!html.ok && html.error.errors).toEqual({ file: ['invalid_type'] });
expect(puts).toEqual([]);
const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
expect(!unavailable.ok && unavailable.error.status).toBe(503);
});
});
describe('clases de un rango en la hora del profe', () => {
const TZ = 'America/Argentina/Buenos_Aires';
it('lista lunes y miércoles a las 18 de una semana', () => {
const from = startOfWeekInTimeZone(new Date('2026-10-28T15:00:00Z'), TZ);
expect(from.toISOString()).toBe('2026-10-26T03:00:00.000Z');
const to = new Date(from.getTime() + 7 * 24 * 60 * 60 * 1000);
const starts = occurrencesBetween({ days: ['MONDAY', 'WEDNESDAY'], time: '18:00', from, to, timeZone: TZ });
expect(starts.map((date) => date.toISOString())).toEqual(['2026-10-26T21:00:00.000Z', '2026-10-28T21:00:00.000Z']);
});
it('sin horario no hay clases', () => {
const now = new Date();
expect(occurrencesBetween({ days: ['MONDAY'], time: null, from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]);
expect(occurrencesBetween({ days: [], time: '18:00', from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]);
});
});