All files / src/components/Merchants/CreateMerchantPanel/schemas BusinessProfileSchema.ts

93.75% Statements 45/48
88.88% Branches 32/36
100% Functions 11/11
93.02% Lines 40/43

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                                                                                            35x 1332x 1332x           35x         219x 444x   392x 73x           319x   319x 1x           318x   2x 2x   2x         2x 1x           1x               1x           35x         219x                     388x 235x 235x         235x           235x             444x   392x 71x         321x                     888x   784x 104x                                                             444x   392x 143x           249x 178x         71x                   784x                            
// ======================================================
// Imports
// ======================================================
import * as Yup from "yup";
import { matchIsValidTel } from "mui-tel-input";
 
import { VALIDATION_MESSAGES } from "@validation/messages";
 
import {
  AVAILABLE_TAX_ID_ERROR,
  DECLINED_SUSPENDED_BP_ERROR,
} from "@constants/constants";
import { createCountryValidator } from "@validation/address/countryValidator";
import { createStreetAddressValidator } from "@validation/address/streetValidator";
import { createCityValidation } from "@validation/address/cityValidator";
import { createStateValidator } from "@validation/address/stateValidator";
import { buildZipSchema } from "@validation/address/zipValidator";
import { ssnSchema } from "@utils/validation.helpers";
import moment from "moment";
 
// ======================================================
// Helpers
// ======================================================
 
interface ExtendedTestContext extends Yup.TestContext {
  from?: Array<{
    value?: {
      linkedBusinessProfile?: boolean;
      isLinkBusinessProfile?: boolean;
    };
  }>;
}
 
interface TaxInfo {
  isOnboardingLinkBPEnabled: boolean;
  checkedTaxID: React.MutableRefObject<{
    taxId: string;
    name?: string;
  } | null>;
  checkTaxIDAvailability: (taxID: string) => Promise<{
    isLinked: boolean;
    isDeclinedOrNotApproved: boolean;
    name?: string;
  }>;
}
 
const skipIfLinked = ({ from }: ExtendedTestContext): boolean => {
  const info = from?.[0]?.value;
  return Boolean(info?.linkedBusinessProfile && info?.isLinkBusinessProfile);
};
 
// ======================================================
// Async tax ID checker wrapper
// ======================================================
const createTaxIdValidation = ({
  isOnboardingLinkBPEnabled,
  checkedTaxID,
  checkTaxIDAvailability,
}: TaxInfo) =>
  Yup.string().test("taxID", "test", async function (value, ctx: any) {
    if (skipIfLinked(ctx)) return true;
 
    if (!value) {
      return this.createError({
        message: VALIDATION_MESSAGES.REQUIRED,
        path: "taxID",
      });
    }
 
    const nonFormattedTaxID = value.replace(/(\s|-)/g, "");
 
    if (nonFormattedTaxID.length !== 9) {
      return this.createError({
        message: `Invalid format. Format should be 12-3456789`,
        path: "taxID",
      });
    }
 
    if (!isOnboardingLinkBPEnabled) return true;
 
    Eif (checkedTaxID.current?.taxId !== nonFormattedTaxID) {
      const available = await checkTaxIDAvailability(nonFormattedTaxID);
 
      checkedTaxID.current = {
        ...available,
        taxId: nonFormattedTaxID,
      };
 
      if (available.isLinked) {
        return this.createError({
          message: AVAILABLE_TAX_ID_ERROR,
          path: "taxID",
        });
      }
 
      Iif (available.isDeclinedOrNotApproved) {
        return this.createError({
          message: DECLINED_SUSPENDED_BP_ERROR,
          path: "taxID",
        });
      }
    }
 
    return true;
  });
 
// ======================================================
// Main schema factory
// ======================================================
export const getBusinessProfileSchema = ({
  isOnboardingLinkBPEnabled,
  checkedTaxID,
  checkTaxIDAvailability,
}: TaxInfo) =>
  Yup.object().shape({
    // --------------------
    // Basic fields
    // --------------------
    isLinkBusinessProfile: Yup.boolean(),
    linkedBusinessProfile: Yup.number(),
    businessType: Yup.string(),
    ownershipType: Yup.string(),
    businessOpenedAt: Yup.string()
      .nullable()
      .test("businessOpenedAt", "test", function (value, ctx) {
        if (!value) return true;
        const date = moment(value);
        Iif (!date.isValid())
          return this.createError({
            message: VALIDATION_MESSAGES.INVALID_DATE,
            path: "businessOpenedAt",
          });
        Iif (date.isAfter(moment(), "day")) {
          return this.createError({
            message: VALIDATION_MESSAGES.FUTURE_DATE_NOT_ALLOWED,
            path: "businessOpenedAt",
          });
        }
        return true;
      }),
 
    // --------------------
    // Legal name
    // --------------------
    legalName: Yup.string().test("legalName", "test", function (value, ctx) {
      if (skipIfLinked(ctx)) return true;
 
      if (!value) {
        return this.createError({
          message: VALIDATION_MESSAGES.REQUIRED,
          path: "legalName",
        });
      }
      return true;
    }),
 
    DBA: Yup.string(),
 
    // --------------------
    // TIN Type (SSN/EIN)
    // --------------------
    tinType: Yup.mixed().when(
      ["linkedBusinessProfile", "isLinkBusinessProfile"],
      {
        is: (linkedBP: any, isLink: boolean) => !(linkedBP && isLink),
        then: (schema) =>
          schema.oneOf(["ssn", "ein"], "tinType must be either SSN or EIN"),
        otherwise: (schema) => schema.oneOf(["ssn", "ein"]).notRequired(),
      },
    ),
 
    // --------------------
    // SSN
    // --------------------
    ssn: Yup.string().when("tinType", {
      is: "ssn",
      then: ssnSchema("ssn"),
    }),
 
    // --------------------
    // EIN
    // --------------------
    taxID: Yup.string().when("tinType", {
      is: "ein",
      then: createTaxIdValidation({
        isOnboardingLinkBPEnabled,
        checkedTaxID,
        checkTaxIDAvailability,
      }),
    }),
 
    // --------------------
    // Phone number
    // --------------------
    contactPhone: Yup.string().test(
      "contactPhone",
      "test",
      function (value, ctx) {
        if (skipIfLinked(ctx)) return true;
 
        if (!value || value === "+1") {
          return this.createError({
            message: VALIDATION_MESSAGES.CONTACT_PHONE_REQUIRED,
            path: "contactPhone",
          });
        }
 
        if (!matchIsValidTel(value)) {
          return this.createError({
            message: "Please enter a valid phone number",
            path: "contactPhone",
          });
        }
        return true;
      },
    ),
 
    // --------------------
    // Address (skipped if linking)
    // --------------------
    address: Yup.object().when("isLinkBusinessProfile", {
      is: false,
      then: () =>
        Yup.object().shape({
          country: createCountryValidator({ nullable: false }),
          address: createStreetAddressValidator({ required: false }),
          city: createCityValidation({ maxLength: 20 }),
          state: createStateValidator(),
          zip: buildZipSchema({
            usFormatOnly: true,
            allowNull: false,
            message: "Invalid ZIP format",
          }),
          notes: Yup.string(),
        }),
    }),
  });