All files / src/features/GiveOnboarding/pages/Identity/PhotoWithId index.tsx

70.37% Statements 38/54
38.23% Branches 13/34
66.66% Functions 8/12
73.07% Lines 38/52

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                                                                                                                          9x 13x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x   12x   12x                 12x 12x     12x               12x 4x     12x   4x             2x 2x                                                 12x     12x   12x 3x 3x 1x   2x           12x                                               12x         12x                                                                 12x 8x                                                                                 1x                                                                               12x                                                       9x    
import PhotoWithIdIcon from "@assets/icons/PhotoWithIdIcon";
 
import {
  CenterIconContainer,
  CustomQRCode,
  DocumentSection,
  ErrorTextComponent,
  InstructionsList,
  PagesContainer,
} from "../../pages.atoms";
import { WebcamIcon } from "@phosphor-icons/react";
import { Box, Stack } from "@mui/material";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import GiveButton from "@shared/Button/GiveButton";
import GiveDivider from "@shared/GiveDivider/GiveDivider";
import TaskCard from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/TaskCard";
import {
  useGetIdentificationFiles,
  useGetSelfieOTC,
} from "@sections/VerifyAccountHolder_v2/hooks/useCamera";
import {
  Dispatch,
  forwardRef,
  SetStateAction,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import { TMerchantDocument } from "@components/Merchants/MerchantPreview/data.types";
import { isEmpty } from "lodash";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import SelfieModal from "../../../modals/SelfieModal";
import { IStep } from "../../../types";
import { checkIfCameraExists } from "@sections/VerifyAccountHolder_v2/hooks/useManageCamera";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { IOnSubmitOptions } from "@features/GiveOnboarding/types/handlers";
import { FormLoader } from "@features/GiveOnboarding/components/loaders/FormLoader";
import { useQueryClient } from "react-query";
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import {
  AcceptAllowedImagesTypes,
  MAX_UPLOAD_SIZE,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import {
  QKEY_GET_MERCHANT_BY_ID,
  QKEY_IDENTIFICATION_FILES,
} from "@constants/queryKeys";
import { challengeSlugs } from "@constants/challengeSlugs";
import { uploadAttachmentType } from "@features/GiveOnboarding/consts";
import useMasqueradeReducer from "@hooks/Reducers/useMasqueradeReducer";
 
interface Props {
  data_key: IStep;
  setIsEmptySelfie: Dispatch<SetStateAction<boolean>>;
  merchantId: string;
  userFullName?: string;
  handleAutoNavigate: () => void;
}
 
const PhotoWithId = forwardRef((props: Props, ref: any) => {
  const { handleAutoNavigate } = props;
  const theme = useAppTheme();
  const [isFormError, setIsFormError] = useState(false);
  const [openModal, setOpenModal] = useState(false);
  const { isMobileView } = useCustomThemeV2();
  const [hasCamera, setHasCamera] = useState(false);
  const queryClient = useQueryClient();
  const { handleUpload, isLoading: uploadLoading } = useUploadFiles();
  const { isMasqueradeMode, origin } = useMasqueradeReducer();
  const isMasqueradeFromAcquirer = origin === "/acquirer/merchants";
 
  const tagPrefix = isMasqueradeFromAcquirer ? "Acquirer" : "Provider";
 
  const merchantId = Number(props.merchantId);
 
  const { isLoading: isLoadingFiles, data } = useGetIdentificationFiles({
    pollUntilDataFound: true,
    onSuccess: async (data: any) => {
      const files = (data?.data as TMerchantDocument[]) || [];
      if (files?.length > 0) setIsFormError(false);
    },
    filter: `?filter=attTypeName:"account_owner_selfie"%3BisUploaded:true`,
  });
 
  const ownerFiles = data?.data as TMerchantDocument[];
  const ownerHasNoFiles = isEmpty(ownerFiles);
 
  const CustomDivider = (
    <GiveDivider
      sx={{
        flex: 1,
        bgcolor: theme.palette.primitive?.transparent["darken-5"],
      }}
    />
  );
 
  useEffect(() => {
    props.setIsEmptySelfie?.(isMobileView && isEmpty(ownerFiles));
  }, [ownerFiles, isMobileView]);
 
  useImperativeHandle(
    ref,
    () => ({
      data_key: props.data_key,
      submit: ({
        onInvalid,
        onSubmitValidated,
        onValid,
      }: IOnSubmitOptions<any>) => {
        if (ownerFiles?.length) {
          onValid?.({});
        } else E{
          if (isMobileView) {
            setOpenModal(true);
          } else {
            setIsFormError(true);
            onInvalid?.({
              type: "formValidation",
              error: {
                account_owner: {
                  message: "Uploading an identification document is required",
                },
              },
            });
          }
        }
      },
    }),
    [props.data_key, ownerFiles, ownerHasNoFiles],
  );
 
  const {
    data: otcData,
    isError,
    isLoading,
  } = useGetSelfieOTC({
    enabled: true,
  });
  const LINK = `https://${window.location.hostname}/make_selfie?token=${otcData?.token}&exp_date=${otcData?.expiresdAt}`;
 
  useEffect(() => {
    checkIfCameraExists().then((hasCamera) => {
      if (hasCamera) {
        setHasCamera(true);
      } else {
        setHasCamera(false);
      }
    });
  }, []);
 
  // Upload handler
  const uploadFunction = async (files: File | File[]) => {
    const fileArray = Array.isArray(files) ? files : [files];
    const file = fileArray[0]; // single-file only
    if (!file) return;
 
    await handleUpload(
      {
        list: [{ file }],
        merchantId: merchantId,
        resourceID: merchantId,
        attachmentType: uploadAttachmentType["selfie"],
        label: "",
        tag: `${isMasqueradeMode ? tagPrefix : "Merchant"} Upload`,
      },
      challengeSlugs.PRIMARY_5,
    );
    await Promise.all([
      queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]),
      queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]),
    ]);
    handleAutoNavigate();
  };
 
  // Helper to invalidate queries on delete
  const handleDeleteSuccess = () => {
    queryClient.invalidateQueries(["onboarding-progress", merchantId]);
  };
 
  // Render masquerade mode view
  const renderMasqueradeView = () => (
    <TaskCard title="Selfie with ID image" containerSx={{ width: "100%" }}>
      {!ownerHasNoFiles ? (
        <DocumentSection
          ownerFiles={ownerFiles}
          userFullName={props?.userFullName}
          onDeleteSuccess={handleDeleteSuccess}
          allowDelete
        />
      ) : (
        <GiveUploadArea
          height="113px"
          message={`Max. 1 file, up to ${MAX_UPLOAD_SIZE.label} each (.png, .jpg, .jpeg, .webp, .heic)`}
          disabled={uploadLoading}
          uploadFunction={uploadFunction}
          accept={AcceptAllowedImagesTypes}
          maxFiles={1}
          maxSizeInBytes={MAX_UPLOAD_SIZE.value}
          backgroundColor="transparent"
          title="Upload file"
          showSelectFileButton={false}
          iconBg={theme.palette.primitive?.transparent["darken-5"]}
          warningText={
            isFormError
              ? "Uploading an identification document is required"
              : ""
          }
        />
      )}
    </TaskCard>
  );
 
  // Render standard mode view
  const renderStandardView = () => (
    <>
      {!ownerHasNoFiles ? (
        <TaskCard title="Attachments">
          <DocumentSection
            userFullName={props?.userFullName}
            ownerFiles={ownerFiles}
            onDeleteSuccess={handleDeleteSuccess}
            allowDelete={!isMasqueradeMode}
          />
        </TaskCard>
      ) : (
        <>
          {!isMobileView && (
            <Box
              borderRadius="20px"
              bgcolor={theme.palette.primitive?.transparent["darken-5"]}
              p="24px"
            >
              <Stack alignItems="center" flexDirection="row" gap="24px">
                <Box height={30} width={30}>
                  <WebcamIcon size={28} />
                </Box>
                <GiveText>
                  Allow camera access on your computer and take the photo.
                </GiveText>
                <GiveTooltip
                  title="Your device has no camera"
                  placement="top"
                  disableHoverListener={hasCamera}
                  fluidWidth
                >
                  <GiveButton
                    sx={{
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}
                    size="large"
                    disabled={!hasCamera}
                    variant="outline"
                    label="Allow Access"
                    onClick={() => setOpenModal(true)}
                  />
                </GiveTooltip>
              </Stack>
              <Stack
                my="18px"
                gap="8px"
                width="100%"
                alignItems="center"
                flexDirection="row"
              >
                {CustomDivider}
                <GiveText
                  sx={{
                    color: theme.palette.text.tertiary,
                  }}
                  fontSize="12px"
                >
                  OR
                </GiveText>
                {CustomDivider}
              </Stack>
 
              <Stack gap="24px" alignItems="center" flexDirection="row">
                <CustomQRCode
                  value={LINK}
                  isLoading={isLoading}
                  isError={isError}
                />
 
                <GiveText fontSize="14px">
                  Scan the QR code with your smartphone and capture the photo.
                </GiveText>
              </Stack>
            </Box>
          )}
        </>
      )}
    </>
  );
  return (
    <>
      <PagesContainer>
        {isLoadingFiles ? (
          <FormLoader />
        ) : (
          <Box>
            <CenterIconContainer>
              <PhotoWithIdIcon />
            </CenterIconContainer>
            <InstructionsList />
            {isFormError && (
              <ErrorTextComponent errorText="  Taking a selfie is required." />
            )}
            {isMasqueradeMode ? renderMasqueradeView() : renderStandardView()}
          </Box>
        )}
      </PagesContainer>
 
      <SelfieModal
        setOpenModal={setOpenModal}
        open={openModal}
        config={{ video: { facingMode: { ideal: "user" } } }}
      />
    </>
  );
});
 
PhotoWithId.displayName = "PhotoWithId";
export default PhotoWithId;