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 | 4x 18x 10x 4x 11x 4x 4x 8x 3x 4x 6x 2x 4x 4x 1x 4x 89x 89x 5x 4x 4x 114x 114x 6x 6x 6x 6x 6x 6x 1x 5x 5x 5x 5x 4x 34x 34x 7x 5x | /**
* Event Management React Query Hooks (Story 2.5.3 - Task 7b)
*
* React Query hooks for Event Management feature:
* - useEvents: List query with filters, sort, pagination (cache 5min)
* - useEvent: Detail query with resource expansion (cache 15min)
* - useEventWorkflow: Workflow state query (cache 10min)
* - useCriticalTasks: Critical tasks query (cache 3min)
* - useTeamActivity: Activity feed query (cache 2min)
* - useCreateEvent: Create mutation
* - useUpdateEvent: Update mutation with optimistic updates
* - useDeleteEvent: Delete mutation
*
* AC: 14 (Performance), 19 (Service Integration), 18 (State Management)
*/
import {
useQuery,
useMutation,
useQueryClient,
type UseQueryResult,
type UseMutationResult,
} from '@tanstack/react-query';
import { eventApiClient } from '@/services/eventApiClient';
import type {
Event,
EventDetailUI,
EventFilters,
EventListResponse,
WorkflowState,
CriticalTasksResponse,
TeamActivityResponse,
CreateEventRequest,
PatchEventRequest,
PaginationParams,
} from '@/types/event.types';
// ============================================================================
// Query Hooks
// ============================================================================
/**
* useEvents - Fetch paginated list of events with filters
* Cache: 5 minutes (moderately volatile data)
*
* @param pagination - Page number and limit
* @param filters - Optional filters for events
* @param options - Optional expand resources (e.g., ['registrations'] for actual counts)
*/
export const useEvents = (
pagination: PaginationParams,
filters?: EventFilters,
options?: { expand?: string[] }
): UseQueryResult<EventListResponse, Error> => {
return useQuery({
queryKey: ['events', pagination, filters, options],
queryFn: () => eventApiClient.getEvents(pagination, filters, options),
staleTime: 5 * 60 * 1000, // 5 minutes
});
};
/**
* useEvent - Fetch single event with optional resource expansion
* Cache: 15 minutes (full event with includes cached longer)
*
* Story 11.E.8 follow-up: {@code refetchOnWindowFocus} is enabled so the organizer's
* Sessions sub-tab (and any other view that consumes this query) refreshes when the
* organizer switches back to the tab after a speaker has submitted new content in a
* different window. Without this, the 15-min staleTime served the prior payload until
* an organizer-side mutation (e.g. quality-review approval) invalidated the cache —
* which made it look like sessions.title only updates after review acceptance.
*
* @param eventCode - Event code identifier (e.g., "BATbern56")
* @param include - Resources to expand (workflow, speakers, sessions, venue, registrations)
*/
export const useEvent = (
eventCode: string | undefined,
include?: string[]
): UseQueryResult<EventDetailUI, Error> => {
return useQuery({
queryKey: ['event', eventCode, include],
queryFn: () => eventApiClient.getEvent(eventCode!, include ? { expand: include } : undefined),
enabled: !!eventCode, // Only fetch if eventCode is provided
staleTime: 15 * 60 * 1000, // 15 minutes
refetchOnWindowFocus: true,
});
};
/**
* useEventWorkflow - Fetch event workflow state
* Cache: 10 minutes (workflow changes moderately)
*/
export const useEventWorkflow = (
eventCode: string | undefined
): UseQueryResult<WorkflowState, Error> => {
return useQuery({
queryKey: ['eventWorkflow', eventCode],
queryFn: () => eventApiClient.getEventWorkflow(eventCode!),
enabled: !!eventCode,
staleTime: 10 * 60 * 1000, // 10 minutes
});
};
/**
* useCriticalTasks - Fetch critical tasks for organizer
* Cache: 3 minutes (tasks are more volatile)
*
* @param organizerUsername - Username of organizer (e.g., "john.doe")
* @param limit - Number of tasks to fetch (default: 10)
*/
export const useCriticalTasks = (
organizerUsername: string | undefined,
limit: number = 10
): UseQueryResult<CriticalTasksResponse, Error> => {
return useQuery({
queryKey: ['criticalTasks', organizerUsername, limit],
queryFn: async () => {
// TODO: API needs to be updated to support organizerUsername filter
// For now, returning empty response until backend implements this endpoint
return {
data: [],
total: 0,
};
},
enabled: !!organizerUsername,
staleTime: 3 * 60 * 1000, // 3 minutes
});
};
/**
* useTeamActivity - Fetch team activity feed
* Cache: 2 minutes (activity feed is very volatile)
*
* @param organizerUsername - Username of organizer (e.g., "john.doe")
* @param limit - Number of activity items to fetch (default: 20)
*/
export const useTeamActivity = (
organizerUsername: string | undefined,
limit: number = 20
): UseQueryResult<TeamActivityResponse, Error> => {
return useQuery({
queryKey: ['teamActivity', organizerUsername, limit],
queryFn: async () => {
// TODO: API needs to be updated to support organizerUsername filter
// For now, returning empty response until backend implements this endpoint
return {
data: [],
pagination: {
page: 1,
limit,
totalItems: 0,
hasNext: false,
},
};
},
enabled: !!organizerUsername,
staleTime: 2 * 60 * 1000, // 2 minutes
});
};
// ============================================================================
// Mutation Hooks
// ============================================================================
/**
* useCreateEvent - Create new event mutation
* Invalidates 'events' query on success
*/
export const useCreateEvent = (): UseMutationResult<Event, Error, CreateEventRequest> => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateEventRequest) => eventApiClient.createEvent(data),
onSuccess: () => {
// Invalidate events list to refresh with new event
queryClient.invalidateQueries({ queryKey: ['events'] });
},
});
};
/**
* useUpdateEvent - Update event mutation with optimistic updates
* Invalidates 'events' and specific 'event' queries on success
*
* Features:
* - Optimistic updates for instant UI feedback
* - Rollback on error
* - Cache invalidation on success
*/
export const useUpdateEvent = (): UseMutationResult<
Event,
Error,
{ eventCode: string; data: PatchEventRequest }
> => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ eventCode, data }: { eventCode: string; data: PatchEventRequest }) =>
eventApiClient.patchEvent(eventCode, data),
// Optimistic update
onMutate: async ({ eventCode, data }) => {
// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: ['event', eventCode] });
// Snapshot the previous value
const previousEvent = queryClient.getQueryData(['event', eventCode]);
// Optimistically update to the new value
queryClient.setQueryData(['event', eventCode], (old: Event | undefined) => {
Eif (!old) return old;
return { ...old, ...data };
});
// Return context with the snapshotted value
return { previousEvent };
},
// Rollback on error
onError: (_error, { eventCode }, context) => {
Iif (context?.previousEvent) {
queryClient.setQueryData(['event', eventCode], context.previousEvent);
}
},
// Invalidate and refetch on success
onSuccess: async (updatedEvent, { eventCode }) => {
// Invalidate ALL event-related caches for proper MVC pattern
// 1. List caches (all pagination/filter combinations)
queryClient.invalidateQueries({ queryKey: ['events'] });
Iif (updatedEvent.eventCode !== eventCode) {
// EventCode changed (e.g., eventNumber 58 -> 998 regenerates BATbern58 -> BATbern998)
// CRITICAL: Cancel all active queries for old eventCode to prevent refetch
await queryClient.cancelQueries({ queryKey: ['event', eventCode] });
// Set the new data for the new eventCode (prevents unnecessary refetch)
queryClient.setQueryData(['event', updatedEvent.eventCode], updatedEvent);
// Remove old eventCode cache (no longer needed)
queryClient.removeQueries({ queryKey: ['event', eventCode] });
} else {
// EventCode unchanged - normal invalidation to refresh data
queryClient.invalidateQueries({ queryKey: ['event', eventCode] });
}
// 3. Current event cache (in case updated event is the current published one)
queryClient.invalidateQueries({ queryKey: ['events', 'current'] });
},
});
};
/**
* useDeleteEvent - Delete event mutation
* Invalidates 'events' query on success
*/
export const useDeleteEvent = (): UseMutationResult<void, Error, string> => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (eventCode: string) => eventApiClient.deleteEvent(eventCode),
onSuccess: () => {
// Invalidate events list to remove deleted event
queryClient.invalidateQueries({ queryKey: ['events'] });
},
});
};
|