All files / src/components/Merchants/MerchantPreview/modals EditMerchantInfoModal.tsx

94.28% Statements 66/70
55.55% Branches 40/72
90% Functions 18/20
95.23% Lines 60/63

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 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577                                                                                                  68x 7x 7x                                                   68x 32x 32x 32x 32x 32x 32x   32x 32x   32x         32x 8x         32x         32x 32x 6x             32x                                   32x                   32x 32x 32x 2x                                                       32x 2x               32x 6x   2x     2x         2x 2x     32x 7x   3x       3x     32x 8x   4x 4x     32x           32x 32x   96x           32x 4x 12x   4x 4x     32x 1x 3x   1x                     32x 32x 32x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           32x                                                                                               448x                                 68x        
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { TMerchantInfo } from "../data.types";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Grid } from "@mui/material";
import { Button } from "@common/Button";
import { useTranslation } from "react-i18next";
import { namespaces } from "localization/resources/i18n.constants";
import { MerchantSlugInput, NameInput } from "@common/BusinessProfileInputs";
import { checkPortals } from "@utils/routing";
import { RHFInput, RHFTelInput } from "@common/Input";
import { RHFSelect } from "@common/Select";
import { useListEnterpriseCategoryCodes } from "@hooks/enterprise-api/merchants/useListEnterpriseCategoryCodes";
import { useEffect, useMemo } from "react";
import { useUpdateMerchantInfo } from "../hooks/useUpdateMerchantInfo";
import EditMerchantBaseModal from "../components/EditMerchantBaseModal";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { removeSpecialChars } from "@utils/slug";
import FadeUpWrapper from "@components/animation/FadeUpWrapper";
import {
  BILLING_DESCRIPTOR_MAX_LENGTH,
  BUSINESS_PURPOSE_FIELD,
  MCC_LABEL,
  MERCHANT_PERMALINK_FIELD,
  SLUG_MAX_CHARACTER_LENGTH,
} from "@constants/constants";
import { RHFCustomAmountInput } from "@common/CustomAmountInput";
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 WebsiteInput from "@common/BusinessProfileInputs/WebsiteInput";
import RiskStatusChip from "@common/Tag/RiskStatusChip";
import { useGetMerchantRiskStatus } from "@components/Signup/Forms/hooks/useGetMerchantRiskStatus";
import CategoriSelectorWithSearch from "@common/BusinessProfileInputs/CategoriSelectorWithSearch";
import { InverseRHFCheckbox } from "@common/Checkbox/Checkbox";
import {
  BUSINESS_CUNDUCTED_OUTSIDE_USA,
  ENTER_COUNTRIES_OUTSIDE_USA,
  MERCHANT_FILE_TEXT,
  SERVICE_OUTSIDE_USA_CANADA_STRING,
} from "@constants/stringConstants";
import { SHOW_RISK_CATEGORY } from "@features/Merchants/MerchantSidePanel/constants";
import { getEditMerchantInfoSchema } from "@validation/merchant";
 
export const formatBillingDescriptor = (value?: string) => {
  Iif (!value) return "";
  return value.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
};
 
type FormInputs = {
  averageTicketAmount: string | null;
  highTicketAmount: string | null;
  merchantName: string;
  category: string;
  merchantSlug: string;
  websiteURL: string;
  billingDescriptor: string;
  servicePhoneNumber: string;
  enterprise?: number;
  description: string;
  estimatedAnnualRevenue: string | null;
  isOutsideUSA: boolean;
  countriesOutside: string;
  classification: string;
  merchantRiskStatus: string;
};
 
interface ModalProps {
  id: number;
  data: TMerchantInfo;
}
 
