All files / src/features/Merchants/MerchantSidePanel/Modals EditProviderInfo.tsx

85.71% Statements 48/56
65.71% Branches 46/70
73.33% Functions 11/15
84.31% Lines 43/51

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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532                                                                                                                                                        1x   23x 23x 23x 23x 23x 23x 23x 1x                                             23x 23x   23x         23x 4x         23x         23x                   23x 23x   23x 2x   1x         1x     23x 2x   1x     1x         1x 1x     23x 4x   3x 3x     23x       23x 1x                 23x 1x     23x                       23x                                                                                   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                               23x                                                                         322x 299x                                
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Grid } from "@mui/material";
import { useTranslation } from "react-i18next";
import { namespaces } from "localization/resources/i18n.constants";
import { checkPortals } from "@utils/routing";
import { useEffect, useMemo } from "react";
import { removeSpecialChars } from "@utils/slug";
import FadeUpWrapper from "@components/animation/FadeUpWrapper";
import {
  BILLING_DESCRIPTOR_MAX_LENGTH,
  BUSINESS_PURPOSE_FIELD,
  MERCHANT_PERMALINK_FIELD,
  SLUG_MAX_CHARACTER_LENGTH,
} from "@constants/constants";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { useAppSelector } from "@redux/hooks";
import { selectMerchantPreview } from "@redux/slices/merchantPreview";
import {
  TClassificationsAPIResponse,
  useBusinessClassification,
} from "@components/Signup/Forms/hooks/useBusinessClassification";
import { getEditMerchantInfoSchema } from "@validation/merchant";
import { useUpdateMerchantInfo } from "@components/Merchants/MerchantPreview/hooks/useUpdateMerchantInfo";
import {
  TMerchantInfo,
  TStatusReview,
} from "@components/Merchants/MerchantPreview/data.types";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveButton from "@shared/Button/GiveButton";
import NameInput from "../components/NameInput/NameInput";
import WebsiteInput from "../components/WebsiteInput/WebsiteInput";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import MerchantSlugInput from "../components/MerchantSlugInput/MerchantSlugInput";
import { HFGiveTelephone } from "@shared/HFInputs/HFGiveTelephone/HFGiveTelephone";
import { getServicePhoneNumber } from "@utils/helpers";
import { InverseRHFCheckbox } from "@common/Checkbox/Checkbox";
import {
  BUSINESS_CUNDUCTED_OUTSIDE_USA,
  ENTER_COUNTRIES_OUTSIDE_USA,
  getMerchantProviderText,
  SERVICE_OUTSIDE_USA_CANADA_STRING,
} from "@constants/stringConstants";
import { SAVE_CHANGES_MODAL } from "modals/modal_names";
import MCCInput from "../components/UnderwriterRiskAnalystAssignCard/MCCInput";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import HFGiveCustomAmount from "@shared/HFInputs/HFGiveCustomAmount/HFGiveCustomAmount";
import { formatBillingDescriptor } from "../helpers";
 
type FormInputs = {
  merchantName: string;
  merchantSlug: string;
  websiteURL: string;
  servicePhoneNumber: string;
  description: string;
  isOutsideUSA: boolean;
  countriesOutside: string;
  classification: string;
  classification_description: string;
  category: number | "";
  billingDescriptor: string;
  estimatedAnnualRevenue: string;
  averageTicketAmount: string;
  highTicketAmount: string;
};
 
interface ModalProps {
  id: number;
  data: TMerchantInfo;
  status?: TStatusReview;
}
 
