All files / src/components/Merchants/MerchantPreview/OFAC/hooks useOFAC.tsx

87.5% Statements 42/48
53.57% Branches 15/28
94.11% Functions 16/17
87.5% Lines 42/48

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                                      11x 27x           11x 230x     27x 10x         230x     11x           10x     10x           11x                 85x               10x 7x         85x     11x         145x 145x 145x 145x 175x     145x         145x       145x               5x                       145x         5x 6x     5x             3x           3x                 3x     3x 3x         3x                                                     145x                                                       11x         4x             11x           20x   4x           20x          
import { showMessage } from "@common/Toast";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import { updatePermissions } from "@redux/slices/app";
import { customInstance } from "@services/api";
import {
  composePermission,
  useAccessControl,
} from "features/Permissions/AccessControl";
import {
  UseQueryOptions,
  useMutation,
  useQuery,
  useQueryClient,
} from "react-query";
import { OFAC_MERCHANT_PANEL_QUERY_FIELD } from "../keys";
import { GET_HISTORY_LIST } from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/constants";
 
const getOfacCategories = () => {
  return customInstance({
    url: "/changelog-categories",
    method: "GET",
  });
};
 
export const useOFACCategories = () => {
  const { data, error, isLoading } = useQuery(
    ["list-ofac-categories"],
    async () => {
      const data = await getOfacCategories();
      return data;
    },
    { refetchOnMount: false, refetchOnWindowFocus: false, staleTime: Infinity }, //categories never change
  );
 
  return { error, isLoading, data };
};
 
const getMerchantOFAC = (
  merchantId: number,
  type: string,
  legalEntityId?: number,
) => {
  // We will pass legalEntityId if new ofac implementation is not disabled
  const url = legalEntityId
    ? `/merchants/${merchantId}/legal-entities/${legalEntityId}/ofac-checks?sort=-createdAt`
    : `/merchants/${merchantId}/ofac-checks?filter=resourceTypeName:"${type}"&sort=-createdAt`;
  return customInstance({
    url: url,
    method: "GET",
  });
};
 
export const useOFACChecks = (
  merchantId: number,
  type: string,
  legalEntityId?: number,
  queryOptions?: Omit<
    UseQueryOptions<any, unknown, any, (string | number)[]>,
    "queryKey" | "queryFn"
  >,
) => {
  const { data, error, isLoading } = useQuery(
    [
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_OFAC,
      merchantId,
      type,
      legalEntityId || "",
    ],
    async () => {
      const ofac = await getMerchantOFAC(merchantId, type, legalEntityId);
      return ofac?.data || [];
    },
    { enabled: Boolean(merchantId && legalEntityId), ...queryOptions },
  );
 
  return { error, isLoading, data: data as OFACCheckType[] };
};
 
export const useRunOFAC = (
  merchantId: number,
  isEnterprise: boolean,
  legalEntityId?: number,
) => {
  const { data: categories } = useOFACCategories();
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const hasNotOFACPermission = useAppSelector(
    (state) => state.app.permissions?.["ofac_check"],
  );
 
  const composed = composePermission(
    isEnterprise ? RESOURCE_BASE.ENTERPRISE : RESOURCE_BASE.MERCHANT,
    RESOURCE_BASE.OFAC,
  );
 
  const isListOfacAllowed = useAccessControl({
    resource: composed,
    operation: OPERATIONS.LIST,
  });
  const runOFACMutation = useMutation(
    ({
      resourceTypeName,
      resourceID,
    }: {
      resourceTypeName: string;
      resourceID?: number;
    }) => {
      return customInstance({
        // We will pass legalEntityId if new ofac implementation is not disabled
 
        url: legalEntityId
          ? `/merchants/${merchantId}/legal-entities/${legalEntityId}/ofac-checks`
          : `/merchants/${merchantId}/resources/${resourceTypeName}/ofac-checks/${resourceID}`,
        method: "POST",
        data: {},
      });
    },
  );
 
  const runOFACHandler = async (
    activeTab: string,
    resourceID?: number,
    onSuccessCb?: () => void,
  ) => {
    const category = categories?.data?.find(
      (category: any) => category.DisplayName === activeTab,
    );
 
    runOFACMutation.mutate(
      {
        resourceTypeName: category?.id,
        resourceID: resourceID,
      },
      {
        onError: (error: any) => {
          showMessage(
            "Error",
            error?.message || error?.response?.status,
            true,
            "Something went wrong...",
          );
          Iif (error.not_authorized) {
            dispatch(
              updatePermissions({
                ofac_check: true,
              }),
            );
          }
        },
        onSettled: (data) => {
          queryClient.invalidateQueries({
            queryKey: [GET_HISTORY_LIST, merchantId],
          });
          Eif (isListOfacAllowed) {
            queryClient.invalidateQueries([
              MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_OFAC,
              merchantId,
            ]);
          }
          const keyToUpdate = (OFAC_MERCHANT_PANEL_QUERY_FIELD as any)[
            data.resourceTypeName
          ];
          if (data && keyToUpdate)
            queryClient.setQueriesData(
              [MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET, merchantId],
              (oldData: any) => {
                return {
                  ...oldData,
                  [keyToUpdate]: {
                    lastCheckStatusName: data.statusName,
                    lastCheckAt: data.updatedAt,
                  },
                };
              },
            );
          else
            queryClient.invalidateQueries([
              MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_LEGAL_ENTITY,
              merchantId,
            ]);
          onSuccessCb?.();
        },
      },
    );
  };
 
  return {
    runOFACHandler,
    isLoading: runOFACMutation.isLoading,
    hasNotOFACPermission,
  };
};
 
export type OFACCheckType = {
  ID: number;
  legalEntityID: number;
  statusName: OFACCheckStatusType;
  matchList: any[];
  possibleMatchAt: number | null;
  createdAt: number;
  updatedAt: number;
  resourceID: number;
  resourceFullName?: string;
  resourceCitizenship?: string;
  resourceCountryOfResidence?: string;
  principalOwnershipPercentage?: number;
};
 
export type OFACCheckStatusType =
  | "clear"
  | "manually_cleared"
  | "possible_match"
  | "confirmed_match";
 
const getOfacCheckById = (
  merchantId: number,
  checkId: number,
  legalEntityId?: number,
) =>
  customInstance({
    url: legalEntityId
      ? `/merchants/${merchantId}/legal-entities/${legalEntityId}/ofac-checks/${checkId}`
      : `/merchants/${merchantId}/ofac-checks/${checkId}`,
    method: "GET",
  });
 
export const useGetOfacCheckById = (
  merchantId: number,
  checkId: number,
  legalEntityId?: number,
  enabled = true,
) => {
  const { data, isLoading } = useQuery(
    ["get-ofac-check-by-id", merchantId, checkId],
    async () => await getOfacCheckById(merchantId, checkId, legalEntityId),
    {
      enabled: enabled && Boolean(merchantId) && Boolean(checkId),
    },
  );
 
  return {
    data,
    isLoading,
  };
};