All files / src/features/GiveOnboarding/modals SelfieModal.tsx

84.21% Statements 32/38
63.33% Branches 19/30
85.71% Functions 6/7
83.78% Lines 31/37

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                                      10x                             23x 23x 23x 23x 23x                     23x 23x 9x 1x   8x       23x   23x 1x 1x 1x       23x 1x       1x 1x                         1x       1x 1x 1x             23x           1x 1x 1x                     23x                 46x 28x                                                                                                                                                            
import { challengeSlugs } from "@constants/challengeSlugs";
import {
  QKEY_GET_MERCHANT_BY_ID,
  QKEY_IDENTIFICATION_FILES,
} from "@constants/queryKeys";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useUploadFiles } from "@hooks/upload-api/uploadHooks";
import { Box, Stack } from "@mui/material";
import useManageCamera from "@sections/VerifyAccountHolder_v2/hooks/useManageCamera";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { base64ToFile } from "@utils/helpers";
import { checkPortals } from "@utils/routing";
import React, { Dispatch, SetStateAction, useEffect } from "react";
import { useQueryClient } from "react-query";
import { buttonText, modalTitle, uploadAttachmentType } from "../consts";
import { showMessage } from "@common/Toast";
 
const UPLOAD_FAILED = "Upload failed. Please try again.";
 
function SelfieModal({
  open,
  setOpenModal,
  uploadType = "selfie",
  bankAccountID,
  config,
}: {
  open: boolean;
  setOpenModal: Dispatch<SetStateAction<boolean>>;
  uploadType?: "selfie" | "bankPicture";
  bankAccountID?: number | string;
  config?: MediaStreamConstraints;
}) {
  const { isMobileView } = useCustomThemeV2();
  const { handleUpload, isLoading } = useUploadFiles();
  const { merchantId } = useGetCurrentMerchantId();
  const { isMerchantPortal } = checkPortals();
  const queryClient = useQueryClient();
 
  const {
    videoRef,
    canvasRef,
    image,
    takePicture,
    stopCamera,
    requestCameraAccess,
    setImage,
    disabled,
  } = useManageCamera(config);
  useEffect(() => {
    if (open) {
      requestCameraAccess();
    } else {
      stopCamera();
    }
  }, [open]);
 
  const isImageTaken = !!image;
 
  const closeModal = () => {
    stopCamera();
    setImage(null);
    setOpenModal(false);
  };
 
  //handle errors that might occur during the image upload
  const handleUploadTakenImage = async () => {
    Iif (!image) {
      // no image to upload, we return early
      return;
    }
    try {
      const result = await handleUpload(
        {
          list: [
            { file: base64ToFile(image, uploadAttachmentType[uploadType]) },
          ],
          merchantId: merchantId,
          resourceID: bankAccountID ? Number(bankAccountID) : merchantId,
          attachmentType: uploadAttachmentType[uploadType],
          label: "",
          tag: `${isMerchantPortal ? "merchant" : "provider"} upload`,
        },
        challengeSlugs.PRIMARY_5,
      );
      Iif (result === "upload_failed") {
        showMessage("Error", UPLOAD_FAILED);
        return;
      }
      queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]);
      queryClient.invalidateQueries(QKEY_GET_MERCHANT_BY_ID);
      closeModal();
    } catch (error: any) {
      const message =
        error?.response?.data?.message || error?.message || UPLOAD_FAILED;
      showMessage("Error", message);
    }
  };
  const buttonsArray = [
    {
      label: buttonText[uploadType].retake,
      variant: "ghost",
      hidden: !isImageTaken,
      onClick: () => {
        setImage(null);
        stopCamera();
        requestCameraAccess();
      },
    },
    {
      label: isImageTaken
        ? buttonText[uploadType].finish
        : buttonText[uploadType].shootImage,
      variant: "filled",
      onClick: isImageTaken ? handleUploadTakenImage : takePicture,
    },
  ];
  return (
    <>
      <GiveBaseModal
        showHeader
        showFooter
        open={open}
        buttons={
          <Stack flexDirection="row">
            {buttonsArray?.map(({ label, variant, hidden, onClick }) => {
              if (hidden) return null;
              return (
                <GiveButton
                  key={label}
                  label={label}
                  size="large"
                  variant={variant as any}
                  onClick={onClick}
                  disabled={isLoading || disabled}
                  sx={{
                    whiteSpace: "nowrap",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                  }}
                />
              );
            })}
          </Stack>
        }
        title={modalTitle[uploadType]}
        width={isMobileView ? "100%" : "720px"}
        PaperProps={{
          style: {
            height: isMobileView ? "auto" : "578px",
            maxWidth: "720px",
          },
        }}
        BackdropProps={{
          style: {
            backdropFilter: "blur(4px)",
          },
        }}
        maxWidth="xl"
        onClose={() => {
          !isLoading && closeModal();
        }}
      >
        <>
          <Stack
            data-testid="Video-stream-Container"
            gap="115px"
            alignItems="center"
            justifyContent="space-between"
          >
            <Box
              borderRadius="16px"
              height="400px"
              overflow="hidden"
              width="100%"
            >
              {isImageTaken ? (
                <img
                  width="100%"
                  height="100%"
                  src={image}
                  style={{ objectFit: "cover", background: "black" }}
                />
              ) : (
                <>
                  <video
                    width="100%"
                    height="100%"
                    ref={videoRef}
                    autoPlay
                    playsInline
                    style={{ objectFit: "cover", background: "black" }}
                  />
                </>
              )}
              <canvas ref={canvasRef} style={{ display: "none" }} />
            </Box>
          </Stack>
        </>
      </GiveBaseModal>
    </>
  );
}
 
export default SelfieModal;