All files / src/features/Merchants/MerchantSidePanel/components/UnderwriterRiskAnalystAssignCard MCCInput.tsx

82.75% Statements 72/87
78.12% Branches 75/96
84.21% Functions 16/19
84.52% Lines 71/84

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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353                                                                      26x                                                                                 6x             770x 770x 770x       770x 770x 770x 770x 770x         770x             770x 770x 770x 770x 770x             770x       770x 6x 6x 6x   770x 97x 3x     770x 102x 54x                 102x 46x   102x 92x   10x                         10x     770x                   770x       770x                                                           770x 300x   770x 338x     770x         770x       770x 6x 6x       6x 6x                       6x 6x 14x   6x   6x 6x     770x 102x 4x 12x   4x         770x             770x 770x 66x 704x 218x     486x     770x                                       2x   2x 2x     2x                                     2x                                                        
import GiveSelect from "@shared/GiveInputs/GiveSelect";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import useUpdateMerchant from "../../hooks/useUpdateMerchant";
import GivePopup from "@shared/Popup/GivePopup";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, {
  ACTION_DENY_MESSAGE,
  OPERATIONS,
} from "@constants/permissions";
import { CustomToolTip as PermissionTooltip } from "componentsV2/Table/CustomTooltip";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import { checkPortals } from "@utils/routing";
import useGetEnterpriseCategoryCodes from "@hooks/enterprise-api/merchants/useGetEnterpriseCategoryCodes";
import { TRiskLevelName } from "@common/Tag/RiskStatusChip";
import { TCategory } from "@common/BusinessProfileInputs/types";
import { debounce, isEmpty } from "lodash";
import { ContextualMenuProps } from "shared/ContextualMenu/ContextualMenu.types";
import { useMerchantSidePanelContext } from "../../Provider/MerchantSidePanelProvider";
import { TStatusReview } from "@components/Merchants/MerchantPreview/data.types";
import { ProcessorValue } from "@features/Merchants/MerchantSidePanel/types";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useQueryClient } from "react-query";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
 
type TOptions = {
  label: string;
  value: number;
  code: string;
  isSelected: boolean;
  checkedIconType: "Check";
  riskStatus: TRiskLevelName;
  description: JSX.Element | string;
};
 
const defaultState = {
  open: false,
  newId: null,
};
 
type Props = {
  setLocalRiskValue?: (val: string) => void;
  enterpriseID?: number;
  categoryCodeID?: number | "";
  name?: string;
  withAPI?: boolean;
  setFormValue?: (val: number, label?: string) => void;
  disableAlert?: boolean;
  contextualMenuProps?: Partial<ContextualMenuProps>;
  placeholder?: string;
  categoryCodeName?: string;
  code?: number;
  riskStatus?: string;
  localSelectedMcc?: React.MutableRefObject<number | null>;
  onConfirmChangeSuccess?: (data?: any) => void;
  isAcquirer?: boolean;
  status?: TStatusReview;
  disabledByProcessor?: boolean;
  processor?: ProcessorValue | "";
  isProvider?: boolean;
};
 
