All files / src/components/AcquirerEnterprises/EnterprisePreview/modals EditEnterpriseMCCNew.tsx

71.01% Statements 49/69
61.9% Branches 26/42
50% Functions 14/28
73.43% Lines 47/64

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 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373                                                                1x   21x 21x 21x 21x 21x   21x           21x       21x                           21x 441x       1x 1x 1x 1x   21x 21x   1x 1x 1x                     1x   21x 21x 21x 3x 3x   21x                                 21x     21x       21x 21x   21x                                                                                                                                                                 4x                       18x 108x   18x                                                                                         84x                                                       1x               4x         1x                         32x 32x   32x 32x                                                                 1x 65x 32x                          
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { BoxProps, Stack, styled } from "@mui/material";
import { Button } from "@common/Button";
import { useState } from "react";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { useUpdateMerchantInfo } from "@components/Merchants/MerchantPreview/hooks/useUpdateMerchantInfo";
import EditMerchantBaseModal from "@components/Merchants/MerchantPreview/components/EditMerchantBaseModal";
import { TCategoryCode } from "@components/Merchants/MerchantPreview/data.types";
import { Virtuoso } from "react-virtuoso";
import CategoryItem from "@components/AcquirerEnterprises/EnterprisePreview/components/CategoryItem";
import { keyframes } from "@mui/material/styles";
import { useDebouncedCallback } from "use-debounce";
import { Box } from "@mui/material";
import { MinusIcon, PlusIcon, SpinnerIcon } from "@phosphor-icons/react";
import NoResultsState from "@common/EmptyState/NoResultsState";
import MCCSearchInput from "@components/AcquirerEnterprises/EnterprisePreview/modals/MCCSearchInput";
import { EDIT_ENTERPRISE_MCC_MODAL } from "modals/modal_names";
import { Text } from "@common/Text";
import { palette } from "@palette";
import { isEmpty } from "lodash";
import { Tooltip } from "@common/Tooltip";
import { WithTooltipWrapper } from "@common/Menu/NewDropdownMenu";
import useGetEnterpriseCategoryCodes from "@hooks/enterprise-api/merchants/useGetEnterpriseCategoryCodes";
import { useGetCurrentMerchantId } from "@hooks/common";
 
interface ModalProps {
  id: number;
  categories: TCategoryCode[];
  parentCategories: TCategoryCode[];
  onClose?: (data: any) => void;
}
 
