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

66.66% Statements 28/42
17.24% Branches 5/29
42.85% Functions 6/14
73.68% Lines 28/38

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                                    2x         2x               2x                                     2x                       2x 1x       1x       1x           2x 5x 5x   5x   1x   2x   2x 2x 1x                                     1x         2x     1x 1x 1x       1x 1x     1x 1x 1x 1x          
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();
 
  return 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);
      Eif (onSuccess) {
        onSuccess();
      }
    },
    onError: (err, _variables, context) => {
      Eif (context?.previousData) {
        queryClient.setQueryData(PENDING_QUERY_KEY, context.previousData);
      }
 
      console.error('[useCreateOutcome] Error creating outcome:', err);
      sentryService.captureException(err);
      Eif (onError) {
        onError(err);
      }
    },
  });
};