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

75.32% Statements 58/77
70.83% Branches 34/48
65.21% Functions 15/23
77.77% Lines 56/72

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                                                                                    1x           1x 17x       102x 102x 102x 102x           102x       102x   102x                           17x       1x 17x           1x   17x 17x 17x 17x 17x 17x   17x   17x                   17x 17x   17x         17x 1x   1x                                           17x 1x     17x 1x     17x                       17x 3x               17x   51x 51x   51x                                                         17x                                                           17x                                                                                                         51x                   306x   243x                                               1x 201x 201x 201x 201x   201x                                                         1x         42x 42x   42x                         42x                               42x                    
import GiveAmexCardIcon from "@assets/iconsV2/GiveAmexCardIcon";
import GiveCardIcon from "@assets/iconsV2/GiveCardIcon";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import NiceModal from "@ebay/nice-modal-react";
import { Stack } from "@mui/material";
import { Box, CircularProgress, Grid } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveText from "@shared/Text/GiveText";
import { styled, useAppTheme } from "@theme/v2/Provider";
import { TFeeObject, TMerchantFees } from "../data.types";
import { CURRENCY } from "@constants/constants";
import { formatLargeNumber, parseAmount } from "@utils/index";
import { checkPortals } from "@utils/routing";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import React, { useEffect, useState } from "react";
import { PlusIcon } from "@phosphor-icons/react";
import HFGiveIntegerInput from "@shared/HFInputs/HFGiveInput/HFGiveIntegerInput";
import {
  FormProvider,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import { useUpdateMerchantInfo } from "../hooks/useUpdateMerchantInfo";
import { SAVE_CHANGES_MODAL } from "modals/modal_names";
import GiveLink from "@shared/Link/GiveLink";
 
type FormInputs = {
  credit_card_fee: string;
  amex_credit_card_fee: string;
  debit_card_fee: string;
};
 
type Props = {
  id: number;
  data: TMerchantFees;
  isProvider?: boolean;
};
 
const defaultValues = {
  credit_card_fee: "",
  amex_credit_card_fee: "",
  debit_card_fee: "",
};
 
const useCalculateFeePerTransaction = () => {
  const calculateFeePerTransaction = (
    fee: TFeeObject,
    isProvider?: boolean,
  ) => {
    Iif (!fee) return { fee: "", estimatedRevenue: "" };
    const globalFee = fee?.baselinePercent / 100;
    const baselineFixed = fee?.baselineFixed / 100;
    const providerFee = isProvider
      ? 0
      : (fee?.parentBaselinePercent || 0) / 100;
 
    // compare new inputted adjustment with the min value which is - baseline percent, it should be more
    const adjustmentPercent =
      (!fee.adjustmentPercent || isNaN(fee.adjustmentPercent)
        ? 0
        : fee.adjustmentPercent) / 100;
 
    const totalFee = globalFee + adjustmentPercent + providerFee;
 
    return {
      globalFee: `${parseAmount(globalFee)}% + ${baselineFixed} ${CURRENCY}`,
      totalFee: `${parseAmount(totalFee)}% + ${baselineFixed} ${CURRENCY}`,
      acquirerEstimatedRevenue: `${formatLargeNumber(
        (1e6 * (globalFee + adjustmentPercent)) / 100,
        0,
      )} per 1M ${CURRENCY}`,
      providerEstimatedRevenue: `${formatLargeNumber(
        (1e6 * (providerFee + adjustmentPercent)) / 100,
        0,
      )} per 1M ${CURRENCY}`,
    };
  };
 
  return { calculateFeePerTransaction };
};
 
// backend handles validation, errors are mapped to fields in onError callback
const getFeesValidationSchema = () =>
  Yup.object().shape({
    credit_card_fee: Yup.string().optional(),
    amex_credit_card_fee: Yup.string().optional(),
    debit_card_fee: Yup.string().optional(),
  });
 
const GiveEditFeesModal = NiceModal.create(
  ({ id, data, isProvider = false }: Props) => {
    const { open, onClose } = useNiceModal();
    const { isEnterprisePortal, isAcquirerPortal } = checkPortals();
    const { isMobileView } = useCustomThemeV2();
    const theme = useAppTheme();
    const { handleSubmit, isLoading } = useUpdateMerchantInfo(id);
    const { calculateFeePerTransaction } = useCalculateFeePerTransaction();
 
    const schema = getFeesValidationSchema();
 
    const methods = useForm<FormInputs>({
      resolver: yupResolver(schema),
      defaultValues,
      mode: "onChange",
    });
 
    const {
      reset,
      watch,
      formState: { isDirty, isValid },
    } = methods;
    const values = watch();
 
    const handleClose = () => {
      reset();
      onClose();
    };
 
    const onError = (error: any) => {
      const message: string = error?.response?.data?.message;
 
      Eif (!message) return;
 
      // split message into chunks
      const parts = message.split(",").map((p) => p.trim());
 
      // ordered: most specific first
      const fieldMap: { key: keyof FormInputs; match: RegExp }[] = [
        { key: "amex_credit_card_fee", match: /amex/i },
        { key: "credit_card_fee", match: /\bcredit card\b/i },
        { key: "debit_card_fee", match: /\bdebit card\b/i },
      ];
 
      parts.forEach((part) => {
        const field = fieldMap.find(({ match }) => match.test(part));
        if (field)
          methods.setError(field.key, {
            type: "manual",
            message: part,
          });
      });
    };
 
    const handleSave = (data: FormInputs) => {
      handleSubmit("fees", data, handleClose, onError);
    };
 
    const onSubmit: SubmitHandler<FormInputs> = (data: any) => {
      handleSave(data);
    };
 
    const handleCancel = () => {
      if (isDirty && isValid) {
        NiceModal.show(SAVE_CHANGES_MODAL, {
          modalName: `${isProvider ? "Provider" : "Merchant"} Fee`,
          handleCancel: () => handleClose(),
          handleSave: () => handleSave(values),
        });
        return;
      }
      handleClose();
    };
 
    useEffect(() => {
      reset({
        credit_card_fee: data.creditCardFee.adjustmentPercent.toString(),
        amex_credit_card_fee:
          data.amexCreditCardFee.adjustmentPercent.toString(),
        debit_card_fee: data.debitCardFee.adjustmentPercent.toString(),
      });
    }, [id, data]);
 
    const getFeeItems = (fee: TFeeObject, name: string) => {
      const { globalFee, providerEstimatedRevenue, acquirerEstimatedRevenue } =
        calculateFeePerTransaction(fee);
      const { totalFee } = calculateFeePerTransaction(fee, isProvider);
 
      return [
        {
          label: isAcquirerPortal ? "Global fee" : "Processing fee",
          value: globalFee,
        },
        {
          label: "Provider global",
          value: `${fee.parentBaselinePercent || 0} BPS`,
          hidden: isAcquirerPortal,
        },
        { label: "Additional markup", name },
        {
          label: "Provider fee",
          value: `${fee.parentBaselinePercent || 0} BPS`,
          hidden: isProvider || isEnterprisePortal,
        },
        {
          label: "Total",
          value: totalFee,
        },
        {
          label: "Estimated revenue",
          value: isEnterprisePortal
            ? providerEstimatedRevenue
            : acquirerEstimatedRevenue,
        },
      ];
    };
 
    const fees = [
      {
        title: "Credit Card",
        icon: <GiveCardIcon />,
        items: getFeeItems(
          { ...data.creditCardFee, adjustmentPercent: +values.credit_card_fee },
          "credit_card_fee",
        ),
      },
      {
        title: "Debit Card",
        icon: <GiveCardIcon />,
        items: getFeeItems(
          { ...data.debitCardFee, adjustmentPercent: +values.debit_card_fee },
          "debit_card_fee",
        ),
      },
      {
        title: "AMEX Credit Card",
        icon: <GiveAmexCardIcon />,
        items: getFeeItems(
          {
            ...data.amexCreditCardFee,
            adjustmentPercent: +values.amex_credit_card_fee,
          },
          "amex_credit_card_fee",
        ),
      },
    ];
 
    return (
      <GiveBaseModal
        title={`${isProvider ? "Provider" : "Merchant"} Fee`}
        open={open}
        onClose={handleCancel}
        width="840px"
        data-testid="edit-fees-modal"
        buttons={
          <>
            <GiveButton
              label="Cancel"
              size="large"
              onClick={handleCancel}
              variant="ghost"
              sx={{
                minWidth: "72px",
                minHeight: "42px !important",
                width: "fit-content !important",
              }}
            />
            <GiveButton
              label="Save"
              size="large"
              type="submit"
              form="edit-fees-form"
              disabled={!isDirty || !isValid || isLoading}
              endIcon={
                isLoading ? (
                  <CircularProgress
                    size={14}
                    style={{
                      color: theme?.palette.primitive?.neutral?.[0],
                    }}
                  />
                ) : undefined
              }
              sx={{
                whiteSpace: "nowrap",
                width: "fit-content !important",
              }}
            />
          </>
        }
      >
        <FormProvider {...methods}>
          <Grid
            component="form"
            id="edit-fees-form"
            container
            spacing={2}
            onSubmit={methods.handleSubmit(onSubmit)}
          >
            {fees.map(({ title, icon, items }) => (
              <Grid item xs={12} sm={isMobileView ? 12 : 6} key={title}>
                <Container>
                  <Stack direction="row" spacing={1.5} alignItems="center">
                    {icon}
                    <GiveText variant="bodyS" fontWeight="bold">
                      {title}
                    </GiveText>
                  </Stack>
                  <Stack spacing={1}>
                    {items
                      .filter((item) => !item.hidden)
                      .map((item) => (
                        <FeeItem
                          key={item.label}
                          label={item.label}
                          value={item.value}
                          name={item.name}
                        />
                      ))}
                  </Stack>
                </Container>
              </Grid>
            ))}
          </Grid>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
type FeeItemProps = {
  label: string;
  value: React.ReactNode;
  name?: string;
};
 
const FeeItem = ({ label, value, name }: FeeItemProps) => {
  const isText = typeof value === "string";
  const { watch } = useFormContext();
  const feeAmount = name ? +watch(name) : 0;
  const [isInput, setIsInput] = useState(feeAmount !== 0);
 
  return (
    <Stack
      key={label}
      direction={isInput ? "column" : "row"}
      spacing={1}
      justifyContent="space-between"
    >
      <GiveText variant="bodyS" color="secondary">
        {label}
      </GiveText>
      {isText ? (
        <GiveText variant="bodyS">{value}</GiveText>
      ) : (
        <AdditionalMarkup
          isInput={isInput}
          name={name as string}
          setIsInput={setIsInput}
        />
      )}
    </Stack>
  );
};
 
type AdditionalMarkupProps = {
  name: string;
  isInput: boolean;
  setIsInput: React.Dispatch<React.SetStateAction<boolean>>;
};
 
const AdditionalMarkup = ({
  name,
  isInput,
  setIsInput,
}: AdditionalMarkupProps) => {
  const { palette } = useAppTheme();
  const { isEnterprisePortal } = checkPortals();
 
  Iif (!isInput)
    return (
      <GiveLink
        Icon={PlusIcon}
        color="secondary"
        sx={{ alignItems: "center" }}
        onClick={() => setIsInput(true)}
        link="#"
      >
        Add
      </GiveLink>
    );
 
  return (
    <HFGiveIntegerInput
      name={name}
      endIcon="BPS"
      width="100%"
      max={9999}
      allowNegative={!isEnterprisePortal}
      sx={{
        "& .MuiInputBase-root.MuiOutlinedInput-root": {
          minHeight: "48px",
        },
      }}
    />
  );
};
 
const Container = styled(Box)(({ theme }) => ({
  borderRadius: "12px",
  display: "flex",
  flexDirection: "column",
  gap: "16px",
  padding: "20px",
  border: `1px solid ${theme.palette.border?.primary}`,
}));
 
export default GiveEditFeesModal;