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:
144
apps/backend/test/db/payment-review.db.test.ts
Normal file
144
apps/backend/test/db/payment-review.db.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
149
apps/backend/test/db/student-access.db.test.ts
Normal file
149
apps/backend/test/db/student-access.db.test.ts
Normal 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' } });
|
||||
});
|
||||
});
|
||||
176
apps/backend/test/db/student-portal.db.test.ts
Normal file
176
apps/backend/test/db/student-portal.db.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user