function MCCInput({
  setLocalRiskValue,
  enterpriseID,
  categoryCodeID,
  name,
  withAPI = true,
  setFormValue,
  disableAlert = false,
  contextualMenuProps,
  placeholder,
  localSelectedMcc,
  categoryCodeName,
  code,
  riskStatus,
  onConfirmChangeSuccess = () => null,
  isAcquirer = false,
  status,
  disabledByProcessor,
  processor,
  isProvider,
}: Props) {
  const searchBarValueRef = useRef("");
  const [searchValue, setSearchValue] = useState<string>("");
  const [{ open, newId }, setOpen] = useState<{
    open: boolean;
    newId: null | number | string;
  }>(defaultState);
  const { merchantId } = useGetCurrentMerchantId();
  const queryClient = useQueryClient();
  const { updateMerchantMutation } = useUpdateMerchant();
  const { mutateAsync, isLoading } = updateMerchantMutation;
  const [localValue, setLocalValue] = useState(categoryCodeID);
  const {
    data: categories,
    isLoading: isLoadingGetCategories,
    onEndReached,
  } = useGetEnterpriseCategoryCodes({
    id: isProvider ? merchantId : enterpriseID, //for provider panel, use the logged in id => acquirer
    searchKey: searchValue || searchBarValueRef.current,
    localValue: localValue || undefined,
    defaultCode: isProvider && !localValue && !status ? "5999" : undefined,
    processor: isProvider ? "worldpay" : processor,
  });
  const { isMobileView } = useCustomThemeV2();
  const { modify_merchant } = useEnterprisePermissions();
  const { isEnterprisePortal } = checkPortals();
  const context = useMerchantSidePanelContext();
  const { data, id: merchantSidePanelId } = !isEmpty(context)
    ? context
    : {
        data: { status },
        id: undefined,
      };
 
  const isApproved = ["approved", "suspended", "closed"].includes(
    data?.status?.statusName || "",
  );
 
  const handleClose = () => {
    searchBarValueRef.current = "";
    setSearchValue("");
    setOpen(defaultState);
  };
  useEffect(() => {
    if (localValue !== categoryCodeID) {
      setLocalValue(categoryCodeID);
    }
  }, [categoryCodeID]);
  const categoriesOptions: any[] = useMemo(() => {
    const allCategories = categories?.length
      ? categories.filter(Boolean).map((category: TCategory) => ({
          label: `${category.categoryCodes.code} - ${category.categoryCodes.title}`,
          value: category.categoryCodes.id,
          code: category.categoryCodes.code,
          isSelected:
            Number(categoryCodeID) === Number(category.categoryCodes.id),
          checkedIconType: "Check",
        }))
      : [];
    const isSelectedCategoryExist = allCategories.find(
      (category) => category?.value === categoryCodeID,
    );
    if (isSelectedCategoryExist || allCategories.length === 0)
      return allCategories;
 
    Iif (code && categoryCodeName) {
      return [
        ...allCategories,
        {
          label: `${code} - ${categoryCodeName}`,
          value: categoryCodeID,
          code: code,
          isSelected: true,
          checkedIconType: "Check",
        },
      ];
    }
 
    return allCategories;
  }, [categories, searchValue, categoryCodeID, code, categoryCodeName]);
 
  const debouncedSetSearchValue = useCallback(
    debounce((value, reason) => {
      if (reason === "onChange" || reason == "keyDown") {
        searchBarValueRef.current = value;
      }
      setSearchValue(value);
    }, 500),
    [],
  );
 
  const handleClearSearch = () => {
    searchBarValueRef.current = "";
    setSearchValue("");
  };
  const ctxMenuProps = {
    searchBarProps: {
      handleChange: (val: string, type: string) =>
        debouncedSetSearchValue(val, type),
      value: searchValue || searchBarValueRef?.current,
      handleClearSearch,
      resetOnClose: false,
    },
    onCloseEmptyState: handleClearSearch,
    showEmptySectionWhenNoData: true,
    onEndReached: onEndReached,
    emptySection: "empty-mcc",
    ...(!isMobileView
      ? {
          color: "transparent",
          texture: "blurred",
          anchorOrigin: {
            vertical: -20,
            horizontal: "center",
          },
          transformOrigin: {
            vertical: "bottom",
            horizontal: "center",
          },
        }
      : {}),
    isLoading: isLoadingGetCategories,
    ...contextualMenuProps,
  };
 
  const oldMCC = categoriesOptions?.find(
    (item: TOptions) => Number(item?.value) === Number(categoryCodeID),
  );
  const newMCC = categoriesOptions?.find(
    (item: TOptions) => Number(item?.value) === Number(newId),
  );
 
  const hasEditMerchantPermission = useAccessControl({
    resource: RESOURCE_BASE.MERCHANT,
    operation: OPERATIONS.UPDATE,
  });
 
  const allowedEditMerchant = isEnterprisePortal
    ? hasEditMerchantPermission && modify_merchant
    : hasEditMerchantPermission;
 
  const onConfirmChange = async (newId: null | number | string) => {
    setLocalValue(Number(newId));
    Iif (newMCC?.riskStatus && setLocalRiskValue) {
      setLocalRiskValue(newMCC.riskStatus);
      if (localSelectedMcc) localSelectedMcc.current = newMCC.code;
    }
    let data = null;
    Iif (withAPI) {
      data = await mutateAsync({
        categoryCodeID: Number(newId),
        merchantRiskStatus: newMCC?.riskStatus,
      });
      if (!categoryCodeID && merchantSidePanelId) {
        queryClient.invalidateQueries([
          MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_LEGAL_ENTITY,
          merchantSidePanelId,
        ]);
      }
    }
    Eif (setFormValue) {
      const labelValue = categoriesOptions?.find(
        (option) => Number(option.value) === Number(newId),
      )?.label;
      setFormValue(Number(newId), labelValue);
    }
    onConfirmChangeSuccess(data);
    handleClose();
  };
 
  useEffect(() => {
    if (isProvider && !categoryCodeID && !localValue && !status) {
      const defaultValue = categoriesOptions?.find(
        (item) => `${item.code}` === "5999",
      );
      Eif (defaultValue) onConfirmChange(defaultValue.value);
    }
  }, [isProvider, categoriesOptions]);
 
  const isDisabled =
    isLoading ||
    isLoadingGetCategories ||
    !allowedEditMerchant ||
    isApproved ||
    (isAcquirer && !enterpriseID && !isProvider) ||
    disabledByProcessor;
 
  const tooltipMessage = (() => {
    if (disabledByProcessor)
      return "Select a Provider and Processor before assigning an MCC";
    if (isApproved)
      return `You can’t change the MCC after the ${
        isProvider ? "provider" : "merchant"
      } is approved`;
    return ACTION_DENY_MESSAGE;
  })();
 
  return (
    <PermissionTooltip
      showToolTip={
        !allowedEditMerchant || isApproved || Boolean(disabledByProcessor)
      }
      message={tooltipMessage}
      placement="top-start"
      alignment="end"
    >
      <GiveSelect
        placeholder={placeholder}
        name={name}
        label="Merchant Category Code (MCC)"
        options={categoriesOptions}
        useContextualMenu
        disabled={isDisabled}
        value={localValue}
        contextualMenuProps={ctxMenuProps as any}
        withIconOffset={false}
        onChange={(e) => {
          const newMCC = e?.target?.value;
 
          Iif (newMCC === oldMCC?.value) return;
          Iif (disableAlert) {
            onConfirmChange(newMCC);
          } else {
            e?.target?.value &&
              setOpen({
                open: true,
                newId: newMCC,
              });
          }
        }}
      />
      <GivePopup
        type="success"
        open={open}
        actionButtons={{
          cancel: {
            label: "Cancel",
            onClick: handleClose,
          },
          success: {
            label: "Yes, Change",
            onClick: () => {
              onConfirmChange(newId);
            },
          },
        }}
        onClose={handleClose}
        description={
          <>
            {oldMCC && newMCC ? (
              <>
                Are you sure you want to change the MCC code from{" "}
                <strong>{oldMCC?.label}</strong> to{" "}
                <strong>{newMCC?.label}</strong>?{" "}
              </>
            ) : (
              <>
                Are you sure you want to assign <strong>{newMCC?.label}</strong>{" "}
                as the MCC for this {isProvider ? "provider" : "merchant"}?{" "}
              </>
            )}
          </>
        }
        title="Change MCC"
      />
    </PermissionTooltip>
  );
}
 
export default memo(MCCInput);