All files / src/hooks/useSlotAssignment useSlotAssignment.ts

95.61% Statements 109/114
80.55% Branches 29/36
100% Functions 19/19
95.41% Lines 104/109

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                                                                                                            1x 96x 96x 96x 96x 96x 96x         96x 52x 52x   52x 52x 50x   50x 23x       2x 2x 2x 2x   52x             96x     5x 5x     5x 5x 5x 10x 5x     5x 5x     3x   3x     3x 2x   1x 1x   3x                     96x   1x 1x   1x 1x 1x 2x     1x 1x   1x 1x 1x 1x             1x                 96x   1x 1x 1x   1x                         96x   5x 5x     7x 5x 10x   5x 5x       4x     4x   2x 2x   2x 2x   4x                 96x 3x   3x 3x 1x   2x 2x             96x 1x           96x 1x           96x 3x   3x 3x     1x   2x 2x 2x 2x             96x 3x   3x 3x     1x   2x 2x 2x 2x         96x 48x       96x   96x                                            
/**
 * useSlotAssignment Hook (Story 5.7 - Task 4b GREEN Phase)
 *
 * State management hook for slot assignment functionality
 * Features:
 * - Fetch and manage unassigned sessions
 * - Assign timing to sessions (drag-drop)
 * - Bulk timing assignment
 * - Conflict detection and management
 * - Optimistic updates with rollback
 */
 
import { useState, useEffect, useCallback } from 'react';
import { AxiosError } from 'axios';
import {
  slotAssignmentService,
  type SlotAssignmentRequestBody,
} from '@/services/slotAssignmentService/slotAssignmentService';
import type {
  Session,
  SessionTimingRequest,
  BulkTimingRequest,
  TimingConflictError,
  ConflictAnalysisResponse,
} from '@/types/event.types';
 
export interface UseSlotAssignmentReturn {
  // State
  unassignedSessions: Session[];
  isLoading: boolean;
  error: string | null;
  conflict: TimingConflictError | null;
  conflictAnalysis: ConflictAnalysisResponse | null;
  assignedCount: number;
  totalSessions: number;
 
  // Actions
  assignTiming: (sessionSlug: string, timing: SessionTimingRequest) => Promise<void>;
  assignToSlot: (sessionSlug: string, request: SlotAssignmentRequestBody) => Promise<void>;
  unassignTiming: (sessionSlug: string) => Promise<void>;
  bulkAssignTiming: (request: BulkTimingRequest) => Promise<void>;
  detectConflicts: () => Promise<void>;
  clearConflict: () => void;
  refreshSessions: () => Promise<void>;
  clearAllTimings: () => Promise<void>;
  autoAssignTimings: () => Promise<void>;
}
 
/**
 * Hook for managing slot assignment state and operations
 *
 * @param eventCode - Event code (e.g., "BATbern142")
 * @returns Slot assignment state and operations
 */
