import { AttemptPhase, AttemptStatus, Prisma } from '@prisma/client'; import { prisma } from '../../lib/prisma.js'; import { ConflictError, ForbiddenError, ValidationError } from '../../shared/errors/index.js'; import { getOrCreateJourney, deriveCurrentStep, derivePermissions, countCompletedSessions, } from '../journey/journey.service.js'; import { PCQ_QUESTION_IDS, DIMENSION_NAMES, DIMENSION_SCORE_MIN, DIMENSION_SCORE_MAX, TOTAL_SCORE_MIN, TOTAL_SCORE_MAX, scoreAssessment, ScoringValidationError, type RawAnswer, } from './scoring/index.js'; import type { SubmitAttemptInput } from './assessments.schemas.js'; type ScoreMap = { total: number; efficacy: number; hope: number; resilience: number; optimism: number; }; function toScoreMap(metrics: { metricKey: string; rawScore: number }[]): ScoreMap { const lookup = Object.fromEntries(metrics.map((m) => [m.metricKey, m.rawScore])); return { total: lookup.total ?? 0, efficacy: lookup.efficacy ?? 0, hope: lookup.hope ?? 0, resilience: lookup.resilience ?? 0, optimism: lookup.optimism ?? 0, }; } function serializeAttempt(attempt: { id: bigint; phase: AttemptPhase; status: AttemptStatus; submittedAt: Date; scoredAt: Date; answers: { questionId: string; rawValue: number; points: number; dimension: string; isReverseScored: boolean; }[]; scores: { metricKey: string; rawScore: number }[]; }) { return { id: attempt.id.toString(), phase: attempt.phase, status: attempt.status, submittedAt: attempt.submittedAt.toISOString(), scoredAt: attempt.scoredAt.toISOString(), scores: toScoreMap(attempt.scores), answers: attempt.answers.map((answer) => ({ questionId: answer.questionId, selectedValue: answer.rawValue, score: answer.points, dimension: answer.dimension, isReverseScored: answer.isReverseScored, })), }; } const attemptInclude = { answers: { orderBy: { questionId: 'asc' as const } }, scores: true, } satisfies Prisma.AssessmentAttemptInclude; export function getPcq24Scale() { return { id: 'pcq24', itemCount: PCQ_QUESTION_IDS.length, questionIds: PCQ_QUESTION_IDS, likertMin: 1, likertMax: 6, reverseScoredQuestionIds: ['pcq_13', 'pcq_20', 'pcq_23'], dimensions: DIMENSION_NAMES.map((name) => ({ name, scoreMin: DIMENSION_SCORE_MIN, scoreMax: DIMENSION_SCORE_MAX, })), totalScoreMin: TOTAL_SCORE_MIN, totalScoreMax: TOTAL_SCORE_MAX, }; } export async function submitAttempt(userId: bigint, input: SubmitAttemptInput) { const [journey, completedSessionCount] = await Promise.all([ getOrCreateJourney(userId), countCompletedSessions(userId), ]); const permissions = derivePermissions(journey, { completedSessionCount }); if (input.phase === 'pre' && !permissions.canTakePreTest) { throw new ConflictError('Pre-test already completed'); } if (input.phase === 'post' && !permissions.canTakePostTest) { if (journey.postTestCompletedAt) { throw new ConflictError('Post-test already submitted'); } throw new ForbiddenError('Post-test is not available yet'); } const existing = await prisma.assessmentAttempt.findFirst({ where: { userId, phase: input.phase }, }); if (existing) { throw new ConflictError(`${input.phase === 'pre' ? 'Pre' : 'Post'}-test already submitted`); } let scored; try { scored = scoreAssessment(input.phase, input.answers as RawAnswer[]); } catch (err) { if (err instanceof ScoringValidationError) { throw new ValidationError('Invalid PCQ-24 answers', err.issues); } throw err; } const now = scored.completedAt; try { const attempt = await prisma.$transaction(async (tx) => { const created = await tx.assessmentAttempt.create({ data: { userId, phase: input.phase, status: AttemptStatus.scored, submittedAt: now, scoredAt: now, answers: { create: scored.answers.map((answer) => ({ questionId: answer.questionId, rawValue: answer.selectedValue, points: answer.rawScore, dimension: answer.dimension, isReverseScored: answer.isReverseScored, })), }, scores: { create: [ { metricKey: 'total', rawScore: scored.totalScore }, { metricKey: 'efficacy', rawScore: scored.dimensions.efficacy }, { metricKey: 'hope', rawScore: scored.dimensions.hope }, { metricKey: 'resilience', rawScore: scored.dimensions.resilience }, { metricKey: 'optimism', rawScore: scored.dimensions.optimism }, ], }, }, include: attemptInclude, }); if (input.phase === 'pre') { await tx.learningJourney.update({ where: { userId }, data: { preTestCompletedAt: journey.preTestCompletedAt ?? now, trainingStartedAt: journey.trainingStartedAt ?? now, lastActivityAt: now, currentStep: 'training_in_progress', }, }); } else { await tx.learningJourney.update({ where: { userId }, data: { postTestCompletedAt: journey.postTestCompletedAt ?? now, lastActivityAt: now, currentStep: 'completed', }, }); } return created; }); return serializeAttempt(attempt); } catch (err) { if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') { throw new ConflictError( `${input.phase === 'pre' ? 'Pre' : 'Post'}-test already submitted`, ); } throw err; } } export async function listAttempts(userId: bigint) { const attempts = await prisma.assessmentAttempt.findMany({ where: { userId }, include: attemptInclude, orderBy: { submittedAt: 'desc' }, }); return attempts.map(serializeAttempt); } export async function getLatestAttempt(userId: bigint, phase: AttemptPhase) { const attempt = await prisma.assessmentAttempt.findFirst({ where: { userId, phase }, include: attemptInclude, orderBy: { submittedAt: 'desc' }, }); return attempt ? serializeAttempt(attempt) : null; } export async function getAssessmentSummary(userId: bigint) { const [pre, post, journey, completedSessionCount] = await Promise.all([ getLatestAttempt(userId, AttemptPhase.pre), getLatestAttempt(userId, AttemptPhase.post), getOrCreateJourney(userId), countCompletedSessions(userId), ]); return { pre, post, journey: { currentStep: deriveCurrentStep(journey), permissions: derivePermissions(journey, { completedSessionCount }), }, }; }