All files / src/sections/PayBuilder/Checkout/hooks useCheckoutHandler.ts

68.68% Statements 125/182
57.98% Branches 69/119
58.82% Functions 10/17
68.71% Lines 123/179

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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570                                                                                                                                          13x                               397x 397x 397x         397x     397x         397x 397x 397x 397x 397x 397x         397x 397x   397x 4x 4x     397x 1x 1x 1x 1x       1x             397x 7x       7x 7x 1x         6x 6x     4x 1x           3x   3x               2x 2x 2x   397x             397x 15x                 15x 15x         15x       15x 15x 15x 15x 15x   15x           15x                     15x   15x 15x     15x 15x       15x             15x 15x             15x                                                                         15x 15x   15x     15x                     15x                     15x 15x                             15x           15x                         15x 15x 14x     15x       15x   15x   15x                                         15x 15x 15x 15x     15x   15x               15x     15x                                             15x 12x 12x     1x         1x   11x 11x 11x           11x     3x           2x 2x 1x         1x   1x                         1x 1x                                 15x 15x 15x 15x     15x     15x     15x       15x 2x 2x           13x 12x 12x         1x         1x                                         1x 1x     1x 1x 1x 1x               397x   397x        
import { useRef } from "react";
import { AxiosError } from "axios";
import NiceModal from "@ebay/nice-modal-react";
import { useNavigate, useParams } from "react-router-dom";
import { useQueryClient } from "react-query";
import { QKEY_LIST_CART } from "@constants/queryKeys";
import { EMAIL_VERIFICATION_PATH } from "@routes/paths";
import { ErrorCodeEnum } from "@services/api/api.constant";
import {
  parseError,
  isStatusCode,
  isDisposableEmailError,
  isEmailVerificationRequiredError,
  isPurchaseVerificationRequiredError,
  isRejectedVerificationCodeError,
  needsNewVerificationCode,
  isCaptchaChallengeRequiredError,
} from "@utils/errorHandling";
import { VALIDATION_MESSAGES } from "@validation/messages";
import {
  CHECKOUT_ERROR_MESSAGES,
  VERIFY_PURCHASE,
} from "@sections/PayBuilder/constants";
import { useResendEmail } from "@pages/EmailVerification/api/useResendEmail";
import { useSubmitPurchaseVerification } from "./useSubmitPurchaseVerification";
import { buildCheckoutUserName } from "@sections/PayBuilder/utils";
import { showMessage } from "@common/Toast";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import useCheckFormType from "@sections/PayBuilder/components/hooks/useCheckFormType";
import {
  invokeSafely,
  formatAddress,
  validateBillingAddress,
} from "../helpers";
import {
  NOT_ABLE_PROCESS_PAYMENT_FORM_MODAL,
  VERIFY_PURCHASE_MODAL,
} from "modals/modal_names";
import { usePaymentCaptchaChallenge } from "./usePaymentCaptchaChallenge";
import { convertPhoneNumber } from "@utils/date.helpers";
import { FieldPath } from "react-hook-form";
import { ICheckoutInputs, CheckoutRequest } from "../types";
import { usePayBuilderForm } from "@sections/PayBuilder/provider/PayBuilderFormProvider";
import { buildCustomFieldsPayload } from "../customFields.helpers";
import {
  buildParticipantsPayload,
  isSameAsContactActive,
  resolveParticipantSlots,
} from "../participants.helpers";
import { useEventParticipantDetails } from "./useEventParticipantDetails";
 
type UseCheckoutHandlerParams = {
  handleCardNumberCheck: any;
  addToCartHandler: any;
  cartCheckoutMutation: any;
  handleSuccess: any;
  product: any;
  orderID: string;
  isCustomerChoicePayer: boolean;
  configurationPassFees: boolean;
  cartItems: any[];
  payBuilderData: any;
  isDeliveryEnabled: boolean;
  setLoading: (v: boolean) => void;
  setFieldError?: (key: FieldPath<ICheckoutInputs>, message?: string) => void;
  onPaymentFailed?: () => void;
};
 
