import type { PrismaClient } from '@generated/prisma/client'; import type { StudentAccessDto } from '@gruperly/shared'; export type StudentAccessStatusDb = Pick; /* Passive state for the attendee's card: active (a live session) > invited (a pending invitation) > expired (invited before, nothing alive) > not invited. It is the person's access, so every group of theirs shows the same state. */ export async function computeStudentAccess( db: StudentAccessStatusDb, personId: string, now: Date, ): Promise { const link = await db.studentAccountPerson.findFirst({ where: { personId }, orderBy: { createdAt: 'asc' }, select: { account: { select: { _count: { select: { passkeys: true } }, sessions: { where: { revokedAt: null, expiresAt: { gt: now } }, orderBy: { lastUsedAt: 'desc' }, select: { device: true, createdAt: true, lastUsedAt: true }, }, tokens: { where: { kind: 'INVITATION' }, orderBy: { createdAt: 'desc' }, take: 1, select: { usedAt: true, revokedAt: true, expiresAt: true }, }, }, }, }, }); if (!link) { return { status: 'not_invited', invitationExpiresAt: null, devices: [], hasPasskey: false }; } const { account } = link; const devices = account.sessions.map((session) => ({ device: session.device, createdAt: session.createdAt.toISOString(), lastUsedAt: session.lastUsedAt.toISOString(), })); const hasPasskey = account._count.passkeys > 0; const lastInvitation = account.tokens[0] ?? null; const pending = lastInvitation && !lastInvitation.usedAt && !lastInvitation.revokedAt && lastInvitation.expiresAt > now ? lastInvitation : null; if (devices.length > 0) { return { status: 'active', invitationExpiresAt: null, devices, hasPasskey }; } if (pending) { return { status: 'invited', invitationExpiresAt: pending.expiresAt.toISOString(), devices, hasPasskey, }; } return { status: lastInvitation ? 'expired' : 'not_invited', invitationExpiresAt: null, devices, hasPasskey, }; }