All files / src/features/Merchants/MerchantSidePanel/GiveMerchantFile/hooks useStatusChangeBankAccount.tsx

35.71% Statements 25/70
5.88% Branches 2/34
21.05% Functions 4/19
38.46% Lines 25/65

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                                                  41x                                                         41x 140x   140x                                                                           140x             41x                                 140x         140x 140x 140x       140x       140x                                       140x                                                   140x             41x                 140x   140x                                                         140x       140x                     41x               140x                     140x         140x 140x                       140x        
import { useCallback } from "react";
import NiceModal from "@ebay/nice-modal-react";
import { useQueryClient } from "react-query";
 
import { useDeleteMutation } from "@common/Modal/DeleteModal/useDeleteMutation";
import { useRefetchCounters } from "@hooks/acquirer-api/merchants/stats/useGetMerchantCounters";
import { buildMerchantEndpoints } from "@services/api/utils.api";
import {
  MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS,
  UNDERWRITING_CHALLENGE_API_KEYS,
} from "@features/Merchants/MerchantSidePanel/constants";
import { useUpdateBankAccountSettings } from "@components/Merchants/MerchantPreview/hooks/useUpdateBankAccountSettings";
import { QKEY_LIST_ALL_BANK_ACCOUNTS } from "@constants/queryKeys";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
import { customInstance } from "@services/api";
import { showMessage } from "@common/Toast";
import { IMerchantBankAccount } from "@components/Merchants/MerchantPreview/data.types";
import { AxiosError } from "axios";
 
type BankAccountStatus = "approved" | "declined" | "update_requested";
 
/* -------------------------------------------------------------------------- */
/*                               Helper: Modal                                */
/* -------------------------------------------------------------------------- */
 
const showConfirmationModal = ({
  type,
  title,
  description,
  confirmText,
  onConfirm,
  hideCancel,
}: {
  type: string;
  title: string;
  description: React.ReactNode;
  confirmText?: string;
  onConfirm: () => void;
  hideCancel?: boolean;
}) => {
  NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
    modalType: type,
    title,
    description,
    customSubmitBtnText: confirmText,
    actions: { handleSuccess: { onClick: onConfirm } },
    hideCancel,
  });
};
 
/* -------------------------------------------------------------------------- */
/*                         Hook: PATCH bank account                           */
/* -------------------------------------------------------------------------- */
 
export const useBankAccountStatus = (merchantId?: number) => {
  const queryClient = useQueryClient();
 
  const updateStatus = useCallback(
    async (id: number, status: BankAccountStatus) => {
      try {
        const res = await customInstance({
          url: buildMerchantEndpoints(`bank-accounts/${id}/status`, merchantId),
          method: "PATCH",
          data: { status },
        });
 
        if (res?.id) {
          queryClient.invalidateQueries([
            MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_BANK_ACCOUNTS,
            merchantId,
          ]);
          queryClient.invalidateQueries([
            MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.PENDING_TASKS_LIST,
            merchantId,
          ]);
          queryClient.invalidateQueries([
            MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET,
            merchantId,
          ]);
          queryClient.invalidateQueries("get-merchant-msp-status");
          queryClient.invalidateQueries(
            UNDERWRITING_CHALLENGE_API_KEYS.GET_TASKS,
          );
          queryClient.invalidateQueries([
            ...UNDERWRITING_CHALLENGE_API_KEYS.GET_STATS,
            merchantId,
          ]);
        }
      } catch (err: any) {
        showMessage("Error", err?.message);
      }
    },
    [merchantId, queryClient],
  );
 
  return { updateStatus };
};
 
/* -------------------------------------------------------------------------- */
/*                         Hook: DELETE bank account                          */
/* -------------------------------------------------------------------------- */
 
