Files
gruperly/apps/backend/test/db/student-guardian.db.test.ts
Jose Selesan 5b3a035dcf feat(student-portal): student account belongs to the adult in charge
- Inviting a kid with an adult in charge links the account to the adult
  (a legacy account linked to the kid moves to the adult and is renamed).
- `linkedPersonWhere` lets the account reach the kids of a linked adult, so
  the adult sees and manages all their kids, including ones added later.
- /me, link info and access status follow the adult; siblings share state.
- Web: greeting uses the account holder, profile lists each kid's group, and
  the invitation sheet/message address the adult.
- DB tests for the adult account flow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:04:25 -03:00

141 lines
6.5 KiB
TypeScript

/* Kids groups against a real Postgres: the student account belongs to the
adult in charge and reaches all of their kids. Skipped unless DB_TESTS=1
(`bun run test:db`). Creates its own teacher/groups/people and deletes them. */
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 { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
import { findLinkedAttendee } from '@/modules/student-portal/lib/access';
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)('cuenta del adulto a cargo (real database)', () => {
let db: PrismaClient;
let unitOfWork: { executeResult: unknown };
const ids = {
user: `test-user-${suffix}`,
swim: `test-swim-${suffix}`,
art: `test-art-${suffix}`,
ana: `test-ana-${suffix}`,
juan: `test-juan-${suffix}`,
sofi: `test-sofi-${suffix}`,
tomi: `test-tomi-${suffix}`,
other: `test-other-${suffix}`,
juanSwim: `test-juan-swim-${suffix}`,
sofiArt: `test-sofi-art-${suffix}`,
tomiArt: `test-tomi-art-${suffix}`,
otherSwim: `test-other-swim-${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.swim, name: 'Natación', audience: 'KIDS', createdById: ids.user } });
await db.group.create({ data: { id: ids.art, name: 'Plástica', audience: 'KIDS', createdById: ids.user } });
await db.person.create({ data: { id: ids.ana, createdById: ids.user, fullName: 'Ana Pérez', phone: `11${suffix.slice(-8)}` } });
for (const [id, fullName] of [
[ids.juan, 'Juan Pérez'],
[ids.sofi, 'Sofi Pérez'],
] as const) {
await db.person.create({
data: { id, createdById: ids.user, fullName, guardians: { create: { guardianId: ids.ana } } },
});
}
await db.person.create({ data: { id: ids.other, createdById: ids.user, fullName: 'Otro Chico' } });
await db.attendee.create({ data: { id: ids.juanSwim, groupId: ids.swim, personId: ids.juan } });
await db.attendee.create({ data: { id: ids.sofiArt, groupId: ids.art, personId: ids.sofi } });
await db.attendee.create({ data: { id: ids.otherSwim, groupId: ids.swim, personId: ids.other } });
// A legacy account linked to the kid (before kids groups).
await db.studentAccount.create({
data: { name: 'Juan Pérez', createdById: ids.user, people: { create: { personId: ids.juan } } },
});
});
afterAll(async () => {
await db.studentAccount.deleteMany({ where: { createdById: ids.user } });
await db.user.deleteMany({ where: { id: ids.user } });
await db.$disconnect();
});
const invite = (groupId: string, attendeeId: string) =>
new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(groupId, attendeeId, ids.user);
const accountOf = async (personId: string) =>
(await db.studentAccountPerson.findFirst({ where: { personId } }))?.accountId ?? null;
it('invitar a un chico pasa su cuenta vieja al adulto', async () => {
const legacy = await accountOf(ids.juan);
const result = await invite(ids.swim, ids.juanSwim);
if (!result.ok) throw new Error('invite failed');
expect(await accountOf(ids.ana)).toBe(legacy);
expect(await accountOf(ids.juan)).toBeNull();
const account = await db.studentAccount.findUniqueOrThrow({ where: { id: legacy as string } });
expect(account.name).toBe('Ana Pérez');
const token = result.value.url.split('/i/')[1] as string;
expect(await new GetStudentLinkInfo({ db }).execute(token)).toMatchObject({
ok: true,
value: { status: 'valid', name: 'Ana Pérez', groupName: 'Natación' },
});
});
it('invitar a un hermano reutiliza la cuenta del adulto', async () => {
const accountId = await accountOf(ids.ana);
const result = await invite(ids.art, ids.sofiArt);
if (!result.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.ana } })).toBe(1);
expect(await accountOf(ids.ana)).toBe(accountId);
const juan = await new GetStudentAccess({ db }).execute(ids.swim, ids.juanSwim, ids.user);
const sofi = await new GetStudentAccess({ db }).execute(ids.art, ids.sofiArt, ids.user);
expect(juan).toMatchObject({ ok: true, value: { status: 'invited' } });
expect(sofi).toEqual(juan);
});
it('la cuenta del adulto ve a todos sus chicos, también uno nuevo, y a nadie más', async () => {
const accountId = (await accountOf(ids.ana)) as string;
// A kid added after the invitation shows up without reinviting.
await db.person.create({
data: { id: ids.tomi, createdById: ids.user, fullName: 'Tomi Pérez', guardians: { create: { guardianId: ids.ana } } },
});
await db.attendee.create({ data: { id: ids.tomiArt, groupId: ids.art, personId: ids.tomi } });
const me = await new GetStudentMe({ db }).execute(accountId);
if (!me.ok) throw new Error('me failed');
expect(me.value.account.name).toBe('Ana Pérez');
expect(me.value.students.map((s) => [s.fullName, s.groupName])).toEqual([
['Juan Pérez', 'Natación'],
['Sofi Pérez', 'Plástica'],
['Tomi Pérez', 'Plástica'],
]);
for (const attendeeId of [ids.juanSwim, ids.sofiArt, ids.tomiArt]) {
expect(await findLinkedAttendee(db, accountId, attendeeId)).not.toBeNull();
}
expect(await findLinkedAttendee(db, accountId, ids.otherSwim)).toBeNull();
});
});