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,