Files
gruperly/apps/backend/test/db/student-access.db.test.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

177 lines
8.5 KiB
TypeScript

/* 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}`,
group2: `test-group2-${suffix}`,
person: `test-person-${suffix}`,
attendee: `test-att-${suffix}`,
attendee2: `test-att2-${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.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } });
// One person in two groups of the teacher.
await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } });
await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } });
});
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.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
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.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
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.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
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' } });
});
it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => {
const fromFirst = await invite();
if (!fromFirst.ok) throw new Error('invite failed');
const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(
ids.group2,
ids.attendee2,
ids.user,
);
if (!fromSecond.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1);
// Same state from both groups: it is the person's access.
const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user);
expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } });
});
});