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

97.05% Statements 33/34
88.23% Branches 15/17
88.88% Functions 8/9
96.87% Lines 31/32

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                                                                                      9x 19x 18x 18x 18x 18x 18x   18x   18x   12x         18x   18x   12x     2x 1x 1x 1x 1x                           18x   7x 7x       18x 1x 1x     1x                     1x             1x     18x 10x           8x                                                                                                 9x      
import IdIcon from "@assets/icons/IdIcon";
import { TMerchantDocument } from "@components/Merchants/MerchantPreview/data.types";
import { challengeSlugs } from "@constants/challengeSlugs";
import {
  QKEY_BUSINESS_PROFILE_BY_ID,
  QKEY_GET_MERCHANT_BY_ID,
  QKEY_IDENTIFICATION_FILES,
} from "@constants/queryKeys";
import { IStep } from "@features/GiveOnboarding/types";
import TaskCard from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/TaskCard";
import {
  AcceptAllowedImagesTypes,
  MAX_UPLOAD_SIZE,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import { useGetIdentificationFiles } from "@sections/VerifyAccountHolder_v2/hooks/useCamera";
 
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import { isEmpty } from "lodash";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import { useQueryClient } from "react-query";
import { DocumentSection } from "../../pages.atoms";
import { useDocumentHandlers } from "@hooks/common/documents";
import { IOnSubmitOptions } from "@features/GiveOnboarding/types/handlers";
import { FormLoader } from "@features/GiveOnboarding/components/loaders/FormLoader";
import { PagesContainer } from "../../pages.atoms";
import { Stack } from "@mui/material";
 
interface Props {
  data_key: IStep;
  merchantId: string;
  userFullName: string;
  handleAutoNavigate: () => void;
}
 
const IdDocument = forwardRef((props: Props, ref: any) => {
  const { handleAutoNavigate } = props;
  const merchantId = Number(props.merchantId);
  const { handleUpload, isLoading: uploadLoading } = useUploadFiles();
  const theme = useAppTheme();
  const queryClient = useQueryClient();
  const { deleteHandler } = useDocumentHandlers(merchantId);
  const { data: files, isLoading: areFilesLoading } =
    useGetIdentificationFiles();
 
  const ownerFiles = useMemo(
    () =>
      files?.data?.filter((doc: any) => doc?.attTypeName === "account_owner") ||
      [],
    [files],
  ) as TMerchantDocument[];
 
  const [isFormError, setIsFormError] = useState(false);
 
  useImperativeHandle(
    ref,
    () => ({
      data_key: props.data_key,
      submit: ({ onInvalid, onValid }: IOnSubmitOptions<any>) => {
        if (ownerFiles.length) {
          onValid?.({});
        } else Eif (!uploadLoading) {
          setIsFormError(true);
          onInvalid?.({
            type: "formValidation",
            error: {
              account_owner: {
                message: "Uploading an identification document is required",
              },
            },
          });
        }
      },
    }),
    [props.data_key, ownerFiles, setIsFormError, uploadLoading],
  );
 
  useEffect(() => {
    //separate effect to not update the intiial values, like submit when it shouldnt
    Eif (ref && typeof ref === "object" && ref.current) {
      ref.current.isLoading = areFilesLoading;
    }
  }, [areFilesLoading, ref]);
 
  const uploadFunction = async (file: File | File[]) => {
    const allFiles = [file];
    const filesToUpload = allFiles.map((file) => ({
      file: file as File,
    }));
    await handleUpload(
      {
        list: filesToUpload,
        merchantId: merchantId,
        resourceID: merchantId,
        attachmentType: "account_owner",
        label: "",
        tag: "Account owner ID",
      },
      challengeSlugs.PRIMARY_5,
    );
    await Promise.all([
      queryClient.invalidateQueries(QKEY_BUSINESS_PROFILE_BY_ID),
      queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]),
      queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]),
      queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]),
    ]);
    // await for the queries to be invalidated then call the handleNavigation
    handleAutoNavigate();
  };
 
  if (areFilesLoading)
    return (
      <PagesContainer testId="identity-id-document">
        <FormLoader />
      </PagesContainer>
    );
 
  return (
    <PagesContainer testId="identity-id-document">
      <Stack alignItems="center" justifyContent="center" width="100%">
        <IdIcon />
      </Stack>
      <GiveText my="24px" fontWeight="400" fontSize="14px">
        Upload an identification document such as a driver license, passport, or
        government issued ID card.
      </GiveText>
      <TaskCard title="Photo of ID" containerSx={{ width: "100%" }}>
        <>
          {isEmpty(ownerFiles) ? (
            <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"
                  : ""
              }
            />
          ) : (
            <DocumentSection
              ownerFiles={ownerFiles}
              userFullName={props?.userFullName}
              onDeleteSuccess={() => {
                queryClient.invalidateQueries([
                  "onboarding-progress",
                  merchantId,
                ]);
              }}
              allowDelete
            />
          )}
        </>
      </TaskCard>
    </PagesContainer>
  );
});
 
IdDocument.displayName = "IdDocument";
 
export { IdDocument };