All files / src/components/UploadFile NotificationStackMobile.tsx

69.23% Statements 45/65
67.39% Branches 31/46
52.63% Functions 10/19
69.35% Lines 43/62

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                                                            2x   32x   32x 32x 32x   32x 32x                         2x 32x               32x     32x   32x   32x 32x   32x 32x 32x   32x 58x           42x     42x     32x 14x   18x     32x             32x                     32x                                                           32x   32x   32x     34x               32x 4x   28x     32x   28x                                                                         58x                                               2x                     58x   58x                                                                                   2x                 28x                                                                         28x                    
import { FileUploadIcon } from "@assets/icons";
 
import { CircularProgress, Stack } from "@mui/material";
import { Box } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { palette } from "@palette";
import { Text, TruncateText } from "@common/Text";
import {
  useGetUploadProgress,
  useUploadProgress,
} from "@redux/slices/uploadProgressSlice";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useDeleteFile } from "@hooks/upload-api/useDeleteFile";
import { bytesToSize } from "@utils/index";
import UploadIconThick from "@assets/rebrandIcons/UploadIconThick";
import { styled } from "@mui/material";
import { Button } from "@common/Button";
import ModalFactory from "@common/Modal/ModalFactory/ModalFactory";
import {
  FileStatus,
  getFileStatus,
  getRightSideStatus,
  Right,
  UploadSnackbarLinearProgress,
} from "@components/UploadFile/NotificationStack";
import { useDebouncedCallback } from "use-debounce";
import { useDeleteAccountFile } from "@hooks/upload-api/useDeleteAccountFile";
import { useQueryClient } from "react-query";
import { ProgressItem } from "@redux/slices/uploadProgressSlice/types";
 
const useMatchQueriesProgress = () => {
  const { mutateAsync: deleteFile, isLoading: isLoadingDelete } =
    useDeleteFile();
  const { mutateAsync: deleteAccountFile, isLoading: isLoadingAccountDelete } =
    useDeleteAccountFile();
  const { merchantId } = useGetCurrentMerchantId();
  const progress = useGetUploadProgress();
  const { deleteUploadProgress, hideUploadProgress, setUploadProgress } =
    useUploadProgress();
  return {
    progress,
    deleteUploadProgress,
    hideUploadProgress,
    setUploadProgress,
    merchantId,
    deleteFile,
    isLoadingDelete,
    deleteAccountFile,
    isLoadingAccountDelete,
  };
};
 
const NotificationStackMobile = () => {
  const queryClient = useQueryClient();
  const {
    progress,
    hideUploadProgress,
    deleteFile,
    deleteAccountFile,
    merchantId,
    setUploadProgress,
  } = useMatchQueriesProgress();
  //
 
  const [openModal, setOpenModal] = useState(false);
 
  const items = progress;
  //
  const isUploadFailed = false;
  const progressKeys = Object.keys(progress);
 
  const fileUploadAverageProgress = useMemo(() => {
    let totalProgress = 0;
    let totalSize = 0;
 
    progressKeys.forEach((key) => {
      if (
        progress &&
        progress[key].progress &&
        progress[key].size &&
        !progress[key].tooLarge
      ) {
        totalProgress =
          totalProgress +
          (progress?.[key]?.progress || 0) * (progress?.[key]?.size || 0);
        totalSize = totalSize + (progress?.[key]?.size || 0);
      }
    });
    if (totalSize === 0) {
      return 0;
    }
    return totalProgress / totalSize || 0;
  }, [progress]);
 
  const hideSnackbar = () => {
    if (openModal) return;
    Object.keys(items).forEach((key) => {
      hideUploadProgress(key);
    });
  };
 
  const handleCancel = (key: string) => {
    const item = items[key];
    item.abortController?.abort();
    setUploadProgress({
      key,
      data: {
        canceled: true,
      },
    });
  };
 
  const handleDelete = async (key: string) => {
    const item = items[key];
 
    try {
      if (item.accountUpload && item.id) {
        await deleteAccountFile({
          fileID: item.id,
          id: item.accountID,
        });
        if (item.refetcherKey) {
          queryClient.invalidateQueries(item.refetcherKey);
        }
      } else {
        await deleteFile({
          accountToRequest: merchantId.toString(),
          identifier: item.id as string,
        });
      }
 
      setUploadProgress({
        key,
        data: {
          deleted: true,
        },
      });
    } catch {
      // failed to delete notification?
    }
  };
 
  const hide = useDebouncedCallback(hideSnackbar, 2500);
 
  useEffect(() => {
    const noCurrentUploading =
      Object.values(items).length >= 1 &&
      Object.values(items).every(
        (item) =>
          item.success ||
          item.failed ||
          item.canceled ||
          item.tooLarge ||
          item.unsuported ||
          item.tooManyFiles,
      );
 
    if (noCurrentUploading && !openModal) {
      hide();
    } else {
      hide.cancel();
    }
  }, [progress, hideUploadProgress, openModal, items]);
  if (progressKeys.length < 1) return null;
 
  return (
    <>
      {!openModal && (
        <UploadStatusButton
          onClick={() => setOpenModal(true)}
          isUploadFailed={isUploadFailed}
          fileUploadAverageProgress={fileUploadAverageProgress}
        />
      )}
      <ModalFactory
        variant="dialog"
        renderMobile
        modalProps={{
          sx: { zIndex: 1300 },
          open: openModal,
          onClose: () => setOpenModal(false),
          DrawerProps: {
            dataTestId: "uploading-files-drawer",
          },
        }}
      >
        <Puller />
        <Text
          color="#575353"
          textAlign="center"
          fontWeight="book"
          fontSize="18px"
          pb="20px"
        >
          Uploads
        </Text>
        <Stack
          flex={1}
          gap={2}
          sx={{ overflowX: "scroll", px: "12px", pb: "90px", pt: "8px" }}
        >
          {Object.keys(items).map((key) => {
            return (
              <IndividualCard
                key={key}
                id={key}
                item={items[key]}
                handleDelete={() => handleDelete(key)}
                handleCancel={() => handleCancel(key)}
              />
            );
          })}
        </Stack>
        <Stack bottom="20px" position="absolute" pt="20px" width="100%">
          <Button
            onClick={() => setOpenModal(false)}
            sx={{ width: "170px", margin: "auto" }}
          >
            Close
          </Button>
        </Stack>
      </ModalFactory>
    </>
  );
};
 