export const useCheckoutHandler = ({
  handleCardNumberCheck,
  addToCartHandler,
  cartCheckoutMutation,
  handleSuccess,
  setLoading,
  setFieldError,
  onPaymentFailed,
  product,
  orderID,
  isCustomerChoicePayer,
  configurationPassFees,
  cartItems,
  payBuilderData,
  isDeliveryEnabled,
}: UseCheckoutHandlerParams) => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { isDesktopView } = useCustomThemeV2();
  // Same endpoint the address-verification page uses; with purchase
  // verification on it mails a code instead of a link.
  // The modal shows a failed resend inline, so a global toast telling the buyer
  // to start over would contradict a modal that is still usable.
  const { sendEmailAsync: sendVerificationEmail } = useResendEmail({
    reportErrors: false,
  });
  const { submitCode } = useSubmitPurchaseVerification();
  const {
    isPayBuilderCustomFieldsEnabled,
    isPaymentRecaptchaEnabled,
    isFeatureFlagLoading,
  } = useGetFeatureFlagValues();
  const { isFundraiser, isSweepstake, isInvoice } = useCheckFormType();
  const isParticipantDetailsEnabled = useEventParticipantDetails();
  const { methods: builderMethods } = usePayBuilderForm();
  const formId = useParams<{ id: string }>();
  const handleCheckoutRef = useRef<(data: ICheckoutInputs) => Promise<void>>(
    async () => undefined,
  );
  // Defined here, not inside handleCheckout: a callback defined there closes
  // over that call's scope and retains the card through it.
  const pendingCheckoutRef = useRef<ICheckoutInputs | null>(null);
  const pendingOrderIDRef = useRef<number | null>(null);
 
  const clearPendingVerification = () => {
    pendingCheckoutRef.current = null;
    pendingOrderIDRef.current = null;
  };
 
  const resendVerificationCode = async () => {
    const orderID = pendingOrderIDRef.current;
    Iif (!orderID) return VERIFY_PURCHASE.RESEND_FAILED;
    try {
      await sendVerificationEmail({ orderID });
      return null;
    } catch (resendError: unknown) {
      // The API names the refusal; fixed copy misdescribes most of them.
      return (
        (resendError as AxiosError<{ message?: string }>)?.response?.data
          ?.message || VERIFY_PURCHASE.RESEND_FAILED
      );
    }
  };
 
  const verifyPurchaseCode = async (code: string) => {
    const orderID = pendingOrderIDRef.current;
    // Before the await: a dismissal mid-submit would otherwise spend the code
    // and then find nothing to retry, reporting success for a checkout never
    // posted.
    const pending = pendingCheckoutRef.current;
    if (!orderID || !pending) {
      return {
        message: CHECKOUT_ERROR_MESSAGES.GENERIC_ERROR,
        needsNewCode: false,
      };
    }
    try {
      await submitCode({ orderID, code });
    } catch (submitError: unknown) {
      // Only a refusal's message describes the code.
      if (!isRejectedVerificationCodeError(submitError)) {
        return {
          message: CHECKOUT_ERROR_MESSAGES.GENERIC_ERROR,
          needsNewCode: false,
        };
      }
      // parseError falls back to axios's own status string, so read the body.
      const apiMessage = (submitError as AxiosError<{ message?: string }>)
        ?.response?.data?.message;
      return {
        message: apiMessage || VERIFY_PURCHASE.GENERIC_INVALID_CODE,
        needsNewCode: needsNewVerificationCode(submitError),
      };
    }
 
    // The retry needs the cart re-read, a fresh captcha token and the success
    // handling.
    clearPendingVerification();
    void handleCheckoutRef.current(pending);
    return null;
  };
  const paymentCaptcha = usePaymentCaptchaChallenge<ICheckoutInputs>({
    onRetry: (pending) => {
      void handleCheckoutRef.current(pending);
    },
    onGiveUp: () => setLoading(false),
  });
 
  const handleCheckout = async (data: ICheckoutInputs) => {
    Iif (isFeatureFlagLoading) {
      return;
    }
    // SECURITY: Extract card data immediately, then wipe from source
    let cardNumber: string | undefined;
    let cvv: string | undefined;
    let expirationDate: string | undefined;
    let nameOnCard: string | undefined;
 
    try {
      Iif (product && !product.merchCanProcessMoney) {
        NiceModal.show(NOT_ABLE_PROCESS_PAYMENT_FORM_MODAL);
 
        return;
      }
      setLoading(true);
 
      // SECURITY: Extract card data to local variables
      const { payment, email, phoneNumber, deliveryAddress, billingAddress } =
        data;
      cardNumber = payment?.cardNumber;
      cvv = payment?.cvv;
      expirationDate = payment?.expirationDate;
      nameOnCard = payment?.nameOnCard;
 
      const cardObject = await handleCardNumberCheck(
        cardNumber || "",
        (message = "Please enter a valid card number") =>
          setFieldError?.("payment.cardNumber", message),
      );
 
      Iif (cardObject === undefined) {
        setLoading(false);
        // SECURITY: Clear card data from memory on validation failure
        cardNumber = undefined;
        cvv = undefined;
        expirationDate = undefined;
        nameOnCard = undefined;
        return;
      }
      // Contact Name (events) takes precedence over the `Name on Card` split;
      // both are sent and the BE resolves them. See buildCheckoutUserName.
      const userName = buildCheckoutUserName(data?.name, nameOnCard);
 
      const [expMonth, expYearShort] = expirationDate?.split("/") || [];
      const delivAddress = isDeliveryEnabled
        ? formatAddress(deliveryAddress)
        : null;
      const { useDeliveryAddress, ...billingAddressFields } = billingAddress;
      const billAddress = useDeliveryAddress
        ? delivAddress
        : formatAddress(billingAddressFields);
 
      const passFees = isCustomerChoicePayer
        ? !data.customerCoversFees
        : configurationPassFees;
 
      // Same cache addToCartHandler writes (QKEY_LIST_CART string key). CartContext
      // `id` is the variant id for events, which persist_participants rejects.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const updatedCartData: any = queryClient.getQueryData(QKEY_LIST_CART);
      const serverCartItems = Array.isArray(updatedCartData?.items)
        ? updatedCartData.items
        : [];
 
      // SECURITY: Build payment data object that will be sent to API
      // This minimizes the time card data exists in memory
      // CRITICAL: Never log, console.log, or store this object - contains PCI data
      const customData: CheckoutRequest = {
        user: {
          ...userName,
          email: email,
          ...(phoneNumber && {
            phoneNumber: convertPhoneNumber(phoneNumber),
          }),
          ...(!isFundraiser && {
            shippingAddress: delivAddress,
          }),
          ...(validateBillingAddress(billAddress) && {
            billingAddress: billAddress,
          }),
        },
        ...(isInvoice && {
          user: payBuilderData?.customer || {},
        }),
        paymentMethodParams: {
          paymentMethodID: null,
          paymentMethod: {
            card: {
              ...(validateBillingAddress(billAddress) && {
                address: billAddress,
              }),
              cvv: cvv,
              cardholderName: nameOnCard,
              number: cardNumber?.replaceAll(" ", ""),
              expiryMonth: parseInt(expMonth),
              expiryYear: 2000 + parseInt(expYearShort),
              isDebit: cardObject?.binInfo?.cardType === "DEBIT",
            },
            isDefault: false,
          },
        },
        ...(!isFundraiser &&
          !isSweepstake && {
          items: cartItems.reduce((acc, curr) => {
            Eif (!isNaN(Number(curr.id))) {
              acc.push(parseInt(curr.id));
            }
            Iif (!isNaN(Number(curr.signupID))) {
              acc.push(parseInt(curr.signupID));
            }
            return acc;
          }, [] as Array<number>),
        }),
        ...(isFundraiser && {
          isCustomerAnonymous: data.Donations!.isAnonymous,
        }),
        ...(isSweepstake && {
          isCustomerAnonymous: data.Entries!.isAnonymous,
        }),
        // PAY-Builder016 — snapshot the custom-field answers onto the txn (AC023).
        ...(() => {
          Eif (!isPayBuilderCustomFieldsEnabled) return {};
          const customFields = buildCustomFieldsPayload(
            builderMethods.getValues().Checkout?.customFields,
            data.customFields,
          );
          return customFields.length ? { customFields } : {};
        })(),
        // Story 2 — per-ticket participants (AC015/AC055). Omitted whenever the
        // buyer is the participant or the feature is off, so every checkout that
        // does not collect participant details sends today's payload unchanged.
        ...(() => {
          const checkoutConfig = builderMethods.getValues().Checkout;
          const participants = buildParticipantsPayload({
            slots: resolveParticipantSlots({
              cartItems,
              serverItems: serverCartItems,
            }),
            values: data.participants ?? {},
            isEnabled: isParticipantDetailsEnabled,
            collectPerTicket: !!checkoutConfig?.participantDetails?.render,
            sameAsContact: isSameAsContactActive({
              sameAsContact: data.participantsSameAsContact,
              contactName: data.name,
              contactEmail: data.email,
            }),
            includePhone: !!checkoutConfig?.participantPhone?.render,
          });
          return participants.length ? { participants } : {};
        })(),
        sourceTypeName: "givesync_ui",
        passFees,
      };
 
      Iif (isPaymentRecaptchaEnabled) {
        paymentCaptcha.resetAttemptsUnlessRetry();
        if (paymentCaptcha.reopenIfRequired(data)) {
          setLoading(false);
          return;
        }
        await paymentCaptcha.attachToken(customData);
      }
      /**
       * if the card is declined, we need to recreate the cart, otherwise BE will return error "The requested order was not found"
       */
 
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const apiIDS = serverCartItems.map((x: any) => x.id);
      if (apiIDS?.length && !isFundraiser && !isSweepstake) {
        customData.items = apiIDS;
      }
 
      Iif ((isFundraiser || isSweepstake) && (!apiIDS || apiIDS.length === 0)) {
        await addToCartHandler(undefined, undefined, passFees);
      }
 
      paymentCaptcha.consumeToken();
 
      let holdPendingForChallenge = false;
 
      await cartCheckoutMutation.mutateAsync(customData, {
        onSuccess: (res: any) => {
          // SECURITY: wipe sensitive card data from memory immediately after API call
          cardNumber = undefined;
          cvv = undefined;
          expirationDate = undefined;
          nameOnCard = undefined;
          paymentCaptcha.reset();
 
          return handleSuccess(
            res,
            data,
            billingAddress,
            deliveryAddress,
            phoneNumber,
            passFees,
            handleCheckout,
          );
        },
        onError: (error: any) => {
          // SECURITY: wipe sensitive card data on error
          cardNumber = undefined;
          cvv = undefined;
          expirationDate = undefined;
          nameOnCard = undefined;
 
          // FIXED: Use centralized error checking
          const parsed = parseError(error);
 
          Iif (isCaptchaChallengeRequiredError(error)) {
            const captchaHandle = paymentCaptcha.requestChallenge(data);
            if (captchaHandle === "shown") {
              holdPendingForChallenge = true;
              setLoading(false);
            }
            return;
          }
          paymentCaptcha.clearPending();
 
          // Check for email validation errors - don't show snackbar
          Iif (
            isStatusCode(error, ErrorCodeEnum.BAD_INPUT) &&
            isDisposableEmailError(parsed.message)
          ) {
            setFieldError?.(
              "email",
              parsed.message || VALIDATION_MESSAGES.INVALID_DISPOSABLE_EMAIL,
            );
            setLoading(false);
            return;
          }
 
          // Email verification flow — keyed on the API's
          // "email_verification_required" code, not the HTTP status: declines
          // (e.g. amount below minimum) are also 400 and must fall through to
          // the failed-payment handling in the catch block instead.
          //
          // Handled before the cart is cleared: the API rejects the checkout
          // without taking payment, so the buyer comes back to finish it and
          // needs the cart they started with.
          // Purchase verification is confirmed with a code in the checkout
          // itself — the address-verification page below would send the buyer
          // to click a link its email does not carry.
          if (isPurchaseVerificationRequiredError(error)) {
            const codeOrderID = parseInt(orderID);
            if (!codeOrderID) {
              // The code is already in the buyer's inbox but there is no order
              // to submit it against.
              showMessage(
                "Error",
                CHECKOUT_ERROR_MESSAGES.VERIFICATION_LOST_ORDER,
                isDesktopView,
              );
              return;
            }
            pendingCheckoutRef.current = data;
            pendingOrderIDRef.current = codeOrderID;
            NiceModal.show(VERIFY_PURCHASE_MODAL, {
              email,
              onVerify: verifyPurchaseCode,
              onResend: resendVerificationCode,
              onDismiss: clearPendingVerification,
            });
            return;
          }
 
          if (isEmailVerificationRequiredError(error)) {
            // The verification page needs both: :id to send the buyer back to
            // the form, and the order id for the resend endpoint, which rejects
            // anything not > 0. orderID comes from the cart, so it is absent
            // once a previous decline cleared it — without this the page was
            // reached with orderID=NaN and resend failed silently.
            const verifiedOrderID = parseInt(orderID);
            if (!formId.id || !verifiedOrderID) {
              showMessage(
                "Error",
                CHECKOUT_ERROR_MESSAGES.GENERIC_ERROR,
                isDesktopView,
              );
              return;
            }
            return navigate(
              `${EMAIL_VERIFICATION_PATH}?orderID=${verifiedOrderID}` +
              `&email=${encodeURIComponent(email)}`,
              {
                state: {
                  productID: parseInt(formId.id),
                  paymentMethodID: cardObject.id,
                },
              },
            );
          }
 
          // Optimistically clear cart cache as backend clears it on failure
          Eif (!parsed.fieldErrors) {
            queryClient.setQueryData(QKEY_LIST_CART, { items: [] });
          }
        },
        onSettled: () => {
          // SECURITY: Final cleanup - ensure card data is wiped
          cardNumber = undefined;
          cvv = undefined;
          expirationDate = undefined;
          nameOnCard = undefined;
          if (!holdPendingForChallenge) {
            paymentCaptcha.clearPending();
          }
          setLoading(false);
        },
      });
    } catch (error: unknown) {
      // SECURITY: wipe sensitive card data on exception
      cardNumber = undefined;
      cvv = undefined;
      expirationDate = undefined;
      nameOnCard = undefined;
 
      // FIXED: Use centralized error parsing
      const parsed = parseError(error);
 
      // mutateAsync still rejects after onError showed the challenge modal.
      Iif (isCaptchaChallengeRequiredError(error)) {
        return;
      }
      paymentCaptcha.clearPending();
 
      // onError above already navigated away, or reported the missing route id
      // itself — either way it is not a failed payment.
      if (isEmailVerificationRequiredError(error)) {
        setLoading(false);
        return;
      }
 
      // Same for the purchase gate, which opened the confirm modal above. No
      // money moved, and the buyer finishes from that modal — so the cart
      // clear and the failed-payment toast below must not run behind it.
      if (isPurchaseVerificationRequiredError(error)) {
        setLoading(false);
        return;
      }
 
      // Don't show snackbar for email validation errors - they're already shown inline
      // Check both message field and fieldErrors
      Iif (isDisposableEmailError(parsed.message)) {
        setLoading(false);
        return;
      }
 
      Iif (parsed.fieldErrors) {
        const fieldErrorEntries = Object.entries(parsed.fieldErrors);
        const [firstParam] = fieldErrorEntries[0];
        const emailParamNames = [
          "email",
          "emailAddress",
          "Email",
          "EmailAddress",
        ];
        const isEmailError = emailParamNames.some(
          (param) => firstParam?.toLowerCase() === param.toLowerCase(),
        );
 
        if (isEmailError) {
          setLoading(false);
          return;
        }
      }
 
      // Optimistically clear cart cache as backend clears it on failure
      // Only clear cart and show payment failed for non-field-validation errors
      if (!parsed.fieldErrors) {
        queryClient.setQueryData(QKEY_LIST_CART, { items: [] });
 
        const snackBarMessage =
          parsed.userMessage || CHECKOUT_ERROR_MESSAGES.GENERIC_ERROR;
        showMessage("Error", snackBarMessage, isDesktopView);
        setLoading(false);
        invokeSafely(onPaymentFailed, "onPaymentFailed", isDesktopView);
      } else E{
        // Field validation errors - don't show payment failed
        setLoading(false);
      }
    }
  };
 
  handleCheckoutRef.current = handleCheckout;
 
  return {
    handleCheckout,
  };
};