All files / src/features/GiveConversation/hooks useManageApi.tsx

87.14% Statements 61/70
62.96% Branches 34/54
92.3% Functions 24/26
86.76% Lines 59/68

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                                                              117x                         90x   90x   90x     5x       4x           21x 21x     21x   21x     1x     3x         90x 21x   21x 3x                   90x 21x   3x 3x 1x         3x 3x           90x   90x                   117x                           128x     10x   10x     10x         10x 10x 10x   10x       10x   10x     6x         50x 50x     50x   50x         128x 23x   75x     75x         128x                 117x                     107x 107x   107x   1x                                                                                   107x     117x                     117x 43x           117x             623x     43x           623x    
import { customInstance } from "@services/api";
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
  UseQueryOptions,
} from "react-query";
 
import {
  ConversationStats,
  GiveConversationTabType,
  MessagesArrayTypes,
  MessagesChatTypes,
  TThreadItem,
} from "../types";
import { getStartOfDay, transformMessage } from "../utils";
import {
  QKEY_GET_CONVERSATION_THREADS,
  QKEY_GET_SINGLE_THREAD_MESSAGES,
  QKEY_GET_CONVERSATION_STATS,
  QKEY_LIST_ACQUIRER_MERCHANTS,
  QKEY_LIST_ENTERPRISE_STATS,
} from "@constants/queryKeys";
import { useGetCurrentMerchantId } from "@hooks/common";
import { ROWS_PER_PAGE } from "@hooks/common/usePagination";
import { isEmpty } from "lodash";
import { useMemo } from "react";
import { UNDERWRITING_CHALLENGE_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { checkPortals } from "@utils/routing";
 
export const useGetMessageConversationChat = ({
  id,
  merchantId,
  nthFromLast = 0,
  onError,
  onSuccess,
}: {
  id?: number;
  merchantId: number;
  nthFromLast?: number;
  onError?: (res: any) => void;
  onSuccess?: (res: any) => void;
}) => {
  const { selectedUser } = useGetCurrentMerchantId();
 
  const loggedInUserAccountId = selectedUser?.userAccID;
 
  const query = useInfiniteQuery(
    [QKEY_GET_SINGLE_THREAD_MESSAGES, id],
    async ({ pageParam = 1 }) => {
      const res = await customInstance({
        url: `/v2/merchants/${merchantId}/threads/${id}/messages?page=${pageParam}&max=${ROWS_PER_PAGE}&sort=-createdAt`, //`/merchants/${merchantId}/threads-v2?page=${pageParam}&limit=${ROWS_PER_PAGE}`,
      });
 
      return res;
    },
    {
      retry: 0,
      enabled: !!id && !!merchantId,
      getNextPageParam: (lastPage, allPages) => {
        const totalFetched = allPages.reduce(
          (sum, page) => sum + (page?.data?.length ?? 0),
          0,
        );
        const totalAvailable = lastPage?.total ?? 0;
 
        return totalFetched < totalAvailable ? allPages.length + 1 : undefined;
      },
      onError(err: any) {
        onError?.(err);
      },
      onSuccess(data) {
        onSuccess?.(data);
      },
    },
  );
 
  const messages = useMemo(() => {
    const messageData = query.data?.pages.flatMap((page) => page?.data) ?? [];
 
    return messageData.map((item, idx, arr) =>
      transformMessage({
        item,
        idx,
        arr,
        nthFromLast,
        loggedInUserAccountId,
      }),
    );
  }, [query.data, nthFromLast, loggedInUserAccountId]);
 
  const groupedByDate = useMemo(() => {
    return Object.values(
      messages.reduce((acc, msg) => {
        const dateKey = getStartOfDay(msg.time);
        if (!acc[dateKey]) {
          acc[dateKey] = {
            date: dateKey,
            messages: [],
          };
        }
        acc[dateKey].messages.unshift(msg);
        return acc;
      }, {} as Record<number, { date: number; messages: MessagesChatTypes[] }>),
    ) as MessagesArrayTypes[];
  }, [messages]);
 
  const isBackgroundFetchingMessages =
    query.isRefetching && !query.isLoading && !query.isFetchingNextPage;
 
  return {
    messages: groupedByDate,
    isLoadingGetMessages: query.isLoading,
    isFetchingNextPageMessages: query.isFetchingNextPage,
    fetchNextPageMessages: query.fetchNextPage,
    hasNextPageMessages: query.hasNextPage,
    isBackgroundFetchingMessages,
  };
};
 
export const useGetConversationThreads = ({
  merchantId,
  selectedTab,
  isMentioned = false,
  accountType,
  enabled = true,
}: {
  merchantId: string | number;
  selectedTab?: GiveConversationTabType;
  isMentioned?: boolean;
  enabled?: boolean;
  accountType?: "all" | "merchant" | "provider";
  additionalFilters?: any;
}) => {
  const query = useInfiniteQuery(
    [QKEY_GET_CONVERSATION_THREADS, merchantId, selectedTab, isMentioned],
    async ({ pageParam = 1 }) => {
      const isTeamTab = selectedTab === "team";
      const accountTypeFilter =
        accountType && accountType !== "all"
          ? `&accountType=${accountType}`
          : "";
      const isInternalFilter = selectedTab
        ? `isInternal:${isTeamTab}${accountTypeFilter}`
        : "";
      // We don't have mentioned filter in merchant tab
      const isMentionedFilter =
        isMentioned && isTeamTab ? `isMentioned=${isMentioned}` : "";
      const filter = (() => {
        Iif (isMentionedFilter)
          return `${isInternalFilter}&${isMentionedFilter}`;
        else if (selectedTab) return isInternalFilter;
        else Ereturn "";
      })();
 
      const formattedFilter = filter ? `&filter=${filter}` : "";
 
      const res = await customInstance({
        url: `/v2/merchants/${merchantId}/threads?page=${pageParam}&max=${ROWS_PER_PAGE}&sort=-lastMessageSentAt${formattedFilter}`,
      });
      return res;
    },
    {
      enabled: !!merchantId && enabled,
      getNextPageParam: (lastPage, allPages) => {
        const totalFetched = allPages.reduce(
          (sum, page) => sum + (page?.data?.length ?? 0),
          0,
        );
        const totalAvailable = lastPage?.total ?? 0;
 
        return totalFetched < totalAvailable ? allPages.length + 1 : undefined;
      },
    },
  );
 
  const flattenedThreads: TThreadItem[] = (
    query.data?.pages.flatMap((page) => page?.data) ?? []
  )
    .filter((item) => !isEmpty(item))
    .map(
      (item) =>
        ({
          ...item,
        } as TThreadItem),
    );
 
  return {
    threads: flattenedThreads,
    isLoading: query.isLoading,
    isFetchingNextPageThreadList: query.isFetchingNextPage,
    fetchNextPageThreadList: query.fetchNextPage,
    hasNextPageThreadList: query.hasNextPage,
  };
};
 
export const useMarkAsRead = ({
  threadId,
  merchantId,
  selectedTab,
  isMentioned = false,
}: {
  threadId?: number;
  merchantId?: number;
  selectedTab?: GiveConversationTabType;
  isMentioned?: boolean;
}) => {
  const queryClient = useQueryClient();
  const { isAcquirerEnterprises } = checkPortals();
 
  const markAsReadMutation = useMutation(
    () => {
      return customInstance({
        url: `/v2/merchants/${merchantId}/messages/read`,
        method: "POST",
        data: threadId
          ? {
              threadID: threadId,
            }
          : {},
      });
    },
    {
      onSuccess(data) {
        queryClient.invalidateQueries([
          QKEY_GET_CONVERSATION_STATS,
          merchantId,
        ]);
 
        queryClient.invalidateQueries([
          QKEY_GET_CONVERSATION_THREADS,
          merchantId,
          selectedTab,
          isMentioned,
        ]);
        // We invalidate the list of merchants to update the unread messages/has merchant replied flags
 
        queryClient.invalidateQueries(
          UNDERWRITING_CHALLENGE_API_KEYS.GET_TASKS,
          {
            refetchActive: true,
            refetchInactive: false,
          },
        );
 
        if (isAcquirerEnterprises) {
          queryClient.invalidateQueries(QKEY_LIST_ENTERPRISE_STATS);
        } else {
          queryClient.invalidateQueries([QKEY_LIST_ACQUIRER_MERCHANTS]);
        }
      },
    },
  );
 
  return { markAsReadMutation };
};
 
export const fetchThread = async (
  merchantId: number,
  threadName: string,
  isInternal = true,
) => {
  return customInstance({
    url: `/v2/merchants/${merchantId}/threads?filter=title:"${threadName}"%3BsubjectAccID:${merchantId}%3BisInternal:${isInternal}`,
    method: "GET",
  });
};
 
export const getConversationStats = async (merchantId: number) => {
  return customInstance({
    url: `/v2/merchants/${merchantId}/threads/stats`,
    method: "GET",
  });
};
 
export const useGetConversationStats = ({
  merchantID,
  options,
}: {
  merchantID: number;
  options?: UseQueryOptions;
}) => {
  const { data, ...rest } = useQuery({
    queryKey: [QKEY_GET_CONVERSATION_STATS, merchantID],
    queryFn: () => {
      return getConversationStats(merchantID);
    },
    enabled: !!merchantID && options?.enabled !== false,
    ...options,
  });
 
  return { data: data as ConversationStats, ...rest };
};