Bin
2025-12-17 21f0498f62ada55651f4d232327e15fc47f498b1
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
/**
 * Hook for fetching state history from the API
 */
 
import { useQuery } from "@tanstack/react-query";
import { getApiInstance } from "@humansignal/core/lib/api-provider/api-instance";
 
export interface StateHistoryItem {
  state: string;
  created_at: string;
  triggered_by: {
    first_name?: string;
    last_name?: string;
    email?: string;
  } | null;
  previous_state?: string;
  transition_name?: string;
  reason?: string;
  context_data?: {
    reason?: string;
  };
}
 
export interface StateHistoryResponse {
  results: StateHistoryItem[];
}
 
export interface UseStateHistoryOptions {
  entityType: "task" | "annotation" | "project";
  entityId: number;
  enabled?: boolean;
}
 
/**
 * Hook to fetch state transition history for an entity
 *
 * @param options - Configuration options
 * @returns Query result with state history data
 */
export function useStateHistory({ entityType, entityId, enabled = true }: UseStateHistoryOptions) {
  const queryKey = ["state-history", entityType, entityId];
 
  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey,
    queryFn: async () => {
      const api = getApiInstance();
 
      // Use the API provider to make the request
      const result = await api.invoke<StateHistoryResponse>("fsmStateHistory", { entityType, entityId });
 
      // Handle API errors
      if (result?.error || !result?.$meta?.ok) {
        throw new Error(result?.error || "Failed to fetch state history");
      }
 
      return result as StateHistoryResponse;
    },
    enabled: enabled && !!entityId,
    staleTime: 30 * 1000, // Cache for 30 seconds
    cacheTime: 5 * 60 * 1000, // Keep in cache for 5 minutes
    retry: 2,
  });
 
  return { data, isLoading, isError, error, refetch };
}