const useBankAccountDeletion = ({
  merchantId,
  selectedRowID,
  bankName,
  isLinkedBASelected,
  onCloseModal,
  refetch,
  handleTransferInProgress,
}: {
  merchantId?: number;
  selectedRowID?: number | null;
  isLinkedBASelected: boolean;
  bankName?: string;
  refetch?: () => void;
  onCloseModal?: (data?: IMerchantBankAccount, id?: number) => void;
  handleTransferInProgress?: () => void;
}) => {
  const url = buildMerchantEndpoints(
    `bank-accounts/${selectedRowID}`,
    merchantId,
  );
 
  const queryClient = useQueryClient();
  const { handleRefetchCounters } = useRefetchCounters();
  const { handleUpdateBankAccountSettings } = useUpdateBankAccountSettings(
    merchantId ?? 0,
  );
 
  const cleanup = () => {
    if (onCloseModal && selectedRowID) onCloseModal(undefined, selectedRowID);
  };
 
  const { handleDelete: deleteBankAccount, mutation } = useDeleteMutation({
    url,
    onSuccess: () => {
      showMessage("Success", bankName, undefined, "Bank Account Deleted");
    },
    onError: (error: unknown) => {
      if (error instanceof AxiosError) {
        const pendingTransfer = error?.response?.data?.message?.includes(
          "bank account has pending transfers",
        );
        if (pendingTransfer) handleTransferInProgress?.();
      }
    },
    refetchQuerieKeys: [],
    invalidateQuerieKeys: [
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_BANK_ACCOUNTS,
      QKEY_LIST_ALL_BANK_ACCOUNTS,
    ],
  });
 
  const onConfirmDelete = () => {
    if (!merchantId) {
      handleRefetchCounters();
      cleanup();
      return;
    }
 
    if (isLinkedBASelected) {
      handleUpdateBankAccountSettings({
        linkedAccountID: null,
        onSuccess: () => {
          queryClient.invalidateQueries([
            MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.PENDING_TASKS_LIST,
            merchantId,
          ]);
          handleRefetchCounters();
          refetch?.();
          cleanup();
        },
      });
    } else {
      deleteBankAccount();
      cleanup();
    }
  };
 
  return { handleDelete: onConfirmDelete, mutation };
};
 
/* -------------------------------------------------------------------------- */
/*                        Hook: APPROVE / DECLINE logic                       */
/* -------------------------------------------------------------------------- */
 
const useBankAccountApproval = ({
  merchantId,
  selectedRowID,
  bankName,
}: {
  merchantId?: number;
  selectedRowID?: number | null;
  bankName?: string;
}) => {
  const { updateStatus } = useBankAccountStatus(merchantId);
 
  const openApprovalModal = useCallback(
    (status: Extract<BankAccountStatus, "approved" | "declined">) => {
      if (!selectedRowID) return;
      const isApprove = status === "approved";
 
      showConfirmationModal({
        type: isApprove ? "approved" : "declined-bank",
        title: `${isApprove ? "Approve" : "Decline"} Bank Account`,
        description: (
          <>
            Are you sure that you want to {isApprove ? "approve" : "decline"}{" "}
            <strong>“{bankName}”</strong> bank account?
          </>
        ),
        confirmText: `Yes, ${isApprove ? "Approve" : "Decline"}`,
        onConfirm: () => {
          updateStatus(selectedRowID, status);
          showMessage(
            isApprove ? "Success" : "Error",
            bankName,
            undefined,
            `Bank Account ${isApprove ? "Approved" : "Declined"}`,
          );
        },
      });
    },
    [bankName, selectedRowID, updateStatus],
  );
 
  const handleRequestUpdate = () => {
    if (selectedRowID) updateStatus(selectedRowID, "update_requested");
  };
 
  return {
    handleApprove: () => openApprovalModal("approved"),
    handleDecline: () => openApprovalModal("declined"),
    handleRequestUpdate,
  };
};
 
/* -------------------------------------------------------------------------- */
/*                   Main Hook: aggregated actions export                     */
/* -------------------------------------------------------------------------- */
 
const useStatusChangeBankAccount = (props: {
  merchantId?: number;
  selectedRowID?: number | null;
  isLinkedBASelected: boolean;
  bankName?: string;
  onCloseModal?: (data?: IMerchantBankAccount, id?: number) => void;
  refetch?: () => void;
}) => {
  const handleTransferInProgress = () => {
    showConfirmationModal({
      type: "warning",
      title: "Transfer in Progress",
      description:
        "This bank account cannot be deleted while a transfer is in progress.",
      onConfirm: () => NiceModal.hide(GIVE_CONFIRMATION_POP_UP),
      confirmText: "Close",
      hideCancel: true,
    });
  };
  const { handleDelete: rawDelete } = useBankAccountDeletion({
    ...props,
    handleTransferInProgress,
  });
  const { handleApprove, handleDecline, handleRequestUpdate } =
    useBankAccountApproval(props);
  const handleDelete = () => {
    if (!props.selectedRowID) return;
    else
      showConfirmationModal({
        type: "delete",
        title: "Delete Bank Account",
        description:
          "Are you sure that you want to delete this bank account? This action is permanent and cannot be undone.",
        onConfirm: rawDelete,
      });
  };
 
  return { handleApprove, handleDecline, handleDelete, handleRequestUpdate };
};
 
export default useStatusChangeBankAccount;