All files / web/src/lib/curriculum server.ts

0% Statements 0/343
0% Branches 0/1
0% Functions 0/1
0% Lines 0/343

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Server-only data fetching for curriculum/practice pages
 *
 * These functions make direct database calls for use in Server Components,
 * avoiding the HTTP round-trip that would occur with API routes.
 *
 * Use these for SSR prefetching with React Query's HydrationBoundary.
 */

import 'server-only'

import { and, eq, inArray } from 'drizzle-orm'
import { db, schema } from '@/db'
import type { SessionPart, SlotResult } from '@/db/schema/session-plans'
import type { Player } from '@/db/schema/players'
import { getPlayer } from '@/lib/arcade/player-manager'
import { batchGetEnrolledClassrooms, batchGetStudentPresence } from '@/lib/classroom'
import { getParentedPlayerIds } from '@/lib/classroom/access-control'
import { getUserId } from '@/lib/viewer'
import {
  computeIntervention,
  computeSkillCategory,
  type SkillDistribution,
  type StudentActiveSessionInfo,
  type StudentWithSkillData,
} from '@/utils/studentGrouping'
import { computeBktFromHistory, getStalenessWarning } from './bkt'
import {
  getAllSkillMastery,
  getPaginatedSessions,
  getPlayerCurriculum,
  getRecentSessions,
} from './progress-manager'
import {
  batchGetRecentSessionResults,
  getActiveSessionPlan,
  getRecentSessionResults,
  type ProblemResultWithContext,
} from './session-planner'

export type { PlayerCurriculum } from '@/db/schema/player-curriculum'
export type { PlayerSkillMastery } from '@/db/schema/player-skill-mastery'
export type { Player } from '@/db/schema/players'
export type { PracticeSession } from '@/db/schema/practice-sessions'
// Re-export types that consumers might need
export type { SessionPlan } from '@/db/schema/session-plans'
export type { StudentWithSkillData } from '@/utils/studentGrouping'

/**
 * Prefetch all data needed for the practice page
 *
 * This fetches in parallel for optimal performance:
 * - Player details
 * - Active session plan
 * - Curriculum position
 * - Skill mastery records
 * - Recent practice sessions
 */
export async function prefetchPracticeData(playerId: string) {
  const [player, activeSession, curriculum, skills, recentSessions] = await Promise.all([
    getPlayer(playerId),
    getActiveSessionPlan(playerId),
    getPlayerCurriculum(playerId),
    getAllSkillMastery(playerId),
    getRecentSessions(playerId, 10),
  ])

  return {
    player: player ?? null,
    activeSession,
    curriculum,
    skills,
    recentSessions,
  }
}

/**
 * Get all players for the current viewer (server-side)
 *
 * Uses getUserId() to identify the current user and fetches their players.
 */
export async function getPlayersForViewer(): Promise<Player[]> {
  const userId = await getUserId()

  // Get all players for this user
  const players = await db.query.players.findMany({
    where: eq(schema.players.userId, userId),
    orderBy: (players, { desc }) => [desc(players.createdAt)],
  })

  return players
}

/**
 * Compute skill distribution for a player from pre-fetched problem history.
 * Uses BKT to determine mastery levels and staleness.
 *
 * Accepts pre-fetched ProblemResultWithContext[] to avoid per-player DB queries.
 */
function computePlayerSkillDistribution(
  practicingSkillIds: string[],
  problemHistory: ProblemResultWithContext[]
): SkillDistribution {
  const distribution: SkillDistribution = {
    strong: 0,
    stale: 0,
    developing: 0,
    weak: 0,
    unassessed: 0,
    total: practicingSkillIds.length,
  }

  if (practicingSkillIds.length === 0) return distribution

  if (problemHistory.length === 0) {
    distribution.unassessed = practicingSkillIds.length
    return distribution
  }

  const now = new Date()
  const bktResult = computeBktFromHistory(problemHistory, {})
  const bktMap = new Map(bktResult.skills.map((s) => [s.skillId, s]))

  for (const skillId of practicingSkillIds) {
    const bkt = bktMap.get(skillId)

    if (!bkt || bkt.opportunities === 0) {
      distribution.unassessed++
      continue
    }

    const classification = bkt.masteryClassification ?? 'developing'

    if (classification === 'strong') {
      const lastPracticed = bkt.lastPracticedAt
      if (lastPracticed) {
        const daysSince = (now.getTime() - lastPracticed.getTime()) / (1000 * 60 * 60 * 24)
        if (getStalenessWarning(daysSince)) {
          distribution.stale++
        } else {
          distribution.strong++
        }
      } else {
        distribution.strong++
      }
    } else {
      distribution[classification]++
    }
  }

  return distribution
}

/**
 * Batch-fetch active sessions for multiple players in a single query.
 *
 * Returns a Map<playerId, StudentActiveSessionInfo>.
 * Players without active sessions are omitted from the map.
 */
