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, primaryGuardian } from '@/modules/people/lib/people'; import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; import { computeStudentAccess } from '../../lib/status'; type InviteStudentDeps = { db?: Pick; unitOfWork?: Pick; now?: Date; }; /* "Invitar" / "Reinvitar": reinviting restarts the access. It revokes every pending link and every session and removes the passkeys (a lost phone must not keep a way in), then issues a fresh 72 h single-use link. The welcome screen shows again on the next sign-in so the student can add a passkey back. The raw token only leaves here, inside the URL: the database keeps its hash. */ export class InviteStudent { constructor(private readonly deps: InviteStudentDeps = {}) {} async execute( groupId: string, attendeeId: string, userId: string, ): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const access = await findGroupForUser(db, groupId, userId); if (!access.ok) return access; const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true, personId: true, person: { select: { fullName: true, phone: true, ...guardianSelect } }, group: { select: { owner: { select: { country: true } } } }, }, }); 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) => { const accountId = await resolveAccount(tx, owner, userId); await tx.studentAccessToken.updateMany({ where: { accountId, usedAt: null, revokedAt: null }, data: { revokedAt: now }, }); await tx.studentSession.updateMany({ where: { accountId, revokedAt: null }, data: { revokedAt: now }, }); await tx.studentPasskey.deleteMany({ where: { accountId } }); await tx.studentAccount.update({ where: { id: accountId }, data: { welcomedAt: null } }); await tx.studentAccessToken.create({ data: { accountId, kind: 'INVITATION', tokenHash: hashToken(token), expiresAt, createdById: userId, createdAt: now, }, }); return ok(accountId); }); if (!issued.ok) return issued; return ok({ url: studentLinkUrl(token), expiresAt: expiresAt.toISOString(), whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country), access: await computeStudentAccess(db, owner.personId, now), }); } } 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 { 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; }