All files / apps/host/src/hooks useCreateOutcome.ts

100% Statements 50/50
93.54% Branches 29/31
100% Functions 16/16
100% Lines 46/46

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                                        2x         2x 6x 6x           2x       2x     2x   1x                   2x         2x 1x   2x       2x 2x       2x       2x           2x 14x 14x 14x   14x   1x   5x   5x 5x 2x 2x                                   3x 2x       5x     2x 2x 1x       2x 1x     2x 2x 1x       1x           14x   8x 2x       2x   6x 6x           14x    
import { useCallback, useRef } from 'react';
 
import { useMutation, useQueryClient } from '@tanstack/react-query';
 
import { TICKET_STATE } from '@repo/constants/ticket';
 
import { useAuth } from '@/contexts/AuthContext';
 
import { PROCESSING_BY_RESPONSE, QUERY_KEYS } from '@/constants/apis';
 
import {
  ActivityState,
  RequestBaseData,
  RequestListResponseData,
  RequestStatus,
} from '@/types/request';
 
import { createOutcome } from '@/services/request';
import { sentryService } from '@/services/sentryService';
 
const PENDING_QUERY_KEY = [
  `${QUERY_KEYS.LIST_REQUESTS} not pagination`,
  RequestStatus.PENDING,
] as const;
 
const isListRequestsQuery = (query: { queryKey: readonly unknown[] }) => {
  const firstKey = query.queryKey[0];
  return (
    firstKey === QUERY_KEYS.LIST_REQUESTS ||
    (typeof firstKey === 'string' && firstKey === `${QUERY_KEYS.LIST_REQUESTS} not pagination`)
  );
};
 
const updatePendingCache = (
  oldData: RequestListResponseData | undefined,
  requestId: string,
): RequestListResponseData | undefined => {
  if (!oldData) return oldData;
 
  const updatedItems =
    oldData.items?.filter((item: RequestBaseData) => item.id !== requestId) || [];
 
  return {
    ...oldData,
    items: updatedItems,
    meta: {
      ...oldData.meta,
      total: updatedItems.length,
    },
  };
};
 
const updatePendingItemCache = (
  oldData: RequestListResponseData | undefined,
  requestId: string,
  updater: (item: RequestBaseData) => RequestBaseData,
): RequestListResponseData | undefined => {
  if (!oldData) return oldData;
  return {
    ...oldData,
    items: oldData.items.map(item => (item.id === requestId ? updater(item) : item)),
  };
};
 
const refetchInactiveQueries = (queryClient: ReturnType<typeof useQueryClient>) => {
  queryClient.refetchQueries({
    queryKey: [QUERY_KEYS.LIST_REQUESTS],
    type: 'inactive',
  });
  queryClient.refetchQueries({
    predicate: isListRequestsQuery,
    type: 'inactive',
  });
  queryClient.refetchQueries({
    queryKey: [QUERY_KEYS.MY_REQUESTS],
    type: 'inactive',
  });
};
 
export const useCreateOutcome = (onSuccess?: () => void, onError?: (error?: unknown) => void) => {
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const inFlightIdsRef = useRef<Set<string>>(new Set());
 
  const mutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: { state: string; note?: string } }) =>
      createOutcome(id, data),
    onMutate: async variables => {
      await queryClient.cancelQueries({ predicate: isListRequestsQuery });
 
      const previousData = queryClient.getQueryData(PENDING_QUERY_KEY);
      if (variables.data.state === TICKET_STATE.PROCEED) {
        queryClient.setQueryData<RequestListResponseData>(PENDING_QUERY_KEY, oldData =>
          updatePendingItemCache(oldData, variables.id, item => ({
            ...item,
            processingBy: user?.email || PROCESSING_BY_RESPONSE.NONE,
            activities: [
              {
                name: user?.displayName ?? '',
                email: user?.email ?? '',
                avatar: user?.photoURL ?? '',
                occurredAt: new Date().toISOString(),
                state: ActivityState.PENDING,
                isApproved: false,
                note: '',
              },
              ...(item.activities ?? []),
            ],
          })),
        );
      } else {
        queryClient.setQueryData<RequestListResponseData>(PENDING_QUERY_KEY, oldData =>
          updatePendingCache(oldData, variables.id),
        );
      }
 
      return { previousData };
    },
    onSuccess: () => {
      refetchInactiveQueries(queryClient);
      if (onSuccess) {
        onSuccess();
      }
    },
    onError: (err, _variables, context) => {
      if (context?.previousData) {
        queryClient.setQueryData(PENDING_QUERY_KEY, context.previousData);
      }
 
      sentryService.captureException(err);
      if (onError) {
        onError(err);
      }
    },
    onSettled: (_data, _error, variables) => {
      inFlightIdsRef.current.delete(variables.id);
    },
  });
 
  // `mutateAsync` is intentionally not wrapped here — any new caller needing
  // the dedup guard must use `mutate`.
  const mutate = useCallback<typeof mutation.mutate>(
    (variables, options) => {
      if (inFlightIdsRef.current.has(variables.id)) {
        sentryService.captureException(
          new Error(`Duplicate createOutcome call ignored for request ${variables.id}`),
          { tags: { dedup: 'createOutcome' } },
        );
        return;
      }
      inFlightIdsRef.current.add(variables.id);
      mutation.mutate(variables, options);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [mutation.mutate],
  );
 
  return { ...mutation, mutate };
};