async function batchGetActiveSessions(
  playerIds: string[]
): Promise<Map<string, StudentActiveSessionInfo>> {
  const result = new Map<string, StudentActiveSessionInfo>()
  if (playerIds.length === 0) return result

  // Single query: active session plans for all players
  const activePlans = await db
    .select({
      id: schema.sessionPlans.id,
      playerId: schema.sessionPlans.playerId,
      status: schema.sessionPlans.status,
      parts: schema.sessionPlans.parts,
      results: schema.sessionPlans.results,
    })
    .from(schema.sessionPlans)
    .where(
      and(
        inArray(schema.sessionPlans.playerId, playerIds),
        inArray(schema.sessionPlans.status, ['approved', 'in_progress'])
      )
    )

  // Group by player (take most recent if multiple — though unlikely)
  for (const plan of activePlans) {
    if (result.has(plan.playerId)) continue // first one wins
    const parts = (plan.parts as SessionPart[]) || []
    const results = (plan.results as SlotResult[]) || []
    const totalProblems = parts.reduce((sum, part) => sum + part.slots.length, 0)
    result.set(plan.playerId, {
      sessionId: plan.id,
      status: plan.status,
      completedProblems: results.length,
      totalProblems,
    })
  }

  return result
}

/**
 * Get all players for the current viewer with enhanced skill data.
 *
 * Includes:
 * - practicingSkills: List of skill IDs being practiced
 * - lastPracticedAt: Most recent practice timestamp (max of all skill lastPracticedAt)
 * - skillCategory: Computed highest-level skill category
 * - intervention: Intervention data if student needs attention
 * - enrolledClassrooms: Batch-fetched classroom enrollments
 * - currentPresence: Batch-fetched presence info
 * - activeSession: Batch-fetched active session info
 */
export async function getPlayersWithSkillData(): Promise<StudentWithSkillData[]> {
  const userId = await getUserId()

  // Get all player IDs the user has parent access to (owned + linked, with guest expiry)
  const parentedIds = await getParentedPlayerIds(userId)

  // Get practice students from the parented set
  // Only returns players flagged as practice students (excludes arcade-only players)
  let players: Player[]
  if (parentedIds.length > 0) {
    players = await db.query.players.findMany({
      where: and(
        inArray(schema.players.id, parentedIds),
        eq(schema.players.isPracticeStudent, true)
      ),
      orderBy: (players, { desc }) => [desc(players.createdAt)],
    })
  } else {
    players = []
  }

  if (players.length === 0) return []

  const playerIds = players.map((p) => p.id)

  // Batch-fetch all enrichment data in parallel (single query each)
  const [allSkillMastery, enrollmentMap, presenceMap, activeSessionMap, sessionResultsByPlayer] =
    await Promise.all([
      db.query.playerSkillMastery.findMany({
        where: inArray(schema.playerSkillMastery.playerId, playerIds),
      }),
      batchGetEnrolledClassrooms(playerIds),
      batchGetStudentPresence(playerIds),
      batchGetActiveSessions(playerIds),
      batchGetRecentSessionResults(playerIds, 100),
    ])

  // Group skill mastery by player
  const skillsByPlayer = new Map<string, typeof allSkillMastery>()
  for (const skill of allSkillMastery) {
    let list = skillsByPlayer.get(skill.playerId)
    if (!list) {
      list = []
      skillsByPlayer.set(skill.playerId, list)
    }
    list.push(skill)
  }

  // Build enriched players (all data is pre-fetched, no async work per player)
  const playersWithSkills = players.map((player) => {
    const skills = skillsByPlayer.get(player.id) ?? []

    // Get practicing skills and compute lastPracticedAt
    const practicingSkills: string[] = []
    let lastPracticedAt: Date | null = null

    for (const skill of skills) {
      if (skill.isPracticing) {
        practicingSkills.push(skill.skillId)
      }
      if (skill.lastPracticedAt) {
        if (!lastPracticedAt || skill.lastPracticedAt > lastPracticedAt) {
          lastPracticedAt = skill.lastPracticedAt
        }
      }
    }

    // Compute skill category
    const skillCategory = computeSkillCategory(practicingSkills)

    // Compute intervention data (only for non-archived students with skills)
    let intervention = null
    if (!player.isArchived && practicingSkills.length > 0) {
      const distribution = computePlayerSkillDistribution(
        practicingSkills,
        sessionResultsByPlayer.get(player.id) ?? []
      )
      const daysSinceLastPractice = lastPracticedAt
        ? (Date.now() - lastPracticedAt.getTime()) / (1000 * 60 * 60 * 24)
        : Infinity

      intervention = computeIntervention(
        distribution,
        daysSinceLastPractice,
        practicingSkills.length > 0
      )
    }

    // Convert server presence to client-compatible shape
    const serverPresence = presenceMap.get(player.id)
    const currentPresence = serverPresence
      ? {
          playerId: serverPresence.playerId,
          classroomId: serverPresence.classroomId,
          enteredAt: serverPresence.enteredAt.toISOString(),
          enteredBy: serverPresence.enteredBy,
          classroom: serverPresence.classroom,
        }
      : null

    return {
      ...player,
      practicingSkills,
      lastPracticedAt,
      skillCategory,
      intervention,
      enrolledClassrooms: enrollmentMap.get(player.id) ?? [],
      currentPresence,
      activeSession: activeSessionMap.get(player.id) ?? null,
    }
  })

  return playersWithSkills
}

// Re-export the individual functions for granular prefetching
export { getPlayer } from '@/lib/arcade/player-manager'
export { getPracticeStudent } from './practice-student'
export {
  getAllSkillMastery,
  getPaginatedSessions,
  getPlayerCurriculum,
  getRecentSessions,
} from './progress-manager'
export type { PaginatedSessionsResponse } from './progress-manager'
export {
  getActiveSessionPlan,
  getMostRecentCompletedSession,
  getRecentSessionResults,
  getSessionPlan,
} from './session-planner'
export type { ProblemResultWithContext } from './session-planner'