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 | 17x 4x 4x 17x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 17x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 1184x 4x 4x 4x 1184x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1184x | import NiceModal from "@ebay/nice-modal-react";
import { useAppSelector } from "@redux/hooks";
import { selectCart } from "@redux/slices/cart";
import { customInstance } from "@services/api";
import {
CHECKOUT_MODAL,
EXPIRED_PAYMENT_FORM_MODAL,
NOT_ABLE_PROCESS_PAYMENT_FORM_MODAL,
} from "modals/modal_names";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { useGetCart } from "./useGetCart";
import { useLocation, useParams } from "react-router-dom";
import { useMediaQuery, useTheme } from "@mui/material";
import { addCartItem, deleteCardItem } from "@services/api/checkout/cart";
import { QKEY_GET_CUSTOMER_FEES, QKEY_LIST_CART } from "@constants/queryKeys";
import { useGetProductFeePayment } from "@hooks/merchant-api/cart/useGetProductFeePayment";
import { useFormContext } from "react-hook-form";
import useCheckFormType from "@sections/PayBuilder/components/hooks/useCheckFormType";
import { useCartLoading } from "@sections/PayBuilder/Checkout/hooks/useCartLoading";
import { handleError, isStatusCode } from "@utils/errorHandling";
import { showMessage } from "@common/Toast";
const getRecurringInterval = (interval?: string) => {
Eif (!interval || ["One-Time", "one_time", "once"].includes(interval))
return "once";
if (interval === "Every Month") return "monthly";
return interval.toLocaleLowerCase();
};
type Props = {
enabled?: boolean;
};
const useProduct = ({ enabled = true }: Props) => {
const { id } = useParams();
const queryClient = useQueryClient();
/* We also need to access product id from checkout modal in case transaction is declined, so we can allow user to create another transaction,
but since in nice modal modals don't have access to useParams we need to retrieve product id from location pathname.
*/
const productId = id || location.pathname.slice(1);
/**
* CRITICAL FIX: Use the same query key as useGetPublicForm ["public-form-id", id]
* This allows React Query to deduplicate requests across different hooks.
* Multiple components can now share the same cached data!
*/
// Validate ID before any operations
const isValidId =
Boolean(Number(productId)) && !!productId && !isNaN(Number(productId));
// First, try to get data from the existing public-form-id query
const existingData = queryClient.getQueryData(["public-form-id", productId]);
/**
* AGGRESSIVE OPTIMIZATION: If data already exists in cache, don't enable the query at all!
* useGetPublicForm (top-level) should be the primary data fetcher.
* This hook should only trigger if no data exists yet.
*/
const shouldFetch = isValidId && enabled && !existingData;
return useQuery(
["public-form-id", productId], // Changed from ["product", productId] to match other hooks
async () => {
// Safety check: should never execute with invalid ID due to enabled check
if (!isValidId) {
throw new Error(`Invalid product ID: ${productId}`);
}
return await customInstance({
url: `products/${productId}`,
method: "GET",
});
},
{
refetchOnWindowFocus: false,
/**
* CRITICAL: staleTime prevents duplicate requests when multiple components
* mount simultaneously. React Query will deduplicate in-flight requests and
* reuse cached data within the staleTime window.
*/
staleTime: 1000 * 60 * 2, // Consider data fresh for 2 minutes
cacheTime: 1000 * 60 * 5, // Keep in cache for 5 minutes after becoming unused
// If we already have data from another query, use it immediately
initialData: existingData as any,
/**
* Only fetch if:
* 1. We have a valid ID
* 2. The hook is enabled
* 3. We DON'T have existing cached data (prevents duplicate calls!)
*/
enabled: shouldFetch,
// Don't retry on invalid IDs
retry: false,
},
);
};
type useAddToCartProps = {
destinationAccountMerchantName?: string;
disableFetchCart?: boolean;
newCartItems?: any[];
showModal?: boolean;
disableGetProduct?: boolean;
};
export const useAddToCart = ({
destinationAccountMerchantName,
disableFetchCart,
newCartItems,
showModal = true,
disableGetProduct,
}: useAddToCartProps) => {
const { isCustomerChoicePayer, passFees: configurationPassFees } =
useGetProductFeePayment();
const form = useFormContext();
const { watch } = form || {};
const customerCoversFees = form ? watch("customerCoversFees") : undefined;
const globalPassFees = isCustomerChoicePayer
? !customerCoversFees
: configurationPassFees;
const theme = useTheme();
const isDesktop = useMediaQuery(theme.breakpoints.up("sm"));
const queryClient = useQueryClient();
const {
mutateAsync: mutateDeleteCartItem,
isLoading: deleteCartItemLoading,
} = useMutation({
mutationFn: deleteCardItem,
});
const { cartItems } = useAppSelector(selectCart);
const { isLoading, setLoading } = useCartLoading();
const { isInvoice, isFundraiser } = useCheckFormType();
const {
data: cart,
isLoading: isFetchingCart,
refetch: refetchCart,
} = useGetCart(disableFetchCart);
const {
data: product,
isLoading: isFetchingProduct,
refetch: refetchProduct,
} = useProduct({ enabled: !deleteCartItemLoading && !disableGetProduct });
const { pathname } = useLocation();
const removeOldCartItems = async () => {
// Check both the hook data and the current cache to avoid deleting if already cleared
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cachedCart: any = queryClient.getQueryData(QKEY_LIST_CART);
const items = cachedCart?.items || cart?.items;
Eif (!items || items.length === 0) return;
await mutateDeleteCartItem(undefined);
};
const addToCartHandler = async (
onSuccess?: () => void,
items?: any[],
passFees: boolean = globalPassFees,
hideMerchCanProcessMoneyModal = false,
skipCleanup = false,
transactionProcessingState = "",
) => {
try {
setLoading(true);
Iif (!product?.id) return;
Iif (!product?.merchCanProcessMoney && !hideMerchCanProcessMoneyModal) {
NiceModal.show(NOT_ABLE_PROCESS_PAYMENT_FORM_MODAL);
setLoading(false);
return true;
}
Iif (
(pathname.includes("events") || pathname.includes("sweepstakes")) &&
product?.endsAt &&
new Date(product?.endsAt * 1000) < new Date()
) {
NiceModal.show(EXPIRED_PAYMENT_FORM_MODAL);
setLoading(false);
return true;
}
// FIXED: Better error handling for removing old cart items
Eif (!skipCleanup) {
try {
await removeOldCartItems();
} catch (err) {
// Ignore 404 errors as the cart might have been already cleared by the backend
if (isStatusCode(err, 404)) {
// Silent ignore
} else {
// Log warning but don't block - this is a cleanup operation
console.warn("Failed to remove old cart items:", err);
}
// Continue with adding new items
}
}
// TODO: to be refactored and tested on all forms on a different PR
const itemsOptions = items || newCartItems || cartItems;
const failedIds: string[] = [];
/*
Without this variable, we would have to call refetch() or invalidateQueries() to see the new items. That would trigger another HTTP GET request to /cart. Since the addCartItem API already gave us the latest data, making another request is wasteful
If we didn't update the cache, the UI might briefly show the old cart state until a background refetch completes. By setting the data manually, the UI updates instantly to show the new items.
In summary:
It takes the data we just got from the server and instantly injects it into the React Query, ensuring the user sees their items immediately without waiting for a refresh.
*/
let lastSuccessfulCart = null;
// Execute sequentially to avoid backend race conditions
for (const item of itemsOptions) {
const customData = {
...item,
price: Math.round((item.amount || item.price) * 100),
recurringFrequency: item.recurringFrequency || 0,
recurringInterval: getRecurringInterval(item.recurringInterval),
recurringMax: item.recurringMax || null,
...(newCartItems?.length && {
productVariantID: item.productVariantID || item.variantID,
recurringInterval: item.recurringIntervalName,
}),
passFees: isCustomerChoicePayer ? passFees : configurationPassFees,
...(item.seats?.length && { seats: item.seats }), // AC008
};
try {
const newCart = await addCartItem(customData);
Iif (newCart) {
lastSuccessfulCart = newCart;
}
onSuccess?.();
} catch (err) {
failedIds.push(item.id);
}
}
Iif (lastSuccessfulCart && lastSuccessfulCart.items) {
const transformedCart = {
...lastSuccessfulCart,
items:
lastSuccessfulCart.items?.map((i: any) => ({
...i,
productVariantPrice: (i.productVariantPrice ?? 0) / 100,
unitPrice: (i.unitPrice ?? 0) / 100,
})) ?? [],
};
try {
queryClient.setQueryData(QKEY_LIST_CART, transformedCart);
} catch (err) {
// Fall back to refetching if failed to update cache
queryClient.invalidateQueries(QKEY_LIST_CART);
}
}
// FIXED: Handle failures appropriately
Iif (failedIds.length > 0) {
if (failedIds.length === itemsOptions.length) {
// All items failed - show error and return 'error' to prevent checkout
setLoading(false);
showMessage(
"Error",
"Unable to add items to cart. Please try again.",
isDesktop,
);
return "error"; // Return string to indicate failure (not out-of-stock array)
} else {
// Some items failed - show warning but continue to cart modal
if (transactionProcessingState !== "declined")
showMessage(
"Warning",
`${failedIds.length} of ${itemsOptions.length} items could not be added to cart.`,
isDesktop,
);
// Don't return here - allow cart modal to show for successful items
}
}
// Only show cart modal if at least some items were added successfully
const hasSuccessfulItems = failedIds.length < itemsOptions.length;
// Only invalidate queries if we have successful items
Eif (hasSuccessfulItems && newCartItems?.length) {
// Invalidate fees query as it depends on cart state
await queryClient.invalidateQueries(QKEY_GET_CUSTOMER_FEES);
// No need to invalidate cart list as we already updated it with setQueryData
}
Iif (isDesktop && showModal && hasSuccessfulItems) {
NiceModal.show(CHECKOUT_MODAL, {
destinationAccountMerchantName,
});
}
setLoading(false);
} catch (error) {
// FIXED: Proper error handling with user notification
setLoading(false);
handleError(error, {
context: "addToCartHandler",
customMessage: "Unable to process cart. Please try again.",
isDesktopView: isDesktop,
});
}
};
return {
addToCartHandler,
refetchProduct,
refetchCart,
isLoading: isLoading || isFetchingCart || isFetchingProduct || !product?.id,
isDesktop,
product,
isFetchingCart,
removeOldCartItems,
isCustomerChoicePayer,
configurationPassFees,
orderID: cart?.items?.[0]?.orderID,
};
};
|