All files / src/components/ProfilePage/BusinessProfileSetupNew/hooks usePrefillToBOData.ts

65% Statements 39/60
59.32% Branches 35/59
66.66% Functions 12/18
69.09% Lines 38/55

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                              39x                       39x               39x 247x   6x 6x     6x 6x       6x         247x     39x 247x   39x                       247x   247x 247x 247x   247x   32x         247x 247x 1205x           247x 247x 6x                 247x                                                                                   247x 32x   32x 6x 6x 30x 30x             30x             30x           30x         247x 28x                    
import { useGetMerchantById } from "@hooks/enterprise-api/account/useGetMerchants";
import { useEffect, useMemo } from "react";
import { useFormContext } from "react-hook-form";
import { findPhoneNumbersInText } from "libphonenumber-js";
import { useGetIdentificationFiles } from "@sections/VerifyAccountHolder_v2/hooks/useCamera";
import { createFileFromURL } from "@utils/assets";
import { formatInUTCMoment } from "@utils/date.helpers";
 
type SpecialFieldHandlers = {
  phoneNumber: (value: string) => string;
  dateOfBirth: (value: any) => any;
  countryOfResidence: (value: string) => boolean;
  citizenship: (value: string) => boolean;
};
 
const FIELDS = [
  { fieldName: "firstName", responseAttr: "firstName" },
  { fieldName: "lastName", responseAttr: "lastName" },
  { fieldName: "dob", responseAttr: "dateOfBirth" },
  { fieldName: "email", responseAttr: "email" },
  { fieldName: "phone", responseAttr: "phoneNumber" },
  { fieldName: "isUSResident", responseAttr: "countryOfResidence" },
  { fieldName: "countryOfResidence", responseAttr: "countryOfResidence" },
  { fieldName: "isUSCitizen", responseAttr: "citizenship" },
  { fieldName: "citizenship", responseAttr: "citizenship" },
];
 
const BO_ADDRESS_FIELDS = [
  { fieldName: "city", responseAttr: "city" },
  { fieldName: "state", responseAttr: "state" },
  { fieldName: "country", responseAttr: "country" },
  { fieldName: "line1", responseAttr: "line1" },
  { fieldName: "zip", responseAttr: "zip" },
];
 
const useSpecialFieldHandlers = () => {
  const specialFieldHandlers: SpecialFieldHandlers = {
    phoneNumber: (value: string) => {
      const parsedNumber = findPhoneNumbersInText(`+${value}`);
      Eif (parsedNumber?.length) {
        const {
          number: { countryCallingCode, nationalNumber },
        } = parsedNumber[0];
        return `+${countryCallingCode}${nationalNumber}`;
      }
      return value;
    },
    dateOfBirth: (value: number | string) => formatInUTCMoment(value),
    countryOfResidence: (value: string) => value === "US",
    citizenship: (value: string) => value === "US",
  };
 
  return { specialFieldHandlers };
};
 
const useGetFormContext = <T>(ctx: T & typeof useFormContext) =>
  ctx ?? useFormContext;
 
export const usePrefillToBOData = ({
  merchantId,
  isAtLeastOneBODefined,
  fieldNames,
  ctx,
  prefillAddress = false,
  makeItDirty = false,
}: any) => {
  const {
    formState: { dirtyFields, touchedFields },
    setValue,
    getValues,
  } = useGetFormContext(ctx());
 
  const { data } = useGetMerchantById({ merchantId });
  const { data: files } = useGetIdentificationFiles({ ID: merchantId });
  const { specialFieldHandlers } = useSpecialFieldHandlers();
 
  const ownerFiles = useMemo(
    () =>
      files?.data?.filter((doc: any) => doc?.attTypeName === "account_owner") ||
      [],
    [files],
  ) as any[];
 
  const dataFields = useMemo(() => {
    return Array.isArray(fieldNames.dataFields) && fieldNames.dataFields.length
      ? FIELDS.slice(0, fieldNames.dataFields.length).map((field, idx) => ({
          responseAttr: field.responseAttr,
          fieldName: fieldNames.dataFields[idx],
        }))
      : FIELDS;
  }, [fieldNames]);
  const boAddressFields = useMemo(() => {
    if (!prefillAddress) return [];
    return Array.isArray(fieldNames.boAddressFields) &&
      fieldNames.boAddressFields.length
      ? BO_ADDRESS_FIELDS.map((field, idx) => ({
          responseAttr: field.responseAttr,
          fieldName: fieldNames.boAddressFields[idx],
        }))
      : BO_ADDRESS_FIELDS;
  }, [fieldNames]);
 
  const handleUsePAHImage = async () => {
    //in order to use the PAH image for BO, we need to recreate the file as anew image, and upload it to the BE
    //first we need to convert the url to a file
    //then on creation we will upload it
    const [file] = ownerFiles;
    if (!file?.fileURL) return;
    const newFile = await createFileFromURL(
      file.fileURL,
      "owner-image.png",
      "png",
    );
    if (newFile) {
      const currentValues = getValues();
      if (
        !dirtyFields.files &&
        !touchedFields.files &&
        !currentValues.files.allFiles.length
      ) {
        const fileData = {
          allFiles: [
            {
              meta: {
                previewUrl: file.fileURL,
                name: "owner-image.png",
                size: 0,
                type: "image/png",
              },
              file: newFile,
              status: "done",
              id: Math.random().toString(36).substring(7),
            },
          ],
        };
 
        setValue("files", fileData, {
          shouldDirty: false,
          shouldTouch: false,
        });
      }
    }
  };
 
  useEffect(() => {
    Iif (!isAtLeastOneBODefined && ownerFiles?.length && merchantId)
      handleUsePAHImage();
    if (!isAtLeastOneBODefined && data?.owner && merchantId) {
      const currentValues = getValues();
      dataFields.forEach(({ fieldName, responseAttr }) => {
        Iif (!fieldName) return; // guard against undefined fieldName
        Eif (
          !dirtyFields[fieldName] &&
          !touchedFields[fieldName] &&
          currentValues[fieldName] !== undefined &&
          data.owner[responseAttr]
        ) {
          const handler =
            specialFieldHandlers[
              responseAttr as keyof typeof specialFieldHandlers
            ];
 
          const value =
            // For the `countryOfResidence` and `citizenship` fields, skip specialFieldHandlers
            // and use the raw API value instead; handlers are meant for derived flags, not these fields themselves.
            Boolean(
              !["countryOfResidence", "citizenship"].includes(fieldName) &&
                handler,
            )
              ? handler(data.owner[responseAttr])
              : data.owner[responseAttr];
          setValue(fieldName, value, { shouldDirty: makeItDirty });
        }
      });
    }
  }, [isAtLeastOneBODefined, data, ownerFiles]);
  useEffect(() => {
    Iif (data?.address && boAddressFields.length > 0) {
      boAddressFields.forEach(({ fieldName, responseAttr }) => {
        if (!fieldName) return; // guard against undefined fieldName
        if (!dirtyFields[fieldName] && !touchedFields[fieldName]) {
          setValue(`address.${fieldName}`, data.address[responseAttr]);
        }
      });
    }
  }, [data]);
};