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>
This commit is contained in:
Jose Selesan
2026-11-11 14:04:25 -03:00
parent 9383841513
commit 5b3a035dcf
17 changed files with 336 additions and 66 deletions

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { guardianSelect } from '@/modules/people/lib/guardians';
import { computeStudentAccess } from '../../lib/status';
type GetStudentAccessDeps = {
@@ -23,9 +24,14 @@ export class GetStudentAccess {
const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true, person: { select: guardianSelect } },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
// A kid with an adult in charge uses the adult's account (shared by siblings).
const ownerId = attendee.person.guardians[0]?.guardian.id ?? attendee.personId;
return ok(await computeStudentAccess(db, ownerId, this.deps.now ?? new Date()));
}
}

View File

@@ -1,10 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
import { contactPhone, guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
import { computeStudentAccess } from '../../lib/status';
@@ -44,30 +44,19 @@ export class InviteStudent {
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
// The account belongs to the adult in charge when the kid has one: it
// reaches all of their kids.
const guardian = primaryGuardian(attendee.person);
const owner = guardian
? { personId: guardian.id, fullName: guardian.fullName }
: { personId: attendee.personId, fullName: attendee.person.fullName };
const token = generateAccessToken();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const issued = await unitOfWork.executeResult(async (tx) => {
// One account per person: inviting from any of their groups reuses it.
const link = await tx.studentAccountPerson.findFirst({
where: { personId: attendee.personId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
const accountId =
link?.accountId
?? (
await tx.studentAccount.create({
data: {
name: attendee.person.fullName,
createdById: userId,
people: { create: { personId: attendee.personId } },
},
select: { id: true },
})
).id;
const accountId = await resolveAccount(tx, owner, userId);
await tx.studentAccessToken.updateMany({
where: { accountId, usedAt: null, revokedAt: null },
data: { revokedAt: now },
@@ -96,7 +85,7 @@ export class InviteStudent {
url: studentLinkUrl(token),
expiresAt: expiresAt.toISOString(),
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
access: await computeStudentAccess(db, attendee.personId, now),
access: await computeStudentAccess(db, owner.personId, now),
});
}
}
@@ -104,3 +93,52 @@ export class InviteStudent {
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
}
type AccountOwner = { personId: string; fullName: string };
/* One account per person: inviting from any of their groups (or, for an adult
in charge, from any of their kids) reuses it. Accounts made before kids
groups were linked to the kid: the oldest one of the adult's kids moves to
the adult, and the kids stop being linked one by one (they are reached
through `person_guardians`). */
async function resolveAccount(tx: Prisma.TransactionClient, owner: AccountOwner, userId: string): Promise<string> {
const kids = await tx.personGuardian.findMany({ where: { guardianId: owner.personId }, select: { childId: true } });
const kidIds = kids.map((kid) => kid.childId);
const own = await tx.studentAccountPerson.findFirst({
where: { personId: owner.personId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
const legacy =
own || kidIds.length === 0
? null
: await tx.studentAccountPerson.findFirst({
where: { personId: { in: kidIds } },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
let accountId: string;
if (own) {
accountId = own.accountId;
} else if (legacy) {
accountId = legacy.accountId;
await tx.studentAccount.update({
where: { id: accountId },
data: { name: owner.fullName, people: { create: { personId: owner.personId } } },
});
} else {
accountId = (
await tx.studentAccount.create({
data: { name: owner.fullName, createdById: userId, people: { create: { personId: owner.personId } } },
select: { id: true },
})
).id;
}
if (kidIds.length > 0) {
await tx.studentAccountPerson.deleteMany({ where: { personId: { in: kidIds } } });
}
return accountId;
}

View File

@@ -13,6 +13,7 @@ import { occurrencesBetween } from '@/modules/home/lib/scheduler';
import {
classAlreadyStartedProblem,
findLinkedAttendee,
linkedPersonWhere,
studentAttendeeNotFoundProblem,
teacherTimeZone,
} from '../../lib';
@@ -127,7 +128,7 @@ export class CancelStudentAbsence {
where: {
id: noticeId,
cancelledAt: null,
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
attendee: { status: { not: 'DROPPED' }, person: linkedPersonWhere(accountId) },
},
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
});

View File

@@ -1,4 +1,4 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
@@ -9,6 +9,13 @@ type GetStudentLinkInfoDeps = {
now?: Date;
};
const firstGroupSelect = {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
take: 1,
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
} satisfies Prisma.Person$attendeesArgs;
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
/* GET of the link: only reads, never consumes (WhatsApp previews and link
@@ -38,10 +45,12 @@ export class GetStudentLinkInfo {
select: {
person: {
select: {
attendees: {
attendees: firstGroupSelect,
// An adult in charge has no groups of their own: their kids' count.
children: {
orderBy: { createdAt: 'asc' },
take: 1,
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
select: { child: { select: { attendees: firstGroupSelect } } },
},
},
},
@@ -62,7 +71,9 @@ export class GetStudentLinkInfo {
return ok({ status: 'invalid' });
}
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
const person = row.account.people[0]?.person;
const group =
person?.attendees[0]?.group ?? person?.children[0]?.child.attendees[0]?.group ?? null;
return ok({
status: 'valid',
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',

View File

@@ -1,9 +1,44 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { unauthorizedProblem } from '@/http/problem-details';
import prisma from '@/lib/prisma';
const personGroupsSelect = {
fullName: true,
attendees: {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
} satisfies Prisma.PersonSelect;
type PersonGroups = Prisma.PersonGetPayload<{ select: typeof personGroupsSelect }>;
/* One entry per membership; a kid reached twice (linked and through the adult)
shows up once. */
function studentsOf(people: PersonGroups[]): StudentMe['students'] {
const seen = new Set<string>();
return people.flatMap((person) =>
person.attendees.flatMap((attendee) => {
if (seen.has(attendee.id)) return [];
seen.add(attendee.id);
return [
{
attendeeId: attendee.id,
fullName: person.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
},
];
}),
);
}
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
export class GetStudentMe {
@@ -20,21 +55,15 @@ export class GetStudentMe {
pendingRecoveryEmail: true,
welcomedAt: true,
_count: { select: { passkeys: true } },
// Linked people, and every group each of them is in.
// Linked people (and the kids of a linked adult in charge), and every
// group each of them is in.
people: {
orderBy: { createdAt: 'asc' },
select: {
person: {
select: {
fullName: true,
attendees: {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
...personGroupsSelect,
children: { orderBy: { createdAt: 'asc' }, select: { child: { select: personGroupsSelect } } },
},
},
},
@@ -52,15 +81,7 @@ export class GetStudentMe {
hasPasskey: account._count.passkeys > 0,
welcomed: account.welcomedAt !== null,
},
students: account.people.flatMap(({ person }) =>
person.attendees.map((attendee) => ({
attendeeId: attendee.id,
fullName: person.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
})),
),
students: studentsOf(account.people.flatMap(({ person }) => [person, ...person.children.map(({ child }) => child)])),
});
}
}

View File

@@ -2,17 +2,29 @@ import type { Prisma } from '@generated/prisma/client';
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
/* The people a student account reaches: the ones linked to it and the kids of
a linked adult in charge (kids groups). Kids are not linked one by one, so a
kid added later shows up without a new invitation. */
export function linkedPersonWhere(accountId: string): Prisma.PersonWhereInput {
return {
OR: [
{ studentAccounts: { some: { accountId } } },
{ guardians: { some: { guardian: { studentAccounts: { some: { accountId } } } } } },
],
};
}
/* The authorization rule of every student endpoint: an attendee (membership)
of a person linked to the session's account, with what the student screens
need from the group. The account is linked to the person, so every group
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
need from the group. The account is linked to the person (or to their adult
in charge), so every group they are in shows up. null for anything else (or DROPPED; PAUSED keeps
access): routes answer 404, the same as for an id that doesn't exist. */
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
return db.attendee.findFirst({
where: {
id: attendeeId,
status: { not: 'DROPPED' },
person: { studentAccounts: { some: { accountId } } },
person: linkedPersonWhere(accountId),
},
select: {
id: true,

View File

@@ -0,0 +1,140 @@
/* 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();
});
});