All files / src/components/ProfilePage/BusinessProfileSetup EnterpriseInfo.tsx

6.89% Statements 2/29
0% Branches 0/12
0% Functions 0/10
6.89% Lines 2/29

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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  19x                                                                           19x                  
import WebsiteInput from "@common/BusinessProfileInputs/WebsiteInput";
import { RHFInput, RHFTelInput } from "@common/Input";
import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Grid, Stack } from "@mui/material";
import { urlSchema } from "@utils/validation.helpers";
import { matchIsValidTel } from "mui-tel-input";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import * as Yup from "yup";
import { VALIDATION_MESSAGES } from "@validation/messages";
import {
  ProfileSetupFormActions,
  ProfileSetupFormContainer,
  ProfileSetupFormTitle,
} from "../form.components";
import { TBusinessStepsCommons } from "@components/ProfilePage/BusinessProfileSetupNew/types";
import { DynamicReturnType } from "./helpers/refineData";
import usePercentageUpdate from "./hooks/usePercentageUpdate";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, {
  EDIT_DENY_MESSAGE,
  OPERATIONS,
} from "@constants/permissions";
import { gridItemsRenderer } from "@utils/rendering/nodesRenderers";
import {
  PROVIDER_PERMALINK_FIELD,
  SLUG_MAX_CHARACTER_LENGTH,
  WEBSITE_URL_FIELD,
} from "@constants/constants";
import {
  BUSINESS_CUNDUCTED_OUTSIDE_USA,
  ENTER_COUNTRIES_OUTSIDE_USA,
  SERVICE_OUTSIDE_USA_CANADA_STRING,
} from "@constants/stringConstants";
import { useEffect } from "react";
import { useSlugPrefix } from "@features/Merchants/MerchantSidePanel/components/MerchantSlugInput/useSlugPrefix";
import { InverseRHFCheckbox } from "@common/Checkbox/Checkbox";
import { generateNameLabelPlaceholder } from "@features/GiveSignup/helpers";
 
type FormInputs = {
  name: string;
  servicePhoneNumber: string;
  purpose: string;
  websiteURL: string;
  serviceCountriesOutUSCanada: boolean;
  countriesServicedOutside: string;
  permalink: string;
};
 
interface IProps extends TBusinessStepsCommons {
  data: DynamicReturnType["enterpriseInfo"];
}
 
