import type { 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'; type StudentMeDeps = { db?: Pick; now?: Date }; export class GetStudentMe { constructor(private readonly deps: StudentMeDeps = {}) {} async execute(accountId: string): Promise> { const db = this.deps.db ?? prisma; const account = await db.studentAccount.findUnique({ where: { id: accountId }, select: { id: true, name: true, recoveryEmail: true, pendingRecoveryEmail: true, welcomedAt: true, _count: { select: { passkeys: true } }, attendees: { where: { attendee: { status: { not: 'DROPPED' } } }, orderBy: { createdAt: 'asc' }, select: { attendee: { select: { id: true, fullName: true, group: { select: { id: true, name: true, owner: { select: { name: true } } } }, }, }, }, }, }, }); if (!account) return err(unauthorizedProblem('/student-portal/me')); return ok({ account: { id: account.id, name: account.name, recoveryEmail: account.recoveryEmail, pendingRecoveryEmail: account.pendingRecoveryEmail, hasPasskey: account._count.passkeys > 0, welcomed: account.welcomedAt !== null, }, students: account.attendees.map(({ attendee }) => ({ attendeeId: attendee.id, fullName: attendee.fullName, groupId: attendee.group.id, groupName: attendee.group.name, teacherName: attendee.group.owner.name, })), }); } } /* The welcome screen is shown until the student goes past it once. */ export class MarkStudentWelcomed { constructor(private readonly deps: StudentMeDeps = {}) {} async execute(accountId: string): Promise> { const db = this.deps.db ?? prisma; await db.studentAccount.updateMany({ where: { id: accountId, welcomedAt: null }, data: { welcomedAt: this.deps.now ?? new Date() }, }); return new GetStudentMe({ db }).execute(accountId); } }