const EditProviderInfoModal = NiceModal.create(
  ({ id, data, status }: ModalProps) => {
    const { sectionFocus } = useAppSelector(selectMerchantPreview);
    const { palette } = useAppTheme();
    const { t } = useTranslation(namespaces.pages.enterprise.createMerchant);
    const { isAcquirerPortal } = checkPortals();
    const modal = useModal();
    const open = modal.visible;
    const defaultData = useMemo(
      () => ({
        merchantName: data.merchantName || "",
        merchantSlug: data.merchantSlug || "",
        websiteURL: data.websiteURL || "",
        servicePhoneNumber:
          getServicePhoneNumber(data?.servicePhoneNumber) || "",
        description: data.description || "",
        isOutsideUSA: data.serviceCountriesOutUSCanada || false,
        countriesOutside: data.countriesServicedOutside || "",
        classification:
          (typeof data.classification !== "string"
            ? data.classification?.name
            : data.classification) || "",
        classification_description: data?.classCustomDescription || "",
        category: data.categoryCodeID || "",
        billingDescriptor: data.billingDescriptor || "",
        estimatedAnnualRevenue: data.estimatedAnnualRevenue || "",
        averageTicketAmount: data.averageTicketAmount || "",
        highTicketAmount: data.highTicketAmount || "",
      }),
      [data],
    );
 
    const { handleSubmit, isLoading } = useUpdateMerchantInfo(id);
    const schema = getEditMerchantInfoSchema(isAcquirerPortal, true);
 
    const isEditAllowed = useAccessControl({
      resource: RESOURCE_BASE.ENTERPRISE,
      operation: OPERATIONS.UPDATE,
    });
 
    const classificationsParser = (res: TClassificationsAPIResponse) =>
      res?.data?.map(({ name, displayName }) => ({
        value: name,
        label: `${displayName}`,
      }));
 
    const { data: classificationOptions } = useBusinessClassification(
      "manage_submerchants",
      classificationsParser,
    );
 
    const methods = useForm<FormInputs>({
      resolver: yupResolver(schema),
      defaultValues: defaultData as FormInputs,
    });
 
    const {
      reset,
      watch,
      setValue,
      formState: { isDirty, isValid },
    } = methods;
    const values = watch();
 
    useEffect(() => {
      if (!isDirty) return;
 
      const slug = removeSpecialChars(
        values.merchantName,
        SLUG_MAX_CHARACTER_LENGTH,
      );
 
      setValue("merchantSlug", slug);
    }, [values.merchantName]);
 
    useEffect(() => {
      if (!isDirty) return;
 
      const descriptor = formatBillingDescriptor(
        values.merchantName.slice(0, BILLING_DESCRIPTOR_MAX_LENGTH),
      );
      const slug = removeSpecialChars(
        values.merchantName,
        SLUG_MAX_CHARACTER_LENGTH,
      );
 
      setValue("billingDescriptor", descriptor);
      setValue("merchantSlug", slug);
    }, [values.merchantName]);
 
    useEffect(() => {
      if (!isDirty) return;
 
      const descriptor = formatBillingDescriptor(values.billingDescriptor);
      setValue("billingDescriptor", descriptor);
    }, [values.billingDescriptor]);
 
    const handleClose = () => {
      reset();
      modal.remove();
    };
    const handleSave = (customData: any) => {
      handleSubmit(
        "merchant_info",
        {
          ...customData,
        },
        handleClose,
      );
    };
 
    const onSubmit: SubmitHandler<FormInputs> = (customData: any) => {
      handleSave(customData);
    };
 
    const handleCancel = () => {
      if (isDirty && isValid) {
        NiceModal.show(SAVE_CHANGES_MODAL, {
          modalName: `Edit ${getMerchantProviderText(false, true)}`,
          handleCancel: () => handleClose(),
          handleSave: () => handleSave(values),
        });
        return;
      }
      handleClose();
    };
 
    const inputList = [
      {
        input: (
          <NameInput
            data-testid="merchant-name-input"
            id="merchantName"
            label="Provider Name"
            name="merchantName"
            placeholder="Provider Name"
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "merchantName"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveSelect
            label={"Classification"}
            name="classification"
            id="classification"
            options={classificationOptions || []}
            disabled={!isEditAllowed}
          />
        ),
        sm: 12,
      },
      {
        input: (
          <MCCInput
            name="category"
            categoryCodeID={values.category}
            code={values.category ? data.category : undefined}
            categoryCodeName={
              values.category ? data.categoryCodeName : undefined
            }
            withAPI={false}
            setFormValue={(val) =>
              setValue("category", val, { shouldDirty: true })
            }
            isProvider
            status={status}
            contextualMenuProps={{
              anchorOrigin: {
                vertical: "bottom",
                horizontal: "center",
              },
              transformOrigin: {
                vertical: "top",
                horizontal: "center",
              },
            }}
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveInput
            id="billingDescriptor"
            name="billingDescriptor"
            label={"Billing Descriptor"}
            fullWidth
            leftContent={
              <GiveText color="secondary" variant="bodyS">
                {data?.billingDescriptorPrefix}*
              </GiveText>
            }
            inputProps={{ maxLength: BILLING_DESCRIPTOR_MAX_LENGTH }}
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "billingDescriptor"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveInput
            label="Describe your business"
            name="classification_description"
            multiline
            rows={6}
            fullWidth
          />
        ),
        sm: 12,
        hidden: values.classification !== "other",
      },
      {
        input: (
          <HFGiveTelephone
            id="servicePhoneNumber"
            label="Provider Phone Number"
            placeholder="Phone Number"
            name="servicePhoneNumber"
            fullWidth
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "servicePhoneNumber"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ),
        sm: 12,
      },
      {
        input: (
          <MerchantSlugInput
            id="merchantSlug"
            name="merchantSlug"
            isProvider
            label={MERCHANT_PERMALINK_FIELD}
            placeholder={MERCHANT_PERMALINK_FIELD}
            parentName={data.parentSlug}
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "merchantSlug"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ),
        sm: 12,
      },
      {
        input: (
          <WebsiteInput
            id="websiteURL"
            name="websiteURL"
            label="Business Website"
            disabled={!isEditAllowed}
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveCustomAmount
            data-testid="estimated-annual-revenue-input"
            id="estimatedAnnualRevenue"
            name="estimatedAnnualRevenue"
            label="Estimated Annual Revenue"
            placeholder="ex. 900"
            bounded={false}
            initialValue={defaultData.estimatedAnnualRevenue}
            currency="usd"
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "estimatedAnnualRevenue"
                ? palette?.primitive?.blue[50]
                : ""
            }
            min={0}
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveCustomAmount
            data-testid="average-ticket-amount-input"
            id="averageTicketAmount"
            name="averageTicketAmount"
            label="Average Ticket Amount"
            placeholder="ex. 900"
            bounded={false}
            initialValue={defaultData.averageTicketAmount}
            currency="usd"
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "averageTicketAmount"
                ? palette?.primitive?.blue[50]
                : ""
            }
            min={0}
          />
        ),
        sm: 12,
      },
      {
        input: (
          <HFGiveCustomAmount
            data-testid="high-ticket-amount-input"
            id="highTicketAmount"
            name="highTicketAmount"
            label="High Ticket Amount"
            placeholder="ex. 900"
            bounded={false}
            initialValue={defaultData.highTicketAmount}
            currency="usd"
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "highTicketAmount"
                ? palette?.primitive?.blue[50]
                : ""
            }
            min={0}
          />
        ),
        sm: 12,
      },
 
      {
        input: (
          <HFGiveInput
            id="description"
            name="description"
            label={BUSINESS_PURPOSE_FIELD}
            placeholder={BUSINESS_PURPOSE_FIELD}
            multiline
            rows={6}
            fullWidth
            disabled={!isEditAllowed}
            inputProps={{
              maxLength: "600",
            }}
            helperText={`${600 - values.description.length} ${t(
              "characters_remaining",
              { ns: namespaces.common },
            )}`}
            focusViewColor={
              sectionFocus.field === "description"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ),
        sm: 12,
      },
      {
        sm: 12,
        input: (
          <InverseRHFCheckbox
            name="isOutsideUSA"
            label={SERVICE_OUTSIDE_USA_CANADA_STRING}
            disabled={!isEditAllowed}
            dataTestId="isOutsideUSA-checkbox"
          />
        ),
      },
      {
        input: values.isOutsideUSA ? (
          <HFGiveInput
            id="countriesOutside"
            name="countriesOutside"
            label={BUSINESS_CUNDUCTED_OUTSIDE_USA}
            placeholder={ENTER_COUNTRIES_OUTSIDE_USA}
            multiline
            rows={6}
            fullWidth
            disabled={!isEditAllowed}
            focusViewColor={
              sectionFocus.field === "countriesOutside"
                ? palette?.primitive?.blue[50]
                : ""
            }
          />
        ) : (
          <></>
        ),
        sm: 12,
        shouldAnimate: false,
      },
    ];
 
    return (
      <GiveBaseModal
        open={open}
        title={"Edit Provider Info"}
        width="720px"
        onClose={handleCancel}
        buttons={
          <>
            <GiveButton
              variant="ghost"
              size="large"
              label="Cancel"
              onClick={handleCancel}
              disabled={isLoading}
            />
 
            <GiveButton
              size="large"
              variant="filled"
              label="Save"
              type="submit"
              form="edit-merchant-info-form"
              disabled={isLoading}
              sx={{ border: "none" }}
            />
          </>
        }
      >
        <FormProvider {...methods}>
          <FadeUpWrapper delay={100}>
            <Box
              component="form"
              id="edit-merchant-info-form"
              onSubmit={methods.handleSubmit(onSubmit)}
            >
              <Grid container spacing={2.5}>
                {inputList.map(({ input, sm, hidden }, index) => {
                  if (hidden) return null;
                  return (
                    <Grid key={index} item xs={12} sm={sm || 6}>
                      {input}
                    </Grid>
                  );
                })}
              </Grid>
            </Box>
          </FadeUpWrapper>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
export default EditProviderInfoModal;