function EnterpriseInfo({
  submitHandler,
  handleBack,
  statusBar,
  updateStatusBar,
  data,
  isSubmitting,
}: IProps) {
  const methods = useForm<FormInputs>({
    mode: "onChange",
    resolver: yupResolver(enterpriseInfoSchema),
    defaultValues: data,
  });
 
  const {
    watch,
    handleSubmit,
    setValue,
    formState: { dirtyFields, isDirty },
  } = methods;
  const values = watch();
 
  const { prefix, webDomain } = useSlugPrefix({
    isProvider: true,
    slugValue: watch("permalink"),
  });
 
  usePercentageUpdate<FormInputs>(
    values,
    dirtyFields,
    enterpriseInfoSchema,
    updateStatusBar,
  );
 
  const isEditAllowed = useAccessControl({
    resource: RESOURCE_BASE.ENTERPRISE,
    operation: OPERATIONS.UPDATE,
  });
 
  const displayName = data.class.name
    ? generateNameLabelPlaceholder(data.class.name)
    : "Provider";
 
  const serviceCountriesOutUSCanada = watch("serviceCountriesOutUSCanada");
 
  useEffect(() => {
    if (!serviceCountriesOutUSCanada) {
      setValue("countriesServicedOutside", ""); // clear when unchecked
    }
  }, [serviceCountriesOutUSCanada]);
 
  const nodeList: Array<{
    node: JSX.Element;
    hidden?: boolean;
  }> = [
    {
      node: (
        <RHFInput
          name="name"
          label={`${displayName} Name`}
          placeholder="The name of your provider"
          fullWidth
          inputProps={{ maxLength: 128 }}
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      node: (
        <WebsiteInput
          fullWidth
          name="permalink"
          label={PROVIDER_PERMALINK_FIELD}
          inputPrefix={prefix}
          inputSuffix={webDomain}
          maxLength={SLUG_MAX_CHARACTER_LENGTH}
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      node: (
        <RHFTelInput
          label={`Provider Phone Number`}
          name="servicePhoneNumber"
          fullWidth
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      node: (
        <WebsiteInput
          name="websiteURL"
          label={WEBSITE_URL_FIELD}
          placeholder="example.com"
          inputPrefix="https://"
          disabled={!isEditAllowed}
          fullWidth
        />
      ),
    },
    {
      node: (
        <RHFInput
          name="purpose"
          label="Goods and/or Services Description"
          placeholder="Goods and/or Services Description"
          multiline
          rows={6}
          fullWidth
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      node: (
        <InverseRHFCheckbox
          name="serviceCountriesOutUSCanada"
          label={SERVICE_OUTSIDE_USA_CANADA_STRING}
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      node: (
        <RHFInput
          name="countriesServicedOutside"
          label={BUSINESS_CUNDUCTED_OUTSIDE_USA}
          placeholder={ENTER_COUNTRIES_OUTSIDE_USA}
          multiline
          rows={6}
          fullWidth
          disabled={!isEditAllowed}
        />
      ),
      hidden: !values?.serviceCountriesOutUSCanada,
    },
  ];
 
  const onSubmit: SubmitHandler<FormInputs> = (data) => {
    submitHandler("enterpriseInfo", data, {
      makeApiCall: isDirty,
      dirtyFields,
    });
  };
 
  return (
    <FormProvider {...methods}>
      <Box
        component="form"
        flexGrow={1}
        id="enterprise-info-form"
        display="flex"
        onSubmit={handleSubmit(onSubmit)}
      >
        <ProfileSetupFormContainer>
          <Stack
            direction="column"
            gap={4}
            alignItems="flex-start"
            height="min-content"
          >
            <ProfileSetupFormTitle title={`${displayName} Info`} />
            <Grid container rowSpacing="12px">
              {gridItemsRenderer(nodeList, {
                show: !isEditAllowed,
                message: EDIT_DENY_MESSAGE,
              })}
            </Grid>
          </Stack>
          <ProfileSetupFormActions
            secondaryAction={{
              onClick: handleBack,
            }}
            primaryAction={{
              disabled: isSubmitting,
              children: "Finish",
              onClick: () => onSubmit(values),
            }}
          />
        </ProfileSetupFormContainer>
      </Box>
    </FormProvider>
  );
}
 
export default EnterpriseInfo;
 
const CustomPhoneSchema = Yup.string()
  .required("A phone is required")
  .when({
    is: (exists: string) => Boolean(exists) && exists !== "+1",
    then: (schema) =>
      schema.test(
        "is-valid-number",
        "Please enter a valid phone number",
        function (value) {
          const phoneNumber = value as string;
          const isPhoneValid = matchIsValidTel(phoneNumber);
 
          if (isPhoneValid) {
            this.createError({
              message: "Plese enter a valid phone Number",
              path: "servicePhoneNumber",
            });
          }
          return matchIsValidTel(phoneNumber);
        },
      ),
  })
  .when({
    is: (exists: string) => {
      return Boolean(exists) && exists === "+1";
    },
    then: (schema) =>
      schema.test(
        "is-empty-number",
        "Please enter a phone number",
        function (value, ctx) {
          const phoneNumber = value as string;
 
          return phoneNumber.length > 2 && matchIsValidTel(phoneNumber);
        },
      ),
  });
 
const enterpriseInfoSchema = Yup.object().shape({
  name: Yup.string().required(VALIDATION_MESSAGES.REQUIRED),
  permalink: Yup.string().required(),
  purpose: Yup.string(),
  servicePhoneNumber: CustomPhoneSchema,
  websiteURL: urlSchema({ isRequired: true }),
  serviceCountriesOutUSCanada: Yup.boolean(),
  countriesServicedOutside: Yup.string(),
});