All files / src/components/ProfilePage/PersonalInformation/hooks usePersonalInformation.ts

73.84% Statements 48/65
60.6% Branches 40/66
68.75% Functions 11/16
77.04% Lines 47/61

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                                                  22x 22x 22x 22x 22x   22x 22x   22x 22x 22x 22x       22x               22x         22x     22x 22x 22x 22x 22x     22x             22x                             22x 26x 7x 7x 9x   7x 7x           7x             22x         2x 2x 2x         2x             2x 2x                                                                 22x       22x                                               19x           22x 22x   22x                                                         19x 2x   2x   2x                                                                         19x      
import { useGetCurrentMerchantId } from "@hooks/common";
import { useRef, useState, useCallback } from "react";
import useManageApi from "@sections/VerifyAccountHolder_v2/hooks/useManageApi";
import useFindBusinessProfileById from "@hooks/enterprise-api/merchants/useFindBusinessProfileById";
import { PersonalInfoTabDefaultData, newPersonalInfoEnum } from "../types";
import { IFileWithMeta } from "react-dropzone-uploader";
import { useGetIdentificationFiles } from "@sections/VerifyAccountHolder_v2/hooks/useCamera";
import { isEmpty } from "lodash";
import { challengeSlugs } from "@constants/challengeSlugs";
import { useQueryClient } from "react-query";
import { useGetMerchantById } from "@hooks/enterprise-api/account/useGetMerchants";
import { getIsOwnerCheckedByDefault } from "@sections/VerifyAccountHolder_v2/form/form.const";
import {
  UPLOAD_STATUSES_ENUM,
  useUploadFiles,
} from "@hooks/upload-api/uploadHooks";
import {
  QKEY_IDENTIFICATION_FILES,
  QKEY_GET_MERCHANT_BY_ID,
} from "@constants/queryKeys";
import { useAppDispatch } from "@redux/hooks";
import { updatePartialUser } from "@redux/slices/auth/auth";
import { formatInUTCMoment } from "@utils/date.helpers";
 
export default function usePersonalInformation() {
  const stepperRef = useRef<any>(null);
  const queryClient = useQueryClient();
  const dispatch = useAppDispatch();
  const handleNext = () => stepperRef.current?.handleNext();
  const handleBack = () => stepperRef.current?.handleBack();
 
  const { data: files } = useGetIdentificationFiles({ filter: "" });
  const { merchantId } = useGetCurrentMerchantId();
  const { onSubmitInformation, informationsAreLoading } =
    useManageApi(merchantId);
  const { handleUpload } = useUploadFiles();
  const [isLoaded, setIsLoaded] = useState<boolean>(false);
  const [step, setStep] = useState<newPersonalInfoEnum>(
    newPersonalInfoEnum.PERSONAL_INFORMATION,
  );
  // Poll merchant data until selfie is uploaded when on the selfie step
  const { data: enterpriseData } = useGetMerchantById({
    merchantId,
    refetchInterval:
      step === newPersonalInfoEnum.TAKE_A_SELFIE
        ? (latestData: any) =>
            !latestData?.owner?.selfieUploaded ? 6000 : false
        : false,
  });
  const { data: legalEntity } = useFindBusinessProfileById({
    id: enterpriseData?.legalEntityID,
    merchantId,
  });
 
  const leType = legalEntity?.type?.name;
 
  const principal =
    legalEntity?.principals &&
    legalEntity?.principals?.find((user: any) => !!user?.ownerID);
  const isPrincipalSaved = principal && !isEmpty(principal);
  const fullOwnershipReleased = legalEntity?.principals?.reduce(
    (acc: number, v: any) => acc + v.ownershipPercentage,
    0,
  );
  const personalTabDefaultData = useGeneratePersonalInfoTabDefaultData(
    enterpriseData?.owner,
    principal,
    legalEntity?.type?.name,
    fullOwnershipReleased,
  );
 
  const [personalInfoStatusBar, setPersonalInfoStatusBar] = useState([
    {
      label: newPersonalInfoEnum.PERSONAL_INFORMATION,
      barValue: 0,
    },
    {
      label: newPersonalInfoEnum.UPLOAD_YOUR_ID,
      barValue: 0,
    },
    {
      label: newPersonalInfoEnum.TAKE_A_SELFIE,
      barValue: 0,
    },
  ]);
 
  const handleUpdateStatusValue = useCallback(
    (label: string) => (value: number) => {
      setPersonalInfoStatusBar((prev) => {
        let oldArr = prev;
        const index = oldArr.findIndex((obj) => obj.label === label);
 
        Eif (index !== -1) {
          oldArr = [
            ...oldArr.slice(0, index),
            { ...oldArr[index], barValue: value },
            ...oldArr.slice(index + 1),
          ];
        }
        return oldArr;
      });
    },
    [],
  );
  type dataOld = PersonalInfoTabDefaultData | IFileWithMeta[] | null;
  type dataNew = PersonalInfoTabDefaultData | File | null;
  const onHandleSubmit = async (
    tab: newPersonalInfoEnum,
    data: dataOld | dataNew,
    skipApiSave = false,
  ) => {
    Eif (tab === newPersonalInfoEnum.PERSONAL_INFORMATION) {
      const payload = generatePayload(tab, data);
      Iif (skipApiSave) {
        setStep(newPersonalInfoEnum.UPLOAD_YOUR_ID);
        return;
      }
 
      return onSubmitInformation(
        {
          ...payload,
          legalEntityId: legalEntity?.id,
          principalId: principal?.id,
        },
        (data) => {
          setStep(newPersonalInfoEnum.UPLOAD_YOUR_ID);
          dispatch(
            updatePartialUser({
              globalName: {
                firstName: data.base.firstName || "",
                lastName: data.base.lastName || "",
                phoneNumber: data.base.phoneNumber || "",
              },
            }),
          );
        },
      );
    }
    if (tab === newPersonalInfoEnum.UPLOAD_YOUR_ID) {
      const uploadRes = await handleUpload(
        {
          list: [{ file: data as File }],
          merchantId,
          resourceID: merchantId,
          attachmentType: "account_owner",
          label: "",
          tag: "Account owner ID",
          refetcherKey: [QKEY_IDENTIFICATION_FILES],
        },
        challengeSlugs.PRIMARY_5,
      );
 
      if (uploadRes === UPLOAD_STATUSES_ENUM.failed) return;
 
      queryClient.invalidateQueries([QKEY_IDENTIFICATION_FILES, merchantId]);
      handleUpdateStatusValue(newPersonalInfoEnum.UPLOAD_YOUR_ID)(100);
      return uploadRes;
    }
  };
  const goNext = () => {
    handleNext();
    queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
  };
  return {
    personalInfoStatusBar,
    step,
    setStep,
    stepperRef,
    isLoaded,
    setIsLoaded,
    handleNext: goNext,
    handleBack,
    handleUpdateStatusValue,
    onHandleSubmit,
    personalTabDefaultData,
    files,
    enterpriseData,
    isIndividualSoleProprietorship: leType === "individual_sole_proprietorship",
    canEdit: legalEntity?.canEdit,
    leType,
    isPrincipalSaved,
    fullOwnershipReleased,
    isSubmitLoading: informationsAreLoading,
    setPersonalInfoStatusBar,
  };
}
 