const EditEnterpriseMCCNew = NiceModal.create(
  ({ id, categories = [], parentCategories, onClose }: ModalProps) => {
    const [search, setSearch] = useState("");
    const { merchantId: acquirerID } = useGetCurrentMerchantId();
    const [placeholderSearch, setPlaceholderSearch] = useState("");
    const [isLoadingSearch, setIsLoading] = useState(false);
    const [added, setAdded] = useState<TCategoryCode[]>(categories);
    const [filteredParentCategories, setFilteredParentCategories] =
      useState<TCategoryCode[]>(parentCategories);
 
    const {
      data: infiniteCategories,
      total,
      onEndReached,
    } = useGetEnterpriseCategoryCodes({
      id: acquirerID,
      searchKey: search,
    });
    const debounced = useDebouncedCallback((value) => {
      setFilteredParentCategories(
        parentCategories.filter((c) => {
          return (
            c.code.includes(value) ||
            c.title.toLowerCase().includes(value.toLowerCase()) ||
            value === ""
          );
        }),
      );
      setIsLoading(false);
      setPlaceholderSearch(value);
    }, 1000);
 
    const availableItems = filteredParentCategories?.filter(
      (item) => !added.some((cat) => cat.id === item.id),
    );
 
    function handleSearch(e: React.ChangeEvent<HTMLInputElement>) {
      const value = e.target.value;
      setSearch(value);
      setIsLoading(true);
      debounced(e.target.value);
    }
    const { isMobileView } = useCustomTheme();
    const { handleSubmit, isLoading } = useUpdateMerchantInfo(id);
    function submit() {
      if (onClose) {
        onClose(added);
        handleCancel();
      } else E{
        const addedIds = added.map((c) => c.id);
        handleSubmit(
          "categories",
          {
            categories: addedIds,
          },
          handleCancel,
        );
      }
      return;
    }
    const modal = useModal(EDIT_ENTERPRISE_MCC_MODAL);
    const open = modal.visible;
    const handleCancel = () => {
      modal.hide();
      isMobileView && modal.remove();
    };
    const onAnimationEnd = () => {
      modal.remove();
    };
    function handleAdd(id: TCategoryCode["id"]) {
      const category = parentCategories.find((c) => c.id === id);
      if (category) {
        setAdded((prev) => {
          return [...prev, category];
        });
      }
    }
    function handleRemove(id: TCategoryCode["id"]) {
      setAdded((prev) => {
        return prev.filter((c) => c.id !== id);
      });
    }
 
    const handleAddAll = () => {
      setAdded(parentCategories);
    };
    const handleRemoveAll = () => {
      setAdded([]);
    };
 
    const isAddedEmpty = isEmpty(added);
    const areAllAdded = isEmpty(availableItems);
 
    return (
      <EditMerchantBaseModal
        onAnimationEnd={onAnimationEnd}
        title="Add Merchant Category Codes (MCC)"
        description="Choose the categories this Provider can assign to its merchants"
        open={open}
        handleCancel={handleCancel}
        sx={{
          "& .MuiPaper-root": {
            width: "928px !important",
            maxWidth: "928px !important",
          },
        }}
        actions={
          <>
            <Button
              size="medium"
              background="tertiary"
              onClick={handleCancel}
              disabled={isLoading}
              sx={{
                padding: "8px 24px",
                ...(isMobileView && {
                  width: "50%",
                }),
              }}
            >
              Cancel
            </Button>
            <Tooltip
              disableHoverListener={!isAddedEmpty}
              title="Add at least one MCC code"
            >
              <Button
                size="medium"
                background="primary"
                form="edit-merchant-info-form"
                disabled={isLoading || isAddedEmpty}
                sx={{
                  padding: "8px 24px",
                  ...(isMobileView && {
                    width: "50%",
                  }),
                }}
                onClick={submit}
              >
                Save
              </Button>
            </Tooltip>
          </>
        }
      >
        <Stack
          direction="column"
          id="edit-merchant-info-form"
          gap={2}
          height="100%"
        >
          <MCCSearchInput value={search} onChange={handleSearch} />
          <Stack
            direction={isMobileView ? "column" : "row"}
            gap={2}
            height="100%"
          >
            <Container
              hideButton={areAllAdded}
              total={total || 0}
              onClick={handleAddAll}
            >
              <Virtuoso
                style={{
                  height: "100%",
                  width: "100%",
                  opacity: isLoadingSearch ? 0.5 : 1,
                  transition: "opacity 0.3s ease-in-out",
                }}
                endReached={onEndReached}
                components={{
                  ...(!isEmpty(search) &&
                    isEmpty(infiniteCategories) && {
                      EmptyPlaceholder: () => (
                        <NoResultsState
                          sx={{
                            height: "100%",
                            width: "100%",
                          }}
                          searchQuery={placeholderSearch}
                        />
                      ),
                    }),
                }}
                data={infiniteCategories}
                itemContent={(_, c) => {
                  const isSelected = Boolean(
                    added.find((a) => a.id === c.categoryCodes.id),
                  );
                  return (
                    <WithTooltipWrapper
                      hasTooltip={c.isAllowed !== undefined}
                      tooltipProps={{
                        show: !c.isAllowed,
                        message: "Not available for your organisation",
                      }}
                    >
                      <CategoryItem
                        key={c.categoryCodes.id}
                        code={c.categoryCodes.code}
                        riskStatus={
                          c.categoryCodes.merchantRiskStatus as
                            | "high"
                            | "normal"
                            | "restricted"
                        }
                        title={c.categoryCodes.title}
                        onClick={() =>
                          isSelected
                            ? handleRemove(c.categoryCodes.id)
                            : handleAdd(c.categoryCodes.id)
                        }
                        isSelected={isSelected}
                        isAllowed={c.isAllowed}
                      />
                    </WithTooltipWrapper>
                  );
                }}
              />
              {isLoadingSearch && <StyledSpinner />}
            </Container>
            <Container
              total={added?.length || 0}
              type="remove"
              onClick={handleRemoveAll}
              hideButton={isAddedEmpty}
            >
              <Virtuoso
                style={{
                  height: "100%",
                  width: "100%",
                }}
                data={added}
                itemContent={(_, c) => (
                  <WithTooltipWrapper
                    hasTooltip={c.isAllowed !== undefined}
                    tooltipProps={{
                      show: !c.isAllowed,
                      message: "Not available for your organisation",
                    }}
                  >
                    <CategoryItem
                      key={c.id}
                      riskStatus={c.riskStatus}
                      code={c.code}
                      title={c.title}
                      onClick={() => handleRemove(c.id)}
                      isOnlyRemaining={added.length === 1}
                      isAllowed={c.isAllowed}
                      added
                    />
                  </WithTooltipWrapper>
                )}
              />
            </Container>
          </Stack>
        </Stack>
      </EditMerchantBaseModal>
    );
  },
);
 
const fadeIn = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;
const StyledSpinner = styled(SpinnerIcon)(() => ({
  animation: `${fadeIn} 250ms ease-in-out`,
  position: "absolute",
}));
 
const Container = ({
  children,
  onClick,
  type = "add",
  total,
  hideButton,
}: {
  children: React.ReactNode;
  onClick: () => void;
  type?: "add" | "remove";
  total: number;
  hideButton?: boolean;
}) => {
  const { isMobileView } = useCustomTheme();
  const isAvailableBox = type === "add";
 
  const Icon = isAvailableBox ? PlusIcon : MinusIcon;
  return (
    <Stack flex={1}>
      <Stack
        justifyContent="space-between"
        alignItems="center"
        flexDirection="row"
        mb="12px"
      >
        <Text color={palette.black[100]} fontSize="14px">
          {isAvailableBox ? "All" : "Added"} {total}
        </Text>
        {!hideButton && (
          <Stack
            sx={{
              cursor: "pointer",
            }}
            gap="4px"
            alignItems="center"
            flexDirection="row"
            onClick={onClick}
          >
            <Icon size="20px" fill={palette.givebox[600]} />
            <Text color={palette.givebox[600]} fontSize="14px">
              {isAvailableBox ? "Add All" : "Remove All"}
            </Text>
          </Stack>
        )}
      </Stack>
      <StyledBox isMobile={isMobileView}>{children}</StyledBox>
    </Stack>
  );
};
 
const StyledBox = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isMobile",
})<BoxProps & { isMobile?: boolean }>(({ theme, isMobile }) => ({
  height: isMobile ? "100%" : "400px",
  width: "100%",
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  alignItems: "center",
  padding: "12px",
  border: `1px solid ${theme.palette.neutral[10]}`,
  borderRadius: "8px",
}));
 
export default EditEnterpriseMCCNew;