const EditMerchantInfoModal = NiceModal.create(({ id, data }: ModalProps) => {
  const { sectionFocus } = useAppSelector(selectMerchantPreview);
  const { t } = useTranslation(namespaces.pages.enterprise.createMerchant);
  const { isAcquirerPortal } = checkPortals();
  const { isMobileView } = useCustomTheme();
  const modal = useModal();
  const open = modal.visible;
 
  const { handleSubmit, isLoading } = useUpdateMerchantInfo(id);
  const schema = getEditMerchantInfoSchema(isAcquirerPortal);
 
  const isEditAllowed = useAccessControl({
    resource: RESOURCE_BASE.MERCHANT,
    operation: OPERATIONS.UPDATE,
  });
 
  const classificationsParser = (res: TClassificationsAPIResponse) =>
    res?.data?.map(({ name, displayName }) => ({
      value: name,
      label: `${displayName}`,
    }));
 
  const { data: classificationOptions } = useBusinessClassification(
    "accept_payments",
    classificationsParser,
  );
 
  const { categories } = useListEnterpriseCategoryCodes(data.enterpriseID);
  const categoriesOptions = useMemo(() => {
    return categories.map((category: any) => ({
      id: category.id,
      value: category.code,
      label: `${category.code} - ${category.title}`,
    }));
  }, [categories]);
 
  const defaultValues = {
    merchantName: "",
    category: "",
    merchantSlug: "",
    websiteURL: "",
    billingDescriptor: "",
    servicePhoneNumber: "",
    enterprise: 0,
    description: "",
    averageTicketAmount: "",
    highTicketAmount: "",
    estimatedAnnualRevenue: "",
    isOutsideUSA: false,
    countriesOutside: "",
    classification: "",
    merchantRiskStatus: "",
  };
 
  const methods = useForm<FormInputs>({
    resolver: yupResolver(schema),
    defaultValues,
  });
 
  const {
    reset,
    watch,
    setValue,
    formState: { isDirty },
  } = methods;
  const values = watch();
  useEffect(() => {
    reset({
      merchantName: data.merchantName,
      category: `${data.category || ""}`,
      merchantSlug: data.merchantSlug,
      websiteURL: data.websiteURL,
      billingDescriptor: data.billingDescriptor,
      servicePhoneNumber: data?.servicePhoneNumber
        ? data.servicePhoneNumber
        : "",
      enterprise: data.enterpriseID,
      description: data.description,
      averageTicketAmount: +data.averageTicketAmount
        ? data.averageTicketAmount
        : null,
      highTicketAmount: +data.highTicketAmount ? data.highTicketAmount : null,
      isOutsideUSA: data.serviceCountriesOutUSCanada,
      countriesOutside: data.countriesServicedOutside,
      estimatedAnnualRevenue: +data.estimatedAnnualRevenue
        ? data.estimatedAnnualRevenue
        : null,
      classification:
        typeof data?.classification === "string"
          ? data?.classification
          : data.classification?.name,
      merchantRiskStatus: data.merchantRiskStatus,
    });
  }, [id, data]);
 
  const enterpriseOptions = useMemo(() => {
    return [
      {
        label: data?.enterprise,
        value: data?.enterpriseID,
      },
    ];
  }, [data]);
 
  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 slug = removeSpecialChars(
      values.merchantSlug,
      SLUG_MAX_CHARACTER_LENGTH,
    );
    setValue("merchantSlug", slug);
  }, [values.merchantSlug]);
 
  useEffect(() => {
    if (!isDirty) return;
 
    const descriptor = formatBillingDescriptor(values.billingDescriptor);
    setValue("billingDescriptor", descriptor);
  }, [values.billingDescriptor]);
 
  const handleCancel = () => {
    reset();
    modal.hide();
  };
 
  const { data: merchantRiskStatuses, isLoading: isLoadingRiskStatus } =
    useGetMerchantRiskStatus(values.category);
  const riskStatusOptions = useMemo(
    () =>
      merchantRiskStatuses?.map((status) => ({
        ...status,
        label: <RiskStatusChip riskLevelName={status.value} />,
      })) || [],
    [merchantRiskStatuses],
  );
  useEffect(() => {
    const selectedCategory = categories.find((c) => {
      return c.code === values.category;
    });
    const newStatus = selectedCategory?.riskStatus;
    newStatus && setValue("merchantRiskStatus", newStatus);
  }, [values.category]);
 
  const onSubmit: SubmitHandler<FormInputs> = (customData: any) => {
    const selectedCategory = categoriesOptions.find(
      (category) => category.value === customData.category,
    );
    handleSubmit(
      "merchant_info",
      {
        ...customData,
        category: selectedCategory?.id,
        parentSlug: data.parentSlug,
      },
      handleCancel,
    );
  };
 
  const disableRiskStatus = !isAcquirerPortal || !values.category;
  const isActionsDisabeled = !isDirty || isLoading || isLoadingRiskStatus;
  const inputList = [
    {
      input: (
        <NameInput
          data-testid="merchant-name-input"
          id="merchantName"
          label={t("merchant_name")}
          name="merchantName"
          placeholder={t("merchant_name_placeholder")}
          isMerchantName
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "merchantName" ? "#6D9CF8" : ""
          }
        />
      ),
    },
    {
      input: (
        <RHFSelect
          label={t("Classification")}
          name="classification"
          id="classification"
          options={classificationOptions}
          disabled={!isEditAllowed}
        />
      ),
    },
    {
      input: (
        <CategoriSelectorWithSearch
          fullWidth
          label={MCC_LABEL}
          name="category"
          placeholder={MCC_LABEL}
          providerId={data.enterpriseID}
          isAcquirer={isAcquirerPortal}
          disabled={!isEditAllowed}
          saveWithCodeProperty
        />
      ),
      sm: 12,
    },
    ...(SHOW_RISK_CATEGORY
      ? [
          {
            input: (
              <RHFSelect
                id="merchantRiskStatus"
                label="Merchant Risk Category"
                name="merchantRiskStatus"
                placeholder="Merchant Risk Category"
                options={riskStatusOptions}
                focusViewColor={
                  sectionFocus.field === "merchantRiskStatus" ? "#6D9CF8" : ""
                }
                disabled={disableRiskStatus || !isEditAllowed}
                helperText={
                  !values.category &&
                  isAcquirerPortal &&
                  "Select a Merchant Category first. Risk category changes only affect this merchant."
                }
              />
            ),
            sm: 12,
          },
        ]
      : []),
    {
      input: (
        <RHFSelect
          label="Provider"
          name="enterprise"
          id="enterprise"
          options={enterpriseOptions}
          focusViewColor={sectionFocus.field === "enterprise" ? "#6D9CF8" : ""}
          fullWidth
          disabled
        />
      ),
      hidden: !isAcquirerPortal,
    },
    {
      input: (
        <RHFInput
          id="billingDescriptor"
          name="billingDescriptor"
          label={"Billing Descriptor"}
          fullWidth
          inputPrefix={`${data?.billingDescriptorPrefix}*`}
          inputProps={{ maxLength: BILLING_DESCRIPTOR_MAX_LENGTH }}
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "billingDescriptor" ? "#6D9CF8" : ""
          }
        />
      ),
    },
    {
      input: (
        <MerchantSlugInput
          id="merchantSlug"
          name="merchantSlug"
          label={MERCHANT_PERMALINK_FIELD}
          placeholder={MERCHANT_PERMALINK_FIELD}
          parentName={data.parentSlug}
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "merchantSlug" ? "#6D9CF8" : ""
          }
        />
      ),
      sm: 12,
    },
    {
      input: (
        <WebsiteInput
          id="websiteURL"
          name="websiteURL"
          label={t("Website URL")}
          disabled={!isEditAllowed}
          focusViewColor={sectionFocus.field === "websiteURL" ? "#6D9CF8" : ""}
        />
      ),
      sm: 12,
    },
    {
      input: (
        <RHFTelInput
          id="servicePhoneNumber"
          label={`Merchant Phone Number`}
          name="servicePhoneNumber"
          fullWidth
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "servicePhoneNumber" ? "#6D9CF8" : ""
          }
        />
      ),
    },
    {
      input: (
        <RHFCustomAmountInput
          data-testid="estimated-annual-revenue-input"
          id="estimatedAnnualRevenue"
          name="estimatedAnnualRevenue"
          label="Estimated Annual Revenue"
          placeholder="ex. 900"
          bounded={false}
          initialValue={data.estimatedAnnualRevenue}
          currency="usd"
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "estimatedAnnualRevenue" ? "#6D9CF8" : ""
          }
        />
      ),
      sm: 6,
    },
    {
      input: (
        <RHFCustomAmountInput
          data-testid="average-ticket-amount-input"
          id="averageTicketAmount"
          name="averageTicketAmount"
          label="Average Ticket Amount"
          placeholder="ex. 900"
          bounded={false}
          initialValue={data.averageTicketAmount}
          currency="usd"
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "averageTicketAmount" ? "#6D9CF8" : ""
          }
        />
      ),
      sm: 6,
    },
    {
      input: (
        <RHFCustomAmountInput
          data-testid="high-ticket-amount-input"
          id="highTicketAmount"
          name="highTicketAmount"
          label="High Ticket Amount"
          placeholder="ex. 900"
          bounded={false}
          initialValue={data.highTicketAmount}
          currency="usd"
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "highTicketAmount" ? "#6D9CF8" : ""
          }
        />
      ),
      sm: 6,
    },
    {
      input: (
        <RHFInput
          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" ? "#6D9CF8" : ""}
        />
      ),
      sm: 12,
    },
    {
      sm: 12,
      input: (
        <InverseRHFCheckbox
          name="isOutsideUSA"
          label={SERVICE_OUTSIDE_USA_CANADA_STRING}
          disabled={!isEditAllowed}
          dataTestId="isOutsideUSA-checkbox"
        />
      ),
    },
    {
      input: values.isOutsideUSA ? (
        <RHFInput
          id="countriesOutside"
          name="countriesOutside"
          label={BUSINESS_CUNDUCTED_OUTSIDE_USA}
          placeholder={ENTER_COUNTRIES_OUTSIDE_USA}
          multiline
          rows={6}
          fullWidth
          disabled={!isEditAllowed}
          focusViewColor={
            sectionFocus.field === "countriesOutside" ? "#6D9CF8" : ""
          }
        />
      ) : (
        <></>
      ),
      sm: 12,
      shouldAnimate: false,
    },
  ];
 
  return (
    <EditMerchantBaseModal
      title={`Edit ${MERCHANT_FILE_TEXT}`}
      open={open}
      handleCancel={handleCancel}
      actions={
        <>
          <Button
            size="medium"
            background="tertiary"
            onClick={handleCancel}
            disabled={isActionsDisabeled}
            sx={{
              padding: "8px 24px",
              ...(isMobileView && {
                width: "50%",
              }),
            }}
          >
            Discard changes
          </Button>
          <Button
            data-testid="save-button"
            size="medium"
            background="primary"
            type="submit"
            form="edit-merchant-info-form"
            disabled={isActionsDisabeled}
            sx={{
              padding: "8px 24px",
              ...(isMobileView && {
                width: "50%",
              }),
            }}
          >
            Save
          </Button>
        </>
      }
    >
      <FormProvider {...methods}>
        <Box
          component="form"
          id="edit-merchant-info-form"
          onSubmit={methods.handleSubmit(onSubmit)}
        >
          <Grid container spacing={1}>
            {inputList.map(({ input, hidden, sm }, index) => (
              <Grid
                key={index}
                item
                xs={12}
                sm={sm || 6}
                sx={{ ...(hidden && { display: "none" }) }}
              >
                <FadeUpWrapper delay={100 * (index + 1)}>{input}</FadeUpWrapper>
              </Grid>
            ))}
          </Grid>
        </Box>
      </FormProvider>
    </EditMerchantBaseModal>
  );
});
 
const getDelay = (index: number) =>
  100 * ((index + 1) / 2 === 0 ? index - 1 : index);
 
export default EditMerchantInfoModal;