import type { 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 { 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, fullName: true, phone: true, guardianPhone: true, group: { select: { owner: { select: { country: true } } } }, }, }); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); 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 link = await tx.studentAccountAttendee.findFirst({ where: { attendeeId }, orderBy: { createdAt: 'asc' }, select: { accountId: true }, }); const accountId = link?.accountId ?? ( await tx.studentAccount.create({ data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } }, select: { id: true }, }) ).id; 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(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country), access: await computeStudentAccess(db, attendeeId, now), }); } } function toWhatsappPhone(phone: string | null, country: string | null): string | null { return phone ? toWhatsappE164(phone, country as CountryCode | null) : null; }