All files / web/src/hooks useUnifiedStudents.ts

38.5% Statements 139/361
100% Branches 29/29
66.66% Functions 2/3
38.5% Lines 139/361

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 3621x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                             1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 2x 9x 1x 9x 1x 9x 1x 9x 1x 9x 1x 9x 1x 9x 1x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 3x 3x 3x  
'use client'
 
import { useMemo, useRef } from 'react'
 
// Stable empty array reference to avoid re-renders
const EMPTY_CHILD_IDS: string[] = []
import {
  useMyClassroom,
  useEnrolledStudents,
  useClassroomPresence,
  useActiveSessionsInClassroom,
  type ActiveSessionInfo,
  type PresenceStudent,
} from '@/hooks/useClassroom'
import { useChildSessionsSocket, type ChildActiveSession } from '@/hooks/useChildSessionsSocket'
import { usePlayersWithSkillData } from '@/hooks/useUserPlayers'
import type { StudentWithSkillData } from '@/utils/studentGrouping'
import type { UnifiedStudent, StudentRelationship, StudentActivity } from '@/types/student'
 
/**
 * Return type for useUnifiedStudents hook
 */
export interface UseUnifiedStudentsResult {
  /** Merged list of all students from all sources */
  students: UnifiedStudent[]
  /** Whether the current user is a teacher (has a classroom) */
  isTeacher: boolean
  /** Teacher's classroom code (for display) */
  classroomCode?: string
  /** Classroom ID (for actions) */
  classroomId?: string
  /** Whether any data is still loading */
  isLoading: boolean
}
 
/**
 * Hook to fetch and merge student data from multiple sources
 *
 * Combines:
 * - My children (from players API)
 * - Enrolled students (teacher's classroom)
 * - Present students (classroom presence)
 * - Active sessions (practicing status)
 *
 * Returns a unified list with relationship and activity status for each student.
 *
 * @param initialPlayers - Server-prefetched player data
 * @param userId - The current user's database ID (for parent session subscriptions)
 */
export function useUnifiedStudents(
  initialPlayers?: StudentWithSkillData[],
  userId?: string
): UseUnifiedStudentsResult {
  // Get classroom data (determines if user is a teacher)
  const { data: classroom, isLoading: isLoadingClassroom } = useMyClassroom()
  const isTeacher = !!classroom

  // Get my children (all users see this)
  const { data: myChildren = [], isLoading: isLoadingChildren } = usePlayersWithSkillData({
    initialData: initialPlayers,
  })

  // Get child IDs for parent session subscription
  const childIds = useMemo(() => myChildren.map((c) => c.id), [myChildren])

  // Build initial session data from batch-fetched enrichment fields
  const initialChildSessions = useMemo(() => {
    const hasEnrichment = myChildren.some((c) => c.activeSession !== undefined)
    if (!hasEnrichment) return undefined

    const map = new Map<string, ChildActiveSession>()
    for (const child of myChildren) {
      if (child.activeSession) {
        map.set(child.id, {
          planId: child.activeSession.sessionId,
          status: child.activeSession.status,
          completedSlots: child.activeSession.completedProblems,
          totalSlots: child.activeSession.totalProblems,
          startedAt: new Date().toISOString(),
        })
      }
    }
    return map
  }, [myChildren])

  // Get enrolled students (teachers only)
  const { data: enrolledStudents = [], isLoading: isLoadingEnrolled } = useEnrolledStudents(
    classroom?.id
  )

  // Get present students (teachers only)
  const { data: presentStudents = [], isLoading: isLoadingPresence } = useClassroomPresence(
    classroom?.id
  )

  // Get active sessions (teachers only - for students in their classroom)
  const { data: activeSessions = [], isLoading: isLoadingActiveSessions } =
    useActiveSessionsInClassroom(classroom?.id)

  // Get active sessions for parent's children (via WebSocket for real-time updates)
  // Enabled for ALL users who have children (teachers can also be parents)
  const hasChildren = childIds.length > 0
  const { sessionMap: childSessionMap, isLoading: isLoadingChildSessions } = useChildSessionsSocket(
    hasChildren ? userId : undefined,
    hasChildren ? childIds : EMPTY_CHILD_IDS,
    initialChildSessions
  )

  // Build lookup maps for efficient merging
  const presenceMap = useMemo(() => {
    const map = new Map<string, PresenceStudent>()
    for (const student of presentStudents) {
      map.set(student.id, student)
    }
    return map
  }, [presentStudents])

  // Merge teacher's classroom sessions with parent's child sessions
  const sessionMap = useMemo(() => {
    const map = new Map<string, ActiveSessionInfo>()
    // Teacher sessions from classroom
    for (const session of activeSessions) {
      map.set(session.playerId, session)
    }
    // Parent sessions from WebSocket (convert ChildActiveSession to ActiveSessionInfo format)
    for (const [playerId, session] of childSessionMap) {
      if (!map.has(playerId)) {
        map.set(playerId, {
          sessionId: session.planId,
          playerId,
          startedAt: session.startedAt,
          completedProblems: session.completedSlots,
          totalProblems: session.totalSlots,
          currentPartIndex: 0,
          currentSlotIndex: session.completedSlots,
          totalParts: 1,
        })
      }
    }
    return map
  }, [activeSessions, childSessionMap])

  const enrolledIds = useMemo(() => {
    return new Set(enrolledStudents.map((s) => s.id))
  }, [enrolledStudents])

  // Merge all sources into unified students
  const students = useMemo(() => {
    const studentMap = new Map<string, UnifiedStudent>()

    // Add my children first (highest priority for data)
    for (const child of myChildren) {
      const relationship: StudentRelationship = {
        isMyChild: true,
        isEnrolled:
          child.enrolledClassrooms !== undefined
            ? child.enrolledClassrooms.length > 0
            : enrolledIds.has(child.id),
        isPresent:
          child.currentPresence !== undefined
            ? child.currentPresence !== null
            : presenceMap.has(child.id),
        enrollmentStatus: null, // TODO: Add pending enrollment lookup
      }

      const session = sessionMap.get(child.id)
      const activity: StudentActivity = session
        ? {
            status: 'practicing',
            sessionProgress: {
              current: session.completedProblems,
              total: session.totalProblems,
            },
            sessionId: session.sessionId,
          }
        : { status: 'idle' }

      studentMap.set(child.id, {
        ...child,
        relationship,
        activity,
      })
    }

    // Add enrolled students that aren't already in the map (teacher view)
    if (isTeacher) {
      for (const enrolled of enrolledStudents) {
        if (!studentMap.has(enrolled.id)) {
          const relationship: StudentRelationship = {
            isMyChild: false,
            isEnrolled: true,
            isPresent: presenceMap.has(enrolled.id),
            enrollmentStatus: null,
          }

          const session = sessionMap.get(enrolled.id)
          const activity: StudentActivity = session
            ? {
                status: 'practicing',
                sessionProgress: {
                  current: session.completedProblems,
                  total: session.totalProblems,
                },
                sessionId: session.sessionId,
              }
            : { status: 'idle' }

          studentMap.set(enrolled.id, {
            ...enrolled,
            relationship,
            activity,
          })
        }
      }

      // Add present students that aren't enrolled or my children
      // (edge case: student who somehow got presence without enrollment)
      for (const present of presentStudents) {
        if (!studentMap.has(present.id)) {
          const relationship: StudentRelationship = {
            isMyChild: false,
            isEnrolled: false,
            isPresent: true,
            enrollmentStatus: null,
          }

          const session = sessionMap.get(present.id)
          const activity: StudentActivity = session
            ? {
                status: 'practicing',
                sessionProgress: {
                  current: session.completedProblems,
                  total: session.totalProblems,
                },
                sessionId: session.sessionId,
              }
            : { status: 'idle' }

          studentMap.set(present.id, {
            ...present,
            relationship,
            activity,
          })
        }
      }
    }

    return Array.from(studentMap.values())
  }, [
    myChildren,
    enrolledStudents,
    presentStudents,
    isTeacher,
    enrolledIds,
    presenceMap,
    sessionMap,
  ])

  const isLoading =
    isLoadingClassroom ||
    isLoadingChildren ||
    (isTeacher && (isLoadingEnrolled || isLoadingPresence || isLoadingActiveSessions)) ||
    (hasChildren && isLoadingChildSessions)

  return {
    students,
    isTeacher,
    classroomCode: classroom?.code,
    classroomId: classroom?.id,
    isLoading,
  }
}
 