const useGeneratePersonalInfoTabDefaultData = (
  owner: any,
  principal: any,
  leType: string,
  fullOwnershipReleased: number,
) => {
  const address = principal?.address;
  const phoneNumber = owner?.phoneNumber || principal?.phoneNumber;
 
  return {
    firstName: owner?.firstName || "",
    lastName: owner?.lastName || "",
    DOB: formatInUTCMoment(owner?.dateOfBirth),
    phoneNumber,
    isOwner: !isEmpty(principal)
      ? true
      : fullOwnershipReleased === 100
      ? false
      : getIsOwnerCheckedByDefault(leType),
    hasManagerialAuthority: true,
    country: address?.country || "US",
    city: address?.city || "",
    street: address?.line1 || "",
    state: address?.state || "",
    zip: address?.zip || "",
    ownership:
      leType === "individual_sole_proprietorship"
        ? "100"
        : principal?.ownershipPercentage
        ? `${principal?.ownershipPercentage}`
        : "10",
    isNotUSResident: !!owner?.countryOfResidence,
    citizenship: owner?.citizenship || "",
    isNotResidentInCitizenshipCountry: !!owner?.citizenship,
    countryOfResidence: owner?.countryOfResidence || "",
  };
};
 
const generatePayload = (tab: newPersonalInfoEnum, data: any) => {
  const phoneNumber = data?.phoneNumber?.slice(1).replaceAll(" ", "");
 
  switch (tab) {
    case newPersonalInfoEnum.PERSONAL_INFORMATION:
      return {
        isOwner: data?.isOwner,
        base: {
          ...(data?.DOB && { dob: data?.DOB }),
          firstName: data?.firstName,
          isManager: data?.hasManagerialAuthority,
          lastName: data?.lastName,
          ...(phoneNumber?.length > 3 && {
            phoneNumber: phoneNumber,
          }),
          citizenship: data?.isNotResidentInCitizenshipCountry
            ? data?.citizenship
            : "",
          countryOfResidence: data?.isNotUSResident
            ? data?.countryOfResidence
            : "",
        },
        ...(data?.isOwner && {
          whenIsOwner: {
            address: {
              country: data?.country,
              city: data?.city,
              line1: data?.street,
              state: data?.state,
              zip: data?.zip,
            },
            ownership: data?.ownership,
          },
        }),
      };
    case newPersonalInfoEnum.TAKE_A_SELFIE:
      return {};
    case newPersonalInfoEnum.UPLOAD_YOUR_ID:
      return {};
  }
};
 
const isValidSSNTaxID = (taxID: string) => {
  return taxID?.replace(/\D/g, "")?.length === 9;
};