All files / src/hooks/enterprise-api/settings useUpdateEnterpriseFees.tsx

86.36% Statements 38/44
88.88% Branches 24/27
80% Functions 8/10
85.36% Lines 35/41

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                                                            2x     33x 33x 33x         33x   33x   33x 9x                 4x                     33x         33x           33x   33x     33x 15x 11x 8x 6x     33x 2x           33x                                         33x         33x     2x 6x         2x 4x               2x                           2x             2x           2x         2x 2x               33x                     2x          
import * as Yup from "yup";
import { SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useMutation, useQueryClient } from "react-query";
import { customInstance } from "@services/api";
import { showMessage } from "@common/Toast";
import { AxiosError } from "axios";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import { useGetMerchantById } from "../account/useGetMerchants";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { useGetCurrentMerchantId } from "@hooks/common";
import {
  QKEY_GET_ALL_CATEGORIES_CODES,
  QKEY_GET_MERCHANT_BY_ID,
} from "@constants/queryKeys";
import { getFeesValidationSchema } from "@utils/validation.helpers";
import { MCCType } from "@hooks/acquirer-api/MCCType";
import { checkPortals } from "@utils/routing";
import { useEffect, useMemo } from "react";
 
type MerchantSettingsConfigurationType = {
  merchant_global_fees: {
    credit_card_fee: string;
    amex_credit_card_fee: string;
    debit_card_fee: string;
  };
  merchant_category_codes: MCCType[];
};
 
const useUpdateEnterpriseFees = (
  portal: "enterprise" | "acquirer" = "enterprise",
) => {
  const { merchantId } = useGetCurrentMerchantId();
  const { isDesktopView } = useCustomTheme();
  const { data, isLoading, isFetching } = useGetMerchantById({
    merchantId,
    enabled: !!merchantId,
  });
 
  const { isAcquirerCategoryCodes } = checkPortals();
 
  const prefix = portal === "enterprise" ? "Provider" : "Acquirer";
 
  const defaultValues = useMemo(
    () => ({
      merchant_global_fees: {
        credit_card_fee: data?.feeConfig?.creditCardFee?.adjustmentPercent ?? 0,
        amex_credit_card_fee:
          data?.feeConfig?.amexCreditCardFee?.adjustmentPercent ?? 0,
        debit_card_fee: data?.feeConfig?.debitCardFee?.adjustmentPercent ?? 0,
      },
      merchant_category_codes:
        data?.allowedCategoryCodes?.map(
          (category: any) => category.categoryCodes,
        ) || [],
    }),
    [
      data?.feeConfig?.amexCreditCardFee?.adjustmentPercent,
      data?.feeConfig?.creditCardFee?.adjustmentPercent,
      data?.feeConfig?.debitCardFee?.adjustmentPercent,
      data?.allowedCategoryCodes,
    ],
  );
 
  const methods = useForm<MerchantSettingsConfigurationType>({
    resolver: yupResolver(schema),
    mode: "onBlur",
    defaultValues,
  });
  const queryClient = useQueryClient();
 
  const {
    reset,
    watch,
    formState: { isDirty, dirtyFields },
  } = methods;
 
  const values = watch();
 
  // RHF only applies `defaultValues` on first render; when async data arrives, we need to hydrate the form.
  useEffect(() => {
    if (isLoading) return;
    if (!data?.feeConfig) return;
    if (isDirty) return;
    reset(defaultValues);
  }, [data?.feeConfig, defaultValues, isDirty, isLoading, reset]);
 
  const updateMerchant = useMutation((payload: any) =>
    customInstance({
      url: `/merchants/${merchantId}`,
      method: "PATCH",
      data: payload,
    }),
  );
  const feeInputs = [
    {
      name: "merchant_global_fees.credit_card_fee",
      label: "Credit Card Fee",
      fixedFeeRate: data?.feeConfig?.creditCardFee.baselineFixed / 100,
      acquirerFee: data?.feeConfig?.creditCardFee.baselinePercent,
    },
    {
      name: "merchant_global_fees.amex_credit_card_fee",
      label: "AMEX Credit Card Fee",
      fixedFeeRate: data?.feeConfig?.amexCreditCardFee.baselineFixed / 100,
      acquirerFee: data?.feeConfig?.amexCreditCardFee.baselinePercent,
    },
    {
      name: "merchant_global_fees.debit_card_fee",
      label: "Debit Card Fee",
      fixedFeeRate: data?.feeConfig?.debitCardFee.baselineFixed / 100,
      acquirerFee: data?.feeConfig?.debitCardFee.baselinePercent,
    },
  ];
 
  const isEditAllowed = useAccessControl({
    resource: RESOURCE_BASE.ENTERPRISE,
    operation: OPERATIONS.UPDATE,
  });
 
  const handleSubmit: SubmitHandler<MerchantSettingsConfigurationType> = (
    payload,
  ) => {
    const addFeeProperty = (payloadField: string, formField: string) => {
      if (
        !dirtyFields?.merchant_global_fees?.[
          formField as keyof typeof dirtyFields.merchant_global_fees
        ]
      )
        return;
      return {
        [payloadField]:
          +payload.merchant_global_fees[
            formField as keyof typeof payload.merchant_global_fees
          ],
      };
    };
 
    const updatedPayload = {
      // Fees
      ...addFeeProperty("defaultSubCreditCardFees", "credit_card_fee"),
      ...addFeeProperty("defaultSubAmexCreditCardFees", "amex_credit_card_fee"),
      ...addFeeProperty("defaultSubDebitCardFees", "debit_card_fee"),
 
      // Category Codes
      ...(dirtyFields.merchant_category_codes && {
        allowedCategoryCodes: values.merchant_category_codes.map(
          (category: any) => category.id,
        ),
      }),
    };
 
    updateMerchant.mutate(updatedPayload, {
      onError: (error: unknown) => {
        reset(defaultValues);
        const axiosError = error as AxiosError;
        showMessage("Error", axiosError.message, isDesktopView);
      },
      onSuccess: async () => {
        await queryClient.invalidateQueries(QKEY_GET_MERCHANT_BY_ID),
          showMessage(
            "Success",
            `${prefix} infos have been changed`,
            isDesktopView,
          );
        Iif (isAcquirerCategoryCodes) {
          queryClient.invalidateQueries(QKEY_GET_ALL_CATEGORIES_CODES);
          queryClient.invalidateQueries("list-acquirer-category-codes");
        }
 
        const updatedData = queryClient.getQueryData(QKEY_GET_MERCHANT_BY_ID);
        reset(updatedData || methods.getValues(), {
          keepValues: true,
          keepDirty: false,
        });
      },
    });
  };
 
  return {
    methods,
    isDisabled: !isDirty || updateMerchant.isLoading,
    handleSubmit,
    isEditAllowed,
    isLoading,
    isFetching,
    feeInputs,
  };
};
 
const schema = Yup.object().shape({
  merchant_global_fees: getFeesValidationSchema(0, 1000, "Value"),
});
 
export default useUpdateEnterpriseFees;