/**
 * Filter students by view
 */
export function filterStudentsByView(
  students: UnifiedStudent[],
  view:
    | 'all'
    | 'my-children'
    | 'my-children-active'
    | 'enrolled'
    | 'in-classroom'
    | 'in-classroom-active'
    | 'needs-attention'
): UnifiedStudent[] {
  switch (view) {
    case 'all':
      return students
    case 'needs-attention':
      return students.filter((s) => s.intervention != null && !s.isArchived)
    case 'my-children':
      return students.filter((s) => s.relationship.isMyChild)
    case 'my-children-active':
      return students.filter((s) => s.relationship.isMyChild && s.activity?.status === 'practicing')
    case 'enrolled':
      return students.filter((s) => s.relationship.isEnrolled)
    case 'in-classroom':
      return students.filter((s) => s.relationship.isPresent)
    case 'in-classroom-active':
      return students.filter((s) => s.relationship.isPresent && s.activity?.status === 'practicing')
    default:
      return students
  }
}
 
/**
 * Compute view counts from unified students.
 *
 * Primary counts exclude archived students (matching the default display).
 * Also returns `allTotal` so the UI can subtly indicate the full roster size.
 */
export function computeViewCounts(
  students: UnifiedStudent[],
  isTeacher: boolean
): Partial<
  Record<
    | 'all'
    | 'my-children'
    | 'my-children-active'
    | 'enrolled'
    | 'in-classroom'
    | 'in-classroom-active'
    | 'needs-attention',
    number
  >
> & { allTotal?: number } {
  const active = students.filter((s) => !s.isArchived)
 
  const counts: Partial<
    Record<
      | 'all'
      | 'my-children'
      | 'my-children-active'
      | 'enrolled'
      | 'in-classroom'
      | 'in-classroom-active'
      | 'needs-attention',
      number
    >
  > & { allTotal?: number } = {
    all: active.length,
    allTotal: students.length,
    'needs-attention': active.filter((s) => s.intervention != null).length,
    'my-children': active.filter((s) => s.relationship.isMyChild).length,
    'my-children-active': active.filter(
      (s) => s.relationship.isMyChild && s.activity?.status === 'practicing'
    ).length,
  }
 
  if (isTeacher) {
    counts.enrolled = active.filter((s) => s.relationship.isEnrolled).length
    counts['in-classroom'] = active.filter((s) => s.relationship.isPresent).length
    counts['in-classroom-active'] = active.filter(
      (s) => s.relationship.isPresent && s.activity?.status === 'practicing'
    ).length
  }
 
  return counts
}