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 | 483x 483x 2867x 2867x 2867x 2867x 2867x 2867x 1x 2867x 2867x 14x 14x 14x 12x 2x 14x 14x 2867x 2867x 2867x 1x 1x 1x 1x 2867x 402x 2867x 2717x 19x 19x 19x 2867x 2867x 30x 2867x 483x 7066x 7066x 7066x 747x 747x 747x 747x 743x 65x 117x 65x 30x 18x 20x 65x 18x 747x 126x 747x 747x 126x 18x 18x 483x 38x 19x | import { showMessage } from "@common/Toast";
import { parseAmount } from "@utils/index";
import { cloneDeep, isEqual } from "lodash";
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
createContext,
} from "react";
import { useCartItems } from "../components/hooks/useCartMutations";
import useCheckFormType from "../components/hooks/useCheckFormType";
import { withoutSeatlessSeatedItems } from "../seating.helpers";
import type { SeatSelection } from "../types";
export interface ICartItem {
signupID?: any;
id: string;
productVariantName: string;
productType?: string;
productVariantID: string | number;
productVariantPrice: number;
quantity: number;
unitPrice: number | string;
productVariantImageURL: string;
recurringIntervalName: string | any;
in_stock?: number | null;
description?: string;
signupFee?: string | null;
seats?: SeatSelection[]; // AC008: chosen seats for assigned-seating event tickets
}
export interface CartContextProps {
cartItems: ICartItem[];
clearCart: () => void;
addToCart: (
item: ICartItem,
addedQuantity?: number,
quantityChangeType?: string,
replace?: boolean,
) => void;
addItemsToCart: (item: { [id: number | string]: ICartItem }) => void;
removeFromCart: (ProductItemTypeId: string) => void;
updateItemInCart: (item: ICartItem, quantity: number) => void;
getItemInCart: (productId: string) => ICartItem | undefined;
isCartEmpty: boolean;
subTotal?: string;
rawSubtotal?: number;
totalAmount?: number | string;
totalItemsInCart: number;
fees: number | null;
setFees: (data: number) => void;
displayFees: boolean;
setDisplayFees: (value: boolean) => void;
outOfStockItemIds: (string | number)[];
setOutOfStockItemIds: (data: (string | number)[]) => void;
setCartItems: any;
cartModalProps: {
open?: boolean;
onClose: () => void;
};
setCartModalProps: React.Dispatch<
React.SetStateAction<{
open: boolean;
onClose: () => void;
}>
>;
}
interface CartProviderProps {
children: React.ReactNode;
}
export const CartContext = createContext<CartContextProps | undefined>(
undefined,
);
export const CartProvider: React.FC<CartProviderProps> = ({ children }) => {
const [cartItems, setCartItems] = useState<{ [id: string]: ICartItem }>({});
const [outOfStockItemIds, setOutOfStockItemIds] = useState<
(string | number)[]
>([]);
const [fees, setFees] = useState<null | number>(null);
const [displayFees, setDisplayFees] = useState<boolean>(false);
const [cartModalProps, setCartModalProps] = useState({
open: false,
onClose: () => {
return;
},
});
const clearCart = () => {
setCartItems({});
};
const { isFundraiser } = useCheckFormType();
const addToCart = async (
item: any,
addedQuantity = 1,
quantityChangeType = "increment",
replace?: boolean,
) => {
const existingItem =
!isFundraiser && cloneDeep(cartItems[item.productVariantID]);
let newQuantity = 0;
if (replace || !existingItem) {
newQuantity = addedQuantity;
} else {
newQuantity =
quantityChangeType === "increment"
? existingItem.quantity + addedQuantity
: existingItem.quantity - addedQuantity;
}
if (!item.in_stock || newQuantity <= item.in_stock) {
setCartItems((prevState) => ({
...prevState,
[item.productVariantID]: existingItem
? {
...existingItem,
quantity: newQuantity,
// PAY Builder 031 (H2) — re-adding a seated ticket via the modal must
// apply the newly-chosen seats. Only sync when the incoming item
// carries `seats` so non-seated products are unaffected.
...("seats" in item ? { seats: item.seats } : {}),
}
: {
...item,
quantity: newQuantity,
},
}));
} else E{
// FIXED: More descriptive error message showing available stock
showMessage(
"Error",
`Cannot add more than ${item.in_stock} ${
item.in_stock === 1 ? "item" : "items"
}. Only ${item.in_stock} available in stock.`,
);
}
};
const updateItemInCart = (newItem: ICartItem, quantity: number) => {
setCartItems((prevState) => ({
...prevState,
[newItem.id]: { ...newItem, quantity },
}));
};
const addItemsToCart = (items: { [id: number | string]: ICartItem }) => {
setCartItems(items);
};
const removeFromCart = (productId: string) => {
setCartItems((prevState) => {
const { [productId]: _, ...rest } = prevState;
return rest;
});
Iif (outOfStockItemIds.length && outOfStockItemIds.includes(productId)) {
setOutOfStockItemIds((prev) => prev.filter((item) => item !== productId));
}
};
const getItemInCart = useCallback(
(productId: string) => cartItems[productId],
[cartItems],
);
const subTotal = useMemo(() => {
return Object.values(cartItems).reduce((total, item) => {
const productPrice = sanitizeNumber(item.productVariantPrice);
const signupFee = sanitizeNumber(item.signupFee || "0");
return total + productPrice * item.quantity + signupFee;
}, 0);
}, [cartItems]);
const totalAmount = parseAmount(subTotal + Number(displayFees ? fees : 0));
const totalItemsInCart = Object.values(cartItems).reduce(
(count, item) => count + item.quantity,
0,
);
return (
<CartContext.Provider
value={{
cartItems: Object.values(cartItems),
clearCart,
addToCart,
removeFromCart,
isCartEmpty: Object.values(cartItems).length === 0,
getItemInCart,
subTotal: parseAmount(subTotal),
rawSubtotal: subTotal, // we need unformatted subtotal to make calculations without needing to decode it
totalAmount,
totalItemsInCart,
fees,
setFees,
displayFees,
setDisplayFees,
outOfStockItemIds,
setOutOfStockItemIds,
setCartItems,
cartModalProps,
setCartModalProps,
addItemsToCart,
updateItemInCart,
}}
>
{children}
</CartContext.Provider>
);
};
export const useCart = () => {
const context = useContext(CartContext);
Iif (!context) {
throw new Error("use useCart within CartProvider wrapper");
}
return context;
};
export function useInitCartItems(
isEnabled: boolean,
variants: any,
// GB-21697 — on an assigned-seating event a server cart item hydrates without seats and
// is unusable; see withoutSeatlessSeatedItems.
assignSeating = false,
) {
const { setCartItems } = useCart();
const { isMembership } = useCheckFormType();
const { data: cartData } = useCartItems(isEnabled);
const serverItems = useMemo(() => {
// GB-21697 — isEnabled gates the WRITE path too, not just the fetch. react-query hands
// back CACHED data for a disabled query, so off a cart route cartData is still populated:
// useIsEnabled matches only /{id} and /{id}/checkout, and /{id}/checkout_success mounts its
// own PayBuilderFormProvider (so previousServerItemsRef starts null). Hydration therefore
// replaced the buyer's cart with the server's seatless view, which
// withoutSeatlessSeatedItems empties, and CheckoutCart's empty-cart guard navigated back to
// the form instead of showing the receipt. The caller also switches this off for invoices,
// whose cart is seeded by the invoice flow rather than GET /cart.
if (!isEnabled) return null;
Eif (cartData && variants?.length) {
const variantIDs = variants?.map((item: any) => item.id);
// Filter out cart items that don't belong to this product
const filtered = cartData.items
?.filter((item: any) => variantIDs.includes(item.productVariantID))
.map((x: any) => ({
...x,
in_stock: variants.find(
(variant: any) => variant.id === x.productVariantID,
)?.inventory,
}));
return !filtered
? {}
: isMembership
? filtered.reduce((acc: any, v: any) => {
const existingItem = acc[v.productVariantID];
if (existingItem && existingItem.isAutomaticallyAdded) {
return {
...acc,
[v.productVariantID]: {
...v,
signupFee: parseAmount(existingItem.unitPrice),
signupID: existingItem.id,
},
};
}
return { ...acc, [v.productVariantID]: v };
}, {})
: filtered.reduce(
(acc: any, v: any) => ({ ...acc, [v.productVariantID]: v }),
{},
);
}
return null;
}, [isEnabled, cartData, variants, isMembership]);
// GB-21697 — a seated ticket restored without seats blocks checkout invisibly and gets
// re-POSTed seatless, so it never enters the cart.
const hydratedItems = useMemo(
() => withoutSeatlessSeatedItems(assignSeating, serverItems),
[assignSeating, serverItems],
);
const previousServerItemsRef = useRef(null);
useEffect(() => {
if (
hydratedItems &&
!isEqual(hydratedItems, previousServerItemsRef.current)
) {
previousServerItemsRef.current = hydratedItems;
setCartItems(hydratedItems);
}
}, [hydratedItems, setCartItems]);
}
const sanitizeNumber = (value: string | number) => {
if (typeof value === "number") return value;
return parseFloat(value.replace(/,/g, ""));
};
|