All files / src/features/GiveOnboarding/hooks useGetApiData.ts

86.95% Statements 20/23
92.3% Branches 84/91
66.66% Functions 2/3
86.36% Lines 19/22

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                                    9x             134x     134x     134x                           134x           134x                                                           134x                                 134x                   134x             134x   134x         134x   134x     134x   134x                                     134x                                               134x                 134x                                                                       134x    
import { useGetBusinessProfileData } from "@components/Settings/BusinessDetails/RebrandedBusinessProfile/hooks/useBusinessProfileV2";
import { useGetMerchantById } from "@hooks/enterprise-api/account/useGetMerchants";
import {
  isOwnerIdentitySubmitted,
  MerchantOwnerReassignment,
  resolveIsPahReassignmentIdentityOnly,
} from "@hooks/common/usePahReassignmentStatus";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import { IStep } from "../types";
import { parsePhoneNumber } from "../utils";
import { useGetBankAccounts } from "@services/api/products/manage-money";
import { useGetAgreementData } from "@features/Merchants/MerchantSidePanel/AgreementAndSnapshot/Agreement/useGetAgreementData";
import { NewOnboardingTBusinessOwner } from "@common/BusinessOwners/types";
import { BankAccountDetailsForm } from "../types/form";
import { useGetLinkedLegalEntity } from "@features/Merchants/MerchantSidePanel/GiveMerchantFile/hooks/useGetLinkedLegalEntity";
import { formatInUTCMoment } from "@utils/date.helpers";
 
