All files / web/src/hooks useParentSocket.ts

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

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                                                                                                                                                                                                                                                                                                                                   
'use client'

import { useEffect, useRef, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { createSocket } from '@/lib/socket'
import { useQueryClient } from '@tanstack/react-query'
import { invalidateForEvent } from '@/lib/classroom/query-invalidations'
import type {
  EnrollmentApprovedEvent,
  EnrollmentRequestApprovedEvent,
  EnrollmentRequestCreatedEvent,
  EnrollmentRequestDeniedEvent,
  EntryPromptAcceptedEvent,
  EntryPromptCreatedEvent,
  EntryPromptDeclinedEvent,
  StudentUnenrolledEvent,
} from '@/lib/classroom/socket-events'

/**
 * Hook for real-time parent notifications via WebSocket
 *
 * When a teacher adds a student (that the parent is linked to) to their classroom,
 * this hook receives the event and automatically invalidates the React Query cache
 * so the UI updates to show the new pending approval.
 *
 * @param userId - The parent's user ID to subscribe to notifications for
 * @returns Whether the socket is connected
 */
export function useParentSocket(userId: string | undefined): {
  connected: boolean
} {
  const [connected, setConnected] = useState(false)
  const socketRef = useRef<Socket | null>(null)
  const queryClient = useQueryClient()

  useEffect(() => {
    if (!userId) return

    // Create socket connection
    const socket = createSocket({
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5,
    })
    socketRef.current = socket

    socket.on('connect', () => {
      console.log('[ParentSocket] Connected')
      setConnected(true)
      // Join the user channel for parent notifications
      socket.emit('join-user-channel', { userId })
    })

    socket.on('disconnect', () => {
      console.log('[ParentSocket] Disconnected')
      setConnected(false)
    })

    // Listen for enrollment request created event (teacher added student to classroom)
    socket.on('enrollment-request-created', (data: EnrollmentRequestCreatedEvent) => {
      console.log(
        '[ParentSocket] Enrollment request created for:',
        data.request.playerName,
        'in classroom:',
        data.request.classroomName
      )
      invalidateForEvent(queryClient, 'requestCreated', {
        classroomId: data.request.classroomId,
        playerId: data.request.playerId,
      })
    })

    // Listen for enrollment request approved event (teacher approved parent's request)
    socket.on('enrollment-request-approved', (data: EnrollmentRequestApprovedEvent) => {
      console.log(
        '[ParentSocket] Enrollment request approved for:',
        data.playerName,
        'by:',
        data.approvedBy
      )
      invalidateForEvent(queryClient, 'requestApproved', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for enrollment request denied event (teacher denied parent's request)
    socket.on('enrollment-request-denied', (data: EnrollmentRequestDeniedEvent) => {
      console.log(
        '[ParentSocket] Enrollment request denied for:',
        data.playerName,
        'by:',
        data.deniedBy
      )
      invalidateForEvent(queryClient, 'requestDenied', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for enrollment completed event (student fully enrolled)
    socket.on('enrollment-approved', (data: EnrollmentApprovedEvent) => {
      console.log('[ParentSocket] Enrollment completed for:', data.playerName)
      invalidateForEvent(queryClient, 'enrollmentCompleted', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for student unenrolled event (child removed from classroom)
    socket.on('student-unenrolled', (data: StudentUnenrolledEvent) => {
      console.log('[ParentSocket] Child unenrolled:', data.playerName, 'from:', data.classroomName)
      invalidateForEvent(queryClient, 'studentUnenrolled', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for entry prompt created event (teacher wants child to enter classroom)
    socket.on('entry-prompt-created', (data: EntryPromptCreatedEvent) => {
      console.log(
        '[ParentSocket] Entry prompt from:',
        data.teacherName,
        'for:',
        data.playerName,
        'to enter:',
        data.classroomName
      )
      invalidateForEvent(queryClient, 'entryPromptCreated', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for entry prompt accepted event (another parent accepted)
    socket.on('entry-prompt-accepted', (data: EntryPromptAcceptedEvent) => {
      console.log('[ParentSocket] Entry prompt accepted for:', data.playerName)
      invalidateForEvent(queryClient, 'entryPromptAccepted', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Listen for entry prompt declined event (another parent declined)
    socket.on('entry-prompt-declined', (data: EntryPromptDeclinedEvent) => {
      console.log('[ParentSocket] Entry prompt declined for:', data.playerName)
      invalidateForEvent(queryClient, 'entryPromptDeclined', {
        classroomId: data.classroomId,
        playerId: data.playerId,
      })
    })

    // Cleanup on unmount
    return () => {
      socket.disconnect()
      socketRef.current = null
    }
  }, [userId, queryClient])

  return { connected }
}