All files / src/sections/PayBuilder/Checkout/hooks useHandleCheckoutError.tsx

45.23% Statements 19/42
42.85% Branches 12/28
40% Functions 2/5
45.23% Lines 19/42

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                                                            14x   390x   390x           6x 6x             6x 1x         5x 1x     4x 2x 2x     2x       2x                       2x                                 2x                                                                                                     2x 2x     390x    
import { AxiosError } from "axios";
import { showMessage } from "@common/Toast";
import { FieldPath } from "react-hook-form";
import { ICheckoutInputs } from "../types";
import {
  parseError,
  isDisposableEmailError,
  isEmailVerificationRequiredError,
  isPurchaseVerificationRequiredError,
  isCaptchaChallengeRequiredError,
} from "@utils/errorHandling";
import { VALIDATION_MESSAGES } from "@validation/messages";
import {
  getErrorParamName,
  zipCodeToFormKeyMap,
} from "@hooks/merchant-api/cart/useCheckout";
import { ErrorCodeEnum } from "@services/api/api.constant";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { CHECKOUT_ERROR_MESSAGES } from "@sections/PayBuilder/constants";
 
type HandleCheckoutErrorParams = {
  error: unknown | AxiosError;
  setFieldError?: (key: FieldPath<ICheckoutInputs>, message?: string) => void;
  setLoading?: (loading: boolean) => void;
};
 
/**
 * Hook for handling checkout errors with automatic context derivation
 * @returns handleError function that only requires error and setFieldError
 */
export const useHandleCheckoutError = () => {
  // Derive all dependencies from hooks
  const { isDesktopView } = useCustomThemeV2();
 
  const handleError = ({
    error,
    setFieldError,
    setLoading,
  }: HandleCheckoutErrorParams) => {
    // FIXED: Use centralized error parsing for consistent error handling
    const parsed = parseError(error);
    const statusCode = (parsed as any).statusCode;
 
    // Early return for email verification flow — matched by the API error
    // code (with a message fallback), not the bare HTTP status: declines
    // (e.g. amount below minimum) are also 400 and must be handled as a
    // failed payment below. The acquirer's security configuration decides
    // whether the gate applies, server-side, so the client never re-checks it.
    if (isEmailVerificationRequiredError(error)) {
      return;
    }
 
    // The purchase gate opens the confirm modal, which states the hold itself.
    // Falling through would put the generic failed-payment toast on top of it.
    if (isPurchaseVerificationRequiredError(error)) {
      return;
    }
 
    if (isCaptchaChallengeRequiredError(error)) {
      setLoading?.(false);
      return;
    }
 
    setLoading?.(false);
 
    // Check for invalid email (disposable or unreachable)
    // Don't show snackbar - error is displayed inline on the field
    Iif (
      statusCode === ErrorCodeEnum.BAD_INPUT &&
      isDisposableEmailError(parsed.message)
    ) {
      setFieldError?.(
        "email",
        parsed.message || VALIDATION_MESSAGES.INVALID_DISPOSABLE_EMAIL,
      );
      return;
    }
 
    // Check for redirect error
    Iif (
      statusCode === ErrorCodeEnum.BAD_INPUT &&
      parsed.message?.toLowerCase() ===
        CHECKOUT_ERROR_MESSAGES.REDIRECT_ERROR.toLowerCase()
    ) {
      showMessage(
        "Error",
        CHECKOUT_ERROR_MESSAGES.REDIRECT_ERROR,
        isDesktopView,
        undefined,
        false,
      );
      window.location.reload();
      return;
    }
 
    // Handle field-specific validation errors
    Iif (parsed.fieldErrors) {
      const fieldErrorEntries = Object.entries(parsed.fieldErrors);
      const [firstParam, firstMessage] = fieldErrorEntries[0];
 
      // Check for email errors (disposable or unreachable)
      // Don't show snackbar for email errors as they already display inline
      const emailParamNames = [
        "email",
        "emailAddress",
        "Email",
        "EmailAddress",
      ];
      const isEmailError = emailParamNames.some(
        (param) => firstParam?.toLowerCase() === param.toLowerCase(),
      );
 
      if (isEmailError) {
        const emailErrorMessage =
          firstMessage || VALIDATION_MESSAGES.PROVIDE_VALID_EMAIL;
 
        setFieldError?.("email", emailErrorMessage);
        return;
      }
 
      // Check for zip code errors
      const invalidZipCodeKeys = fieldErrorEntries
        .map(([param]) => zipCodeToFormKeyMap?.[param])
        .filter(Boolean);
 
      if (invalidZipCodeKeys.length > 0) {
        invalidZipCodeKeys.forEach((field) => {
          setFieldError?.(
            field as FieldPath<ICheckoutInputs>,
            VALIDATION_MESSAGES.INVALID_ZIP_CODE,
          );
        });
 
        // Don't show snackbar for zip code errors - they're displayed inline
        return;
      }
 
      // Show first field error to user via snackbar
      const errorMessage =
        firstMessage || `${getErrorParamName(firstParam)} is not valid`;
 
      showMessage("Error", errorMessage, isDesktopView);
      return;
    }
 
    // 5. Generic fallback
    const snackBarMessage =
      parsed.userMessage || CHECKOUT_ERROR_MESSAGES.GENERIC_ERROR;
    showMessage("Error", snackBarMessage, isDesktopView);
  };
 
  return { handleError };
};