All files / src/components/Merchants/MerchantPreview/hooks useUpdateBankAccountSettings.ts

94.44% Statements 17/18
80.95% Branches 17/21
80% Functions 4/5
93.33% Lines 14/15

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              44x       183x   183x   183x               183x   183x       3x   2x                                   2x   1x       1x       1x     1x         183x    
import { customInstance } from "@services/api";
import { useMutation, useQueryClient } from "react-query";
import { showMessage } from "@common/Toast";
import { TMerchantBankAccountSettings } from "../data.types";
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
 
export const useUpdateBankAccountSettings = (
  merchantId: number,
  defaultValues?: TMerchantBankAccountSettings,
) => {
  const queryClient = useQueryClient();
  const { money_transfers, bank_account_linking, manage_bank_account } =
    useEnterprisePermissions();
 
  const updateMerchantMutation = useMutation((data: any) => {
    return customInstance({
      url: `/merchants/${merchantId}`,
      method: "PATCH",
      data,
    });
  });
 
  const { isLoading } = updateMerchantMutation;
 
  const handleUpdateBankAccountSettings = (
    data: any,
    onSuccess?: () => void,
  ) => {
    if (!merchantId) return;
 
    const customData = {
      ...(manage_bank_account &&
        typeof data?.allowBankAccounts === "boolean" &&
        defaultValues?.allowBankAccounts !== data?.allowBankAccounts && {
          allowAddingBankAccounts: data.allowBankAccounts,
        }),
      ...(bank_account_linking &&
        data.linkedAccountID !== 0 &&
        defaultValues?.linkedAccountID !== data?.linkedAccountID && {
          linkedBankAccountID: data.linkedAccountID,
        }),
      ...(money_transfers &&
        typeof data?.allowTransfers === "boolean" &&
        defaultValues?.allowTransfers !== data?.allowTransfers && {
          submerchantAllowedToTransfer: data?.allowTransfers,
        }),
    };
 
    updateMerchantMutation.mutate(customData, {
      onSuccess: (res: any) => {
        queryClient.setQueryData(
          [MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET, merchantId],
          res,
        );
        Eif (onSuccess) onSuccess();
      },
      onError: (err: any) => {
        const message =
          err?.response?.data?.input[0].message ||
          err?.response?.data?.message ||
          err?.message;
        Eif (message) showMessage("Error", message);
      },
    });
  };
 
  return { handleUpdateBankAccountSettings, isLoading };
};