const IndividualCard = ({
  item,
  id,
  handleDelete,
  handleCancel,
}: {
  item: ProgressItem;
  id: string;
  handleDelete: () => void;
  handleCancel: () => void;
}) => {
  const { sizeString } = bytesToSize(item.size);
 
  return (
    <Box
      sx={{
        height: "60px",
        width: "100%",
        borderRadius: "8px",
        backgroundColor: palette.neutral.white,
        boxShadow: "0px 3px 15px 0px rgba(2, 2, 2, 0.15)",
        padding: "4px 16px",
      }}
    >
      <Stack direction="column" height="100%" width="100%" alignItems="center">
        <Stack direction="row" height="100%" width="100%" alignItems="center">
          <Box sx={{ mr: "12px" }}>
            <FileUploadIcon />
          </Box>
          <Stack
            direction="column"
            height="100%"
            justifyContent="center"
            width="100%"
            flex={1}
          >
            <TruncateText lineClamp={1}>{item.fileName}</TruncateText>
            <FileStatus status={getFileStatus(item)} />
          </Stack>
          <Right
            type={getRightSideStatus(item).type}
            size={sizeString}
            hovered={true}
            handleDelete={handleDelete}
            handleCancel={handleCancel}
          />
        </Stack>
        <UploadSnackbarLinearProgress item={item} />
      </Stack>
    </Box>
  );
};
 
export default NotificationStackMobile;
 
const UploadStatusButton = ({
  onClick,
  isUploadFailed,
  fileUploadAverageProgress,
}: {
  onClick: () => void;
  isUploadFailed: boolean;
  fileUploadAverageProgress: number;
}) => {
  return (
    <Box
      onClick={onClick}
      position="fixed"
      bottom="60px"
      right="20px"
      zIndex={1301}
      data-testid="file-upload-floating-button"
    >
      <Box
        data-testid="file-upload-floating-button-data"
        sx={{
          height: "52px",
          width: "52px",
          backgroundColor: isUploadFailed ? "#F5E0DF" : "#E6EAF2",
          borderRadius: "26px",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <Box sx={{ position: "absolute", top: "-5px" }}>
          <CircularProgress
            size="62px"
            variant="determinate"
            value={isUploadFailed ? 0 : fileUploadAverageProgress}
            sx={{ color: "#6D9CF8", strokeLinecap: "round" }}
            data-testid="file-upload-floating-button-progress"
          />
        </Box>
 
        <UploadIconThick fill={isUploadFailed ? "#D80D0D" : "#6D9CF8"} />
      </Box>
    </Box>
  );
};
 
const Puller = styled(Box)(() => ({
  width: 52,
  height: 4,
  backgroundColor: "#FDFDFD",
  borderRadius: 3,
  position: "absolute",
  top: "-12px",
  zIndex: 1500,
  left: "calc(50% - 26px)",
}));