All files / src/components/Merchants/BulkInvite/hooks useCsvImport.ts

69.6% Statements 71/102
42.5% Branches 17/40
78.94% Functions 15/19
73.03% Lines 65/89

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                7x   2x   2x                   2x 69x 69x 69x 69x 69x 69x   69x   69x 10x 10x 10x 10x 10x       69x   7x 7x 7x   7x                 7x   7x 70x 70x 6x 6x     70x                     69x   7x 7x 7x                         69x                                     69x   7x         7x 7x     18x 7x       7x 7x     7x   7x 7x 7x 7x                   69x   7x 7x     7x   7x           7x       7x 7x 7x 7x           69x                         69x 15x 15x 15x 15x 15x     69x                      
import { IDropzoneProps } from "react-dropzone-uploader";
import { useEffect, useRef, useState, useCallback } from "react";
import { TImportedRow } from "../types";
import { parseCsv } from "../utils/parseCsv";
import { isEmpty } from "lodash";
import { useUploadProgress } from "@redux/slices/uploadProgressSlice";
import { getRandomNumber } from "@utils/helpers";
 
const isCsv = (file: File) => file.type === "text/csv";
 
const MIN_UPLOAD_TIME = 1500;
 
const localErrorStates = [
  "rejected_file_type",
  "rejected_max_files",
  "error_file_size",
  "error_validation",
  "error_upload_params",
  "aborted",
  "error_upload",
];
 
const useCsvImport = () => {
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { setUploadProgress } = useUploadProgress();
  const currentUploadKey = useRef<string | null>(null);
  const progressInterval = useRef<NodeJS.Timeout | null>(null);
  const isCanceled = useRef<boolean>(false);
 
  const importedRows = useRef<TImportedRow[]>([]);
 
  useEffect(() => {
    return () => {
      setUploadedFile(null);
      importedRows.current = [];
      setIsLoading(false);
      if (progressInterval.current) clearInterval(progressInterval.current);
    };
  }, []);
 
  const onUploadStart = useCallback(
    (file: File) => {
      const key = `${getRandomNumber(1000000, 100000000)}`;
      currentUploadKey.current = key;
      let currentProgress = 0;
 
      setUploadProgress({
        key,
        data: {
          fileName: file.name,
          size: file.size,
          progress: currentProgress,
        },
      });
 
      Iif (progressInterval.current) clearInterval(progressInterval.current);
 
      progressInterval.current = setInterval(() => {
        currentProgress += Math.floor(Math.random() * 10) + 5;
        if (currentProgress >= 90) {
          Eif (progressInterval.current) clearInterval(progressInterval.current);
          currentProgress = 90;
        }
 
        setUploadProgress({
          key,
          data: {
            progress: currentProgress,
          },
        });
      }, 150);
    },
    [setUploadProgress],
  );
 
  const onUploadSuccessInternal = useCallback(
    (fileName: string) => {
      Eif (progressInterval.current) clearInterval(progressInterval.current);
      Eif (currentUploadKey.current) {
        setUploadProgress({
          key: currentUploadKey.current,
          data: {
            fileName,
            success: true,
            progress: 100,
          },
        });
      }
    },
    [setUploadProgress],
  );
 
  const onUploadErrorInternal = useCallback(
    (fileName: string) => {
      if (progressInterval.current) clearInterval(progressInterval.current);
      if (currentUploadKey.current) {
        setUploadProgress({
          key: currentUploadKey.current,
          data: {
            fileName,
            failed: true,
          },
        });
      }
      setUploadedFile(null);
      importedRows.current = [];
      setIsLoading(false);
    },
    [setUploadProgress],
  );
 
  const validateCsv = useCallback(
    (file: File) => {
      Iif (!isCsv(file)) {
        onUploadErrorInternal(file.name);
        return;
      }
 
      const parsePromise = new Promise((resolve, reject) => {
        parseCsv(
          file,
          () => reject(),
          (element) => importedRows.current.push(element),
          () => resolve(undefined),
        );
      });
 
      const minUploadPromise = new Promise((resolve) => {
        setTimeout(resolve, MIN_UPLOAD_TIME);
      });
 
      Promise.allSettled([parsePromise, minUploadPromise])
        .then(() => {
          Iif (isCanceled.current) return;
          setUploadedFile(file);
          onUploadSuccessInternal(file.name);
          setIsLoading(false);
        })
        .catch(() => {
          if (isCanceled.current) return;
          onUploadErrorInternal(file.name);
        });
    },
    [onUploadSuccessInternal, onUploadErrorInternal],
  );
 
  const handleChangeStatus: IDropzoneProps["onChangeStatus"] = useCallback(
    ({ file, remove }: any, status: any) => {
      isCanceled.current = false;
      Iif (!isEmpty(importedRows.current)) {
        remove();
      }
      setIsLoading(true);
 
      Iif (file.name === uploadedFile?.name) {
        if (remove) remove();
        onUploadErrorInternal(file.name);
        return;
      }
 
      Iif (localErrorStates.includes(status)) {
        onUploadStart(file);
        if (remove) remove();
        onUploadErrorInternal(file.name);
      } else Eif (status === "done") {
        onUploadStart(file);
        validateCsv(file);
        Eif (remove) remove();
      }
    },
    [uploadedFile, validateCsv, onUploadStart, onUploadErrorInternal],
  );
 
  const handleReplace = useCallback(
    (file: File) => {
      isCanceled.current = false;
      importedRows.current = [];
 
      if (isLoading) return;
      setIsLoading(true);
      onUploadStart(file);
      validateCsv(file);
    },
    [isLoading, validateCsv, onUploadStart],
  );
 
  const resetState = useCallback(() => {
    isCanceled.current = true;
    setUploadedFile(null);
    importedRows.current = [];
    setIsLoading(false);
    if (progressInterval.current) clearInterval(progressInterval.current);
  }, []);
 
  return {
    handleChangeStatus,
    handleReplace,
    reset: resetState,
    uploadedFile,
    importedRows: importedRows.current,
    isLoading,
  };
};
 
export default useCsvImport;