export const useGetApiData = ({
  currentSubstep,
  isStarted,
}: {
  currentSubstep: IStep;
  isStarted: boolean;
}) => {
  const { data, isLoading } = useGetMerchantById({ enabled: true });
  // selectUser returns undefined until auth state is populated; the onboarding
  // flow can render before then, so read email defensively (no destructure).
  const currentUserEmail = useAppSelector(selectUser)?.email;
 
  const { data: bankAcountData, isLoading: bankAccountsLoading } =
    useGetBankAccounts(
      { sorting: "createdAt", merchantId: data?.accID, page: 1 },
      {
        refetchOnWindowFocus: false,
        enabled:
          Boolean(data?.accID) &&
          isStarted &&
          [
            "business_bank_connect",
            "business_bank_statement",
            "business_bank_confirm",
          ].includes(currentSubstep),
      },
    );
  const pendingLegalEntityQuery = useGetLinkedLegalEntity({
    merchantID: data?.accID,
    pendingLegalEntityID: data?.pendingLegalEntityID,
    enabled: Boolean(data?.accID && data?.pendingLegalEntityID),
  });
 
  const merchantInfoData = {
    merchantId: data?.accID,
    merchantName: data?.name,
    legalEntityID: data?.legalEntityID || undefined, //enforce it to be undefined. is checked agains undefined to decided if bp mutation is a patch or post
    isInOnboardingSection: data?.isInOnboardingSection ?? false,
    bankAccountSettings: data?.bankAccountSettings || {},
    pendingTaxIdNumber: data?.pendingLegalEntityTaxIDNumber,
    pendingLegalEntityEmail:
      pendingLegalEntityQuery?.data?.controllerOwnerEmail,
    pendingLegalEntityStatus: data?.pendingLegalEntityStatus,
    isOnboardingCompleted: data?.isOnboardingCompleted ?? false,
    statusInfo: useGetAgreementData(data),
    isAllowedAddBankAccounts: data?.isAllowedAddBankAccounts ?? false,
    isController: data?.isController ?? false,
    // PAH006 SS-4 / GB-21477: identity-only re-onboarding applies only to the
    // incoming new PAH. resolveIsPahReassignmentIdentityOnly scopes the
    // merchant-wide BE flag to the logged-in user (suppresses it for the seated
    // old PAH while the invite is unaccepted).
    isPahReassignmentIdentityOnly: resolveIsPahReassignmentIdentityOnly(
      data?.owner as MerchantOwnerReassignment | undefined,
      currentUserEmail,
    ),
    // PAH006 SS-4 follow-up: true once the PAH has uploaded identity
    // (owner.statusName → ready_for_verification). The wizard closes on this so
    // the PAH lands on the portal directly instead of a review screen.
    isPahReassignmentIdentitySubmitted: isOwnerIdentitySubmitted(
      data?.owner as MerchantOwnerReassignment | undefined,
    ),
  };
 
  const businessDetails = {
    business_social_media: data?.socialMediaURL?.replace(
      /^https:\/\/|(?<=:)https:\/\//g,
      "",
    ),
    website_url: data?.websiteURL?.replace(/^https:\/\/|(?<=:)https:\/\//g, ""),
    businessImage: data?.imageURL,
    billingDescriptor: data?.billingDescriptor,
    billingDescriptorPrefix: data?.billingDescriptorPrefix,
    estimated_annual_revenue: data?.annualCreditCardSalesVolume / 100,
    high_ticket_amount: data?.highTicketAmount / 100,
    average_ticket_amount: data?.averageTicketAmount / 100,
    merchant_name: data?.name,
    amount: "130.29 USD",
    date: " 2 May 2024 14:05",
    merchant_phone_number: parsePhoneNumber(data?.servicePhoneNumber) || "",
  };
  const ownerData = {
    firstName: data?.owner?.firstName,
    lastName: data?.owner?.lastName,
    dateOfBirth: formatInUTCMoment(data?.owner?.dateOfBirth) || null,
    phoneNumber: parsePhoneNumber(data?.owner?.phoneNumber) ?? "",
    countryOfResidence: data?.owner?.countryOfResidence || "US",
    citizenship: data?.owner?.citizenship || "US",
  };
 
  const { data: legalEntityData, isLoading: isLoadingLegalEntity } =
    useGetBusinessProfileData({
      legalEntityID: merchantInfoData.legalEntityID,
      enabled: isStarted,
    });
 
  let firstAccount;
 
  const linkedAccounts = bankAcountData?.data?.filter((b) => b.isLinked);
 
  Iif (linkedAccounts?.length) {
    const firstLinkedBankAccount = linkedAccounts[0];
    firstAccount = firstLinkedBankAccount;
  } else {
    const lastCreatedBankAccount =
      bankAcountData?.data?.[bankAcountData?.data?.length - 1];
 
    firstAccount = lastCreatedBankAccount;
  }
 
  const isLoadingBP = pendingLegalEntityQuery.isLoading || isLoadingLegalEntity;
 
  const bankData: BankAccountDetailsForm = {
    accountNumber: firstAccount?.numberLast4
      ? `•••• ${firstAccount?.numberLast4}`
      : "",
    name: firstAccount?.name || "",
    type: firstAccount?.type || "checking",
    routingNumber: firstAccount?.routingNumber || "",
    notes: firstAccount?.notes || "",
    bankDataAux: {
      id: firstAccount?.id as never,
      bankName: firstAccount?.bankName || "",
      createdAt: firstAccount?.createdAt || null,
      routingNumber: firstAccount?.routingNumber || "",
      numberLast4: firstAccount?.numberLast4 || "",
      status: firstAccount?.status || "",
      isLinked: firstAccount?.isLinked || false,
    },
  };
 
  const businessProfileData = {
    name: legalEntityData?.name ?? merchantInfoData.merchantName,
    DBA: legalEntityData?.doingBusinessAs,
    businessOpenedAt:
      formatInUTCMoment(legalEntityData?.businessOpenedAt) || null,
    type: legalEntityData?.type?.name,
    ownershipType: legalEntityData?.ownershipType,
    phoneNumber: parsePhoneNumber(legalEntityData?.phoneNumber) ?? "",
    taxIDNumber: legalEntityData?.taxIDNumber,
    ssn: legalEntityData?.tinType === "ssn" ? legalEntityData?.taxIDNumber : "",
    tinType: legalEntityData?.tinType ?? "ein",
    businessProfileDataAux: {
      //is is undefined means not business profile linked, therefore we should show the form
      //otherwise, show the form only if candEdit and if is false, it means is a linked one
      showLinkedBusinessProfile: merchantInfoData.legalEntityID
        ? merchantInfoData.legalEntityID && !merchantInfoData.isController
        : Boolean(merchantInfoData.pendingTaxIdNumber) &&
          merchantInfoData.pendingLegalEntityStatus !== "pending",
      wasFilledAnExistingTaxID:
        Boolean(merchantInfoData.pendingTaxIdNumber) &&
        merchantInfoData.pendingLegalEntityStatus === "pending",
    },
  };
 
  const businessAddressData = {
    country: legalEntityData?.address?.country || "US",
    address: legalEntityData?.address?.line1 ?? "",
    city: legalEntityData?.address?.city ?? "",
    state: legalEntityData?.address?.state ?? "",
    zip: legalEntityData?.address?.zip ?? "",
    notes: legalEntityData?.address?.notes ?? "",
  };
 
  const apiData = {
    data: {
      merchant_info: merchantInfoData,
      identity_details: ownerData,
      business_profile:
        businessProfileData.businessProfileDataAux.wasFilledAnExistingTaxID ||
        legalEntityData
          ? businessProfileData
          : undefined,
      business_address: legalEntityData ? businessAddressData : undefined,
      business_owners: {
        list:
          legalEntityData?.principals?.length > 0
            ? legalEntityData.principals?.map(
                (x: NewOnboardingTBusinessOwner) => ({
                  ...x,
                  idImageUrl: x.idImageURL,
                  dob: formatInUTCMoment(x?.dateOfBirth),
                }),
              )
            : [],
        skipInitialRequestOnMount: true,
      },
      business_details: businessDetails,
      business_bank_connect: bankData,
    },
    loadings: {
      merchant_info: isLoading,
      identity_details: false,
      business_profile: isLoadingBP,
      business_address: isLoadingBP,
      business_owners: isLoadingBP,
      business_bank_connect: bankAccountsLoading,
    },
  };
 
  return apiData;
};