export const useSlotAssignment = (eventCode: string): UseSlotAssignmentReturn => {
  const [unassignedSessions, setUnassignedSessions] = useState<Session[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [conflict, setConflict] = useState<TimingConflictError | null>(null);
  const [conflictAnalysis, setConflictAnalysis] = useState<ConflictAnalysisResponse | null>(null);
  const [totalSessions, setTotalSessions] = useState<number>(0);
 
  /**
   * Fetch unassigned sessions
   */
  const fetchUnassignedSessions = useCallback(async () => {
    setIsLoading(true);
    setError(null);
 
    try {
      const sessions = await slotAssignmentService.getUnassignedSessions(eventCode);
      setUnassignedSessions(sessions);
      // If this is first load, set total sessions
      if (totalSessions === 0) {
        setTotalSessions(sessions.length);
      }
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to fetch unassigned sessions';
      console.error('[useSlotAssignment] Fetch failed:', errorMessage);
      setError(errorMessage);
      setUnassignedSessions([]);
    } finally {
      setIsLoading(false);
    }
  }, [eventCode, totalSessions]);
 
  /**
   * Assign timing to a session
   */
  const assignTiming = useCallback(
    async (sessionSlug: string, timing: SessionTimingRequest): Promise<void> => {
      // Clear any existing conflicts
      setConflict(null);
      setError(null);
 
      // Optimistic update - remove from unassigned list and save snapshot for rollback
      let rollbackSessions: Session[] = [];
      setUnassignedSessions((prev) => {
        rollbackSessions = [...prev]; // Capture current state for rollback
        const filtered = prev.filter((s) => s.sessionSlug !== sessionSlug);
        return filtered;
      });
 
      try {
        await slotAssignmentService.assignSessionTiming(eventCode, sessionSlug, timing);
        // Success - optimistic update is kept, no need to refetch
      } catch (err) {
        console.error('[useSlotAssignment] ✗ API call failed - rolling back optimistic update');
        // Rollback optimistic update using captured snapshot
        setUnassignedSessions(rollbackSessions);
 
        // Handle conflict errors (409)
        if (err instanceof AxiosError && err.response?.status === 409) {
          setConflict(err.response.data as TimingConflictError);
        } else {
          const errorMessage = err instanceof Error ? err.message : 'Failed to assign timing';
          setError(errorMessage);
        }
        throw err;
      }
    },
    [eventCode]
  );
 
  /**
   * Assign / insert / swap a session by stable slot key (Story 15.3).
   * Optimistically removes the dragged session from the unassigned tray and rolls back on error.
   * A 409 (agenda-full / conflict) is surfaced via `conflict`.
   */
  const assignToSlot = useCallback(
    async (sessionSlug: string, request: SlotAssignmentRequestBody): Promise<void> => {
      setConflict(null);
      setError(null);
 
      let rollbackSessions: Session[] = [];
      setUnassignedSessions((prev) => {
        rollbackSessions = [...prev];
        return prev.filter((s) => s.sessionSlug !== sessionSlug);
      });
 
      try {
        await slotAssignmentService.assignSessionToSlot(eventCode, sessionSlug, request);
      } catch (err) {
        setUnassignedSessions(rollbackSessions);
        if (err instanceof AxiosError && err.response?.status === 409) {
          const body = err.response.data as TimingConflictError | undefined;
          setConflict(
            body && body.message ? body : ({ message: 'Agenda is full' } as TimingConflictError)
          );
        } else E{
          const errorMessage = err instanceof Error ? err.message : 'Failed to assign slot';
          setError(errorMessage);
        }
        throw err;
      }
    },
    [eventCode]
  );
 
  /**
   * Unassign a single session's slot — clears its timing and returns it to the pool (Story 15.3).
   */
  const unassignTiming = useCallback(
    async (sessionSlug: string): Promise<void> => {
      setError(null);
      try {
        await slotAssignmentService.unassignSessionTiming(eventCode, sessionSlug);
        // Refresh so the freed session reappears in the unassigned tray.
        await fetchUnassignedSessions();
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : 'Failed to remove slot';
        setError(errorMessage);
        throw err;
      }
    },
    [eventCode, fetchUnassignedSessions]
  );
 
  /**
   * Bulk assign timing to multiple sessions
   */
  const bulkAssignTiming = useCallback(
    async (request: BulkTimingRequest): Promise<void> => {
      setConflict(null);
      setError(null);
 
      // Optimistic update - remove all assigned sessions from unassigned list
      const sessionSlugs = request.assignments.map((a) => a.sessionSlug);
      const originalSessions = [...unassignedSessions];
      setUnassignedSessions((prev) => prev.filter((s) => !sessionSlugs.includes(s.sessionSlug)));
 
      try {
        await slotAssignmentService.bulkAssignTiming(eventCode, request);
        // Success - optimistic update is kept
      } catch (err) {
        // Rollback optimistic update
        setUnassignedSessions(originalSessions);
 
        // Handle conflict errors (409)
        if (err instanceof AxiosError && err.response?.status === 409) {
          // For bulk conflicts, set error instead of conflict
          const errorMessage = err.response.data?.message || 'Bulk assignment conflicts detected';
          setError(errorMessage);
        } else {
          const errorMessage = err instanceof Error ? err.message : 'Failed to assign timing';
          setError(errorMessage);
        }
        throw err;
      }
    },
    [eventCode, unassignedSessions]
  );
 
  /**
   * Detect conflicts in event schedule
   */
  const detectConflicts = useCallback(async (): Promise<void> => {
    setError(null);
 
    try {
      const analysis = await slotAssignmentService.detectConflicts(eventCode);
      setConflictAnalysis(analysis);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to detect conflicts';
      setError(errorMessage);
    }
  }, [eventCode]);
 
  /**
   * Clear conflict state
   */
  const clearConflict = useCallback((): void => {
    setConflict(null);
  }, []);
 
  /**
   * Refresh unassigned sessions
   */
  const refreshSessions = useCallback(async (): Promise<void> => {
    await fetchUnassignedSessions();
  }, [fetchUnassignedSessions]);
 
  /**
   * Clear all session timings (reset all to unassigned)
   */
  const clearAllTimings = useCallback(async (): Promise<void> => {
    setError(null);
 
    try {
      await slotAssignmentService.clearAllTimings(eventCode);
 
      // Refresh sessions to update UI
      await fetchUnassignedSessions();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to clear all timings';
      console.error('[useSlotAssignment] ✗ Failed to clear timings:', errorMessage);
      setError(errorMessage);
      throw err;
    }
  }, [eventCode, fetchUnassignedSessions]);
 
  /**
   * Auto-assign all unassigned sessions to available time slots
   */
  const autoAssignTimings = useCallback(async (): Promise<void> => {
    setError(null);
 
    try {
      await slotAssignmentService.autoAssignTimings(eventCode);
 
      // Refresh sessions to update UI
      await fetchUnassignedSessions();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to auto-assign timings';
      console.error('[useSlotAssignment] ✗ Failed to auto-assign:', errorMessage);
      setError(errorMessage);
      throw err;
    }
  }, [eventCode, fetchUnassignedSessions]);
 
  // Fetch unassigned sessions on mount
  useEffect(() => {
    fetchUnassignedSessions();
  }, [fetchUnassignedSessions]);
 
  // Calculate assigned count
  const assignedCount = totalSessions - unassignedSessions.length;
 
  return {
    // State
    unassignedSessions,
    isLoading,
    error,
    conflict,
    conflictAnalysis,
    assignedCount,
    totalSessions,
 
    // Actions
    assignTiming,
    assignToSlot,
    unassignTiming,
    bulkAssignTiming,
    detectConflicts,
    clearConflict,
    refreshSessions,
    clearAllTimings,
    autoAssignTimings,
  };
};