All files / src/components/Merchants/MerchantPreview/hooks useEditPAH.tsx

68.25% Statements 43/63
65.21% Branches 30/46
66.66% Functions 10/15
67.21% Lines 41/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                                                                                                          4x                 52x           4x                                                 4x 18x 18x 18x     18x   18x                     18x 18x   18x             18x 12x             18x 12x                   18x 8x 8x   8x                                               18x                                   18x         18x 2x               18x         2x         2x       18x 1x   1x     1x       1x               1x           1x             18x 1x       18x 1x 1x         1x         18x    
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { useEffect } from "react";
import { useUpdateMerchantInfo } from "@components/Merchants/MerchantPreview/hooks/useUpdateMerchantInfo";
import { SAVE_CHANGES_MODAL } from "modals/modal_names";
import { IParsedData, TPrimaryAccountHolder } from "../data.types";
import { useAppSelector } from "@redux/hooks";
import {
  dateOfBirthSchema,
  nonResidentInputsSchema,
  phoneSchema,
} from "@utils/validation.helpers";
import { OFAC_STATUS } from "@constants/constants";
import { getServicePhoneNumber } from "@utils/helpers";
import { renderBODeps } from "@components/ProfilePage/BusinessProfileSetupNew/utils/principal.utils";
import { selectUser } from "@redux/slices/auth/auth";
import {
  LocalOwnerFileType,
  TOwnerFile,
} from "../components/PrimaryAccountHolder/types";
import { usePAHUploader } from "../hooks/usePAHUploader";
import { IFileWithMeta } from "react-dropzone-uploader";
import { isEmpty, pick } from "lodash";
 
type FormInputs = {
  firstName: string;
  lastName: string;
  isNotUSResident: boolean;
  citizenship: string;
  isNotResidentInCitizenshipCountry: boolean;
  countryOfResidence: string;
  email: string;
  phoneNumber: string;
  dob: Date | string | null;
  ssn: string;
  isUSResident: boolean;
  isUSCitizen: boolean;
  selfie?: LocalOwnerFileType;
  ID?: LocalOwnerFileType;
  removedSelfieFileId?: number;
  removedIDFileId?: number;
  address: {
    country: string;
    city: string;
    address: string;
    state: string;
    zip: string;
  };
};
 
const schema = Yup.object().shape({
  firstName: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
  lastName: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
  email: Yup.string()
    .email("Please enter a valid email")
    .required(VALIDATION_MESSAGES.REQUIRED),
  phoneNumber: phoneSchema().test(
    "phone-number",
    VALIDATION_MESSAGES.REQUIRED,
    (value) => !!value && value !== "+1",
  ),
  dob: dateOfBirthSchema(true),
  ...nonResidentInputsSchema,
});
 
const defaultValues = {
  firstName: "",
  lastName: "",
  email: "",
  phoneNumber: "",
  dob: "",
  isNotUSResident: false,
  citizenship: "",
  isNotResidentInCitizenshipCountry: false,
  countryOfResidence: "",
  isUSResident: true,
  isUSCitizen: true,
  ID: undefined,
  selfie: undefined,
  removedSelfieFileId: undefined,
  removedIDFileId: undefined,
};
 
type Props = {
  id: number;
  data: TPrimaryAccountHolder;
  ownerAccId: number;
  merchantData: IParsedData;
};
 
export const useEditPAH = ({ id, data, ownerAccId }: Props) => {
  const modal = useModal();
  const { handleSubmit, isLoading } = useUpdateMerchantInfo(id);
  const { email } = useAppSelector(selectUser);
 
  const isOFACConfirmedMatch =
    data?.ofac?.lastCheckStatusName === OFAC_STATUS.CONFIRMED_MATCH;
 
  const methods = useForm<FormInputs>({
    mode: "onChange",
    resolver: yupResolver(schema),
    defaultValues,
  });
 
  const {
    reset,
    setValue,
    formState: { isValid, isDirty, dirtyFields },
    watch,
  } = methods;
  const values = watch();
 
  const { handleConversionAndUpload, _deleteDocument } = usePAHUploader({
    docUrl: "",
    fileId: 0,
    merchantId: id,
    type: "primaryAccountHolderID", // will be overwritten by the customType,
  });
 
  useEffect(() => {
    Iif (values.isUSCitizen && methods.formState.dirtyFields?.isUSCitizen) {
      setValue("citizenship", "US", {
        shouldDirty: true,
      });
    }
  }, [values.isUSCitizen]);
 
  useEffect(() => {
    Iif (values.isUSResident && methods.formState.dirtyFields?.isUSResident) {
      setValue("countryOfResidence", "", {
        shouldDirty: true,
      });
      setValue("isUSCitizen", true, {
        shouldDirty: true,
      });
    }
  }, [values.isUSResident]);
 
  useEffect(() => {
    const { isUSCitizen, isUSResident } = renderBODeps(data.owner);
    const dob = data?.dateOfBirth;
 
    reset(
      data
        ? {
            ...data,
            dob: dob ? dob : "",
            phoneNumber: getServicePhoneNumber(data.phoneNumber),
            isNotUSResident: !!data?.citizenship,
            citizenship: isUSCitizen ? "US" : data?.owner?.citizenship || "",
            isNotResidentInCitizenshipCountry: !!data?.countryOfResidence,
            countryOfResidence: isUSResident
              ? "US"
              : data?.owner?.countryOfResidence || "",
            email: data?.owner?.email || data?.email,
            isUSCitizen,
            isUSResident,
            ID: undefined,
            selfie: undefined,
            removedSelfieFileId: undefined,
            removedIDFileId: undefined,
          }
        : defaultValues,
    );
  }, [id, data]);
 
  const handleLocalDoc = (data: LocalOwnerFileType) => {
    const fileData = data?.fileURL === null ? undefined : { ...data };
 
    if (data?.type === "primaryAccountHolderID") {
      if (data?.fileId) {
        setValue("removedIDFileId", data?.fileId, { shouldDirty: true });
      } else {
        setValue("ID", fileData, { shouldDirty: true });
      }
    } else {
      if (data?.fileId) {
        setValue("removedSelfieFileId", data?.fileId, { shouldDirty: true });
      } else {
        setValue("selfie", fileData, { shouldDirty: true });
      }
    }
  };
 
  const handleClose = () => {
    reset();
    modal.hide();
  };
 
  const handleUpload = (file: string | undefined, type: TOwnerFile) => {
    Eif (!file) return;
    handleConversionAndUpload({
      allFiles: [{ file } as unknown as IFileWithMeta],
      status: "done",
      customType: type,
    });
  };
 
  const handleDeleteAndMaybeUpload = (
    type: TOwnerFile,
    removedFileId?: number,
    newFileUrl?: any,
  ) => {
    Iif (removedFileId) {
      _deleteDocument(type, removedFileId, () => {
        handleUpload(newFileUrl, type);
      });
    } else {
      handleUpload(newFileUrl, type);
    }
  };
 
  const handleSave = (newData: FormInputs) => {
    const isLoggedInPAH = email === data?.owner?.email;
 
    const payload = pick(newData, Object.keys(dirtyFields));
 
    const inviteOwner =
      data?.owner?.email &&
      data?.owner?.email !== newData?.email &&
      !isLoggedInPAH;
 
    handleSubmit(
      "primary_account_holder",
      { ...payload, inviteOwner },
      handleClose,
      undefined,
      ownerAccId,
    );
 
    handleDeleteAndMaybeUpload(
      "primaryAccountHolderID",
      newData?.removedIDFileId,
      newData?.ID?.fileURL,
    );
 
    handleDeleteAndMaybeUpload(
      "primaryAccountHolderSelfie",
      newData?.removedSelfieFileId,
      newData?.selfie?.fileURL,
    );
  };
 
  const onSubmit: SubmitHandler<FormInputs> = async (newData) => {
    if (!isEmpty(dirtyFields)) handleSave(newData);
    else EhandleClose();
  };
 
  const handleCancel = () => {
    Eif (isDirty && isValid && !isOFACConfirmedMatch) {
      NiceModal.show(SAVE_CHANGES_MODAL, {
        modalName: "Edit Primary Account Holder",
        handleCancel: () => handleClose(),
        handleSave: () => handleSave(values),
      });
      return;
    }
    handleClose();
  };
 
  return { methods, handleCancel, onSubmit, handleLocalDoc, isLoading };
};