All files / src/components/Merchants/BulkInvite/modals GiveCSVBulkImportModal.tsx

68.75% Statements 22/32
60% Branches 12/20
66.66% Functions 6/9
70% Lines 21/30

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                                    16x                 2x               2x         69x 69x 69x               69x   69x 30x 10x       69x 5x 5x 5x     69x                 69x                                           69x                                                                                                                                                     7x 7x 7x 7x                              
import { useEffect } from "react";
import { Box, Stack } from "@mui/material";
import { FileTextIcon } from "@phosphor-icons/react";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import GiveButton from "@shared/Button/GiveButton";
import GiveText from "@shared/Text/GiveText";
import GiveTruncateText from "@shared/Text/GiveTruncateText";
import GiveLink from "@shared/Link/GiveLink";
import { useAppTheme, styled } from "@theme/v2/Provider";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import useCsvImport from "../hooks/useCsvImport";
import { TImportedRow } from "../types";
import NiceModal from "@ebay/nice-modal-react";
import Papa from "papaparse";
import { COLUMN_NAMES, EXAMPLE_CSV_ROWS } from "../constants";
 
const UploadedRow = styled(Stack)(({ theme }) => ({
  flexDirection: "row",
  alignItems: "center",
  gap: "8px",
  borderRadius: theme.customs?.radius?.small ?? "12px",
  padding: "12px 16px",
  background: theme.palette.primitive?.transparent["darken-5"] || "#0000000D",
}));
 
const generateTemplate = () => {
  const csv = Papa.unparse({
    fields: COLUMN_NAMES,
    data: EXAMPLE_CSV_ROWS,
  });
  return "data:text/csv;charset=utf-8," + encodeURI(csv);
};
 
const GiveCSVBulkImport = ({
  handleImport,
}: {
  handleImport: (data: TImportedRow[]) => void;
}) => {
  const { open, onClose } = useNiceModal();
  const { palette } = useAppTheme();
  const { isMobileView } = useCustomThemeV2();
  const {
    handleChangeStatus,
    handleReplace,
    uploadedFile,
    importedRows,
    reset,
    isLoading,
  } = useCsvImport();
 
  useEffect(() => {
    if (open) {
      reset();
    }
  }, [open, reset]);
 
  const handleSubmit = () => {
    handleImport(importedRows);
    reset();
    onClose();
  };
 
  const onDownloadTemplate = () => {
    const href = generateTemplate();
    const a = document.createElement("a");
    a.setAttribute("href", href);
    a.setAttribute("download", "merchants_template.csv");
    a.click();
  };
 
  const footerLeft = (
    <GiveText variant="bodyS" color="secondary">
      Download a{" "}
      <GiveLink
        onClick={onDownloadTemplate}
        sx={{
          cursor: "pointer",
          color: palette.primitive?.blue[100],
          display: "inline",
          textDecoration: "none", // Explicitly remove text-decoration
          borderBottom: `1px solid ${palette.primitive?.blue[100]}`, // Custom underline via border
          "&:hover": {
            textDecoration: "none", // Ensure no text-decoration on hover
            borderBottom: `1px solid ${palette.primitive?.blue[100]}`, // Maintain custom underline on hover
          },
        }}
      >
        sample CSV template
      </GiveLink>{" "}
      to see an example of the format required.
    </GiveText>
  );
 
  return (
    <GiveBaseModal
      open={open}
      onClose={onClose}
      title="Import Merchants by CSV"
      width={isMobileView ? "100%" : "560px"}
      height="fit-content"
      showFooter
      buttons={
        <>
          <GiveButton
            variant="ghost"
            size="large"
            onClick={onClose}
            label="Cancel"
            sx={{
              width: "auto!important",
            }}
            disabled={isLoading} // Disable Cancel button when loading
          />
          <GiveButton
            variant="filled"
            size="large"
            onClick={handleSubmit}
            label="Import"
            sx={{
              width: "auto!important",
            }}
            disabled={!uploadedFile || isLoading} // Disable Import button when loading or no file
            data-testid="import-csv-button"
          />
        </>
      }
    >
      <Box>
        <Box sx={{ mb: "24px" }}>{footerLeft}</Box>
        {uploadedFile ? (
          <UploadedRow>
            <FileTextIcon size={20} color={palette.icon?.["icon-primary"]} />
            <GiveTruncateText
              lineClamp={1}
              variant="bodyM"
              sx={{ flexGrow: 1, minWidth: 0 }}
            >
              {uploadedFile.name}
            </GiveTruncateText>
            <label htmlFor="csv-replace-input">
              <input
                id="csv-replace-input"
                type="file"
                accept="text/csv"
                style={{ display: "none" }}
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) handleReplace(file);
                }}
                disabled={isLoading} // Add disabled attribute here
              />
              <GiveButton
                component="span"
                variant="ghost"
                size="small"
                label="Replace"
                color="light"
                disabled={isLoading}
              />
            </label>
          </UploadedRow>
        ) : (
          <GiveUploadArea
            disabled={isLoading} // Disable GiveUploadArea when loading
            {...(isMobileView && {
              title: "Upload file",
            })}
            uploadFunction={(files) => {
              const file = Array.isArray(files) ? files[0] : files;
              Eif (file) {
                const fileWithMeta = { file, remove: () => {} } as any;
                handleChangeStatus(fileWithMeta, "done", [fileWithMeta]);
              }
            }}
            accept={{ "text/csv": [".csv"] }}
            maxFiles={1}
            maxSizeInBytes={2000000}
            message="CSV format required, max 1,000 merchants"
          />
        )}
      </Box>
    </GiveBaseModal>
  );
};
 
export default NiceModal.create(GiveCSVBulkImport);