All files / src/sections/PayBuilder/items PublicProductItemModal.tsx

95.58% Statements 65/68
62.06% Branches 72/116
88.23% Functions 15/17
95.45% Lines 63/66

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                                                                                                                                                      3x                                                             86x 86x 86x 86x 86x 86x 86x 86x         86x 86x 86x     86x     86x 86x 86x             86x       86x   86x 16x                         86x 16x       86x 31x     86x 86x 5x   5x 5x                                         5x       86x 3x 3x     86x 2x 2x               86x 24x 24x         24x 2x               86x 2x 2x     86x 5x   86x   86x   86x   86x       86x               86x   86x             86x   86x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       3x 115x 56x             3x           3x 3x                               3x           3x      
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import NiceModal from "@ebay/nice-modal-react";
import { Grid, rgbToHex, Stack } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import {
  Product,
  TFormStatus,
  TFormStatusEnum,
} from "../components/products/types";
import { styled, useAppTheme } from "@theme/v2/Provider";
import GiveText from "@shared/Text/GiveText";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { showMessage } from "@common/Toast";
import { LinkSimpleIcon } from "@phosphor-icons/react";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import QuantityInput from "../components/products/QuantityInput";
import { ICartItem } from "../provider/CartContext";
import SeatPicker from "./SeatPicker";
import { reconcileSeatQuantity } from "@sections/PayBuilder/seating.helpers";
import type {
  SeatSelection,
  SeatingRow,
  TakenSeat,
} from "@sections/PayBuilder/types";
import { addSizeToImage } from "@utils/image.helpers";
import PublicUrlShare from "../LaunchStep/PublicURLShare/PublicURLShare";
import { parsePriceToInteger } from "@utils/helpers";
import { parseDescription } from "@shared/HFInputs/HFRichInput/RichTextUtils";
import { useIsEnabled } from "../components/hooks/useHelpers";
import useCheckFormType from "../components/hooks/useCheckFormType";
import { parseAmount } from "@utils/index";
import { paymentTypeSuffixes } from "./AddProductItemModal";
import { FormType, getTextColorsBasedOnBackground } from "../utils";
import { darken } from "@mui/material";
import SubscribeButton from "../components/products/CardItem/SubscribeButton";
import { CURRENCY } from "@constants/constants";
import { isExceededAmount } from "../Checkout/helpers";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { CANNOT_EXCEED_MAX_AMOUNT } from "@constants/stringConstants";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
 
type Props = {
  product: Product;
  addToCart: (
    item: ICartItem,
    addedQuantity?: number,
    quantityChangeType?: string,
    replace?: boolean,
  ) => void;
  // GB-21697 — the seat picker is the only place a seated ticket can be un-chosen: its card
  // hides the +/- stepper and Add to cart can never commit an empty selection. Passed by the
  // event ticket card; the product/membership callers have no seat map, so it stays optional.
  removeFromCart?: (productId: string) => void;
  accentColor: string;
  backgroundColor: string;
  productQuantity: number;
  displayStatus: TFormStatus;
  // GB-21654 — this modal mounts at the App-root NiceModal.Provider, outside the
  // route match, so useCheckFormType can't resolve the public form's type in here.
  // Callers that know the form they render for pass it in; the hook is the fallback.
  formType?: FormType;
  subscribeBtnText?: string;
  isPreview?: boolean;
  secondaryColor?: string;
  showCheckoutBottomSheet?: Dispatch<SetStateAction<boolean>>;
  subTotal: string;
  assignSeating?: boolean; // AC008: event has assigned seating on
  seatingRows?: SeatingRow[]; // AC008: rows (with ids + variantIDs) for this event
  takenSeats?: TakenSeat[]; // AC009: already-booked seats
};
 
// TODO ADD QUANTITY INPUT COMPONENT, AS IT HAS A SPECIFIC STYLING
 
const PUBLIC_PRODUCT_ITEM_MODAL = NiceModal.create(
  ({
    product,
    addToCart,
    removeFromCart,
    accentColor,
    backgroundColor,
    productQuantity,
    displayStatus,
    formType,
    subscribeBtnText,
    isPreview,
    // This color is passed because NiceModal doesn't react to palette changes based on luminance. TODO: investigate other solution
    secondaryColor,
    showCheckoutBottomSheet,
    subTotal = "0",
    assignSeating = false,
    seatingRows = [],
    takenSeats = [],
  }: Props) => {
    const {
      thumbnail,
      amount,
      title,
      description,
      in_stock,
      paymentType,
      variantID,
      featureList,
      signupFee,
      hideInventory,
    } = product;
    const { palette } = useAppTheme();
    const [quantity, setQuantity] = useState<number>(productQuantity);
    const [seats, setSeats] = useState<SeatSelection[]>([]);
    const { open, onClose } = useNiceModal();
    const { isWideView } = useCustomThemeV2();
    const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
    const parsedDescription = parseDescription(description);
    const {
      isEvent: isEventFromRoute,
      isProduct: isProductFromRoute,
      isMembership: isMembershipFromRoute,
    } = useCheckFormType();
    const isEvent = formType ? formType === FormType.EVENTS : isEventFromRoute;
    const isProduct = formType
      ? formType === FormType.STANDARDS || formType === FormType.PRODUCTS
      : isProductFromRoute;
    const isMembership = formType
      ? formType === FormType.MEMBERSHIPS
      : isMembershipFromRoute;
    const isOutOfStock = in_stock === 0;
    const seatsRequired = isEvent && assignSeating;
    const seatVariantID = Number(product.variantID ?? product.id);
    // The variant id as it must reach the WIRE. Product types variantID as a string, but
    // Items maps `variantID: item.id` straight off the API variant (utils.ts:867), so at
    // runtime it is a NUMBER — and useAddToCart (:224) forwards productVariantID into
    // POST /cart/items verbatim. Coercing it fails the request with
    // `bad_input: Cannot unmarshal string value into field productVariantID`, so it is passed
    // through untouched.
    const cartItemVariantID = product.variantID ?? String(product.id);
    // The key CartContext files this ticket under: setCartItems writes
    // cartItems[productVariantID] and object keys are always strings. Derived from the wire
    // value above so the add and the removal can never address different entries.
    const cartItemID = String(cartItemVariantID);
 
    useEffect(() => {
      setQuantity(productQuantity);
    }, [productQuantity, product]);
 
    // PAY Builder 031 (GB-21611) — this modal is a SINGLE NiceModal instance shared by every
    // ticket: closing it calls modal.hide(), which leaves the entry in the NiceModal store, so
    // the component stays mounted and its React state survives until the next open. `quantity`
    // is re-seeded above from the incoming product, but the seat selection was not — so opening
    // ticket B after picking a seat for ticket A inherited A's seats: the picker opened at
    // "(1/1)" with a seat already counted as selected, which both mis-seeded every further
    // selection AND enabled Add to cart without a seat being chosen for B, sending A's
    // seatingRowID to the BE (checkout then rejects the cart). Clear the selection whenever the
    // modal is pointed at a different ticket/variant; re-opening the SAME ticket still keeps the
    // seats it was left with, matching what that ticket holds in the cart.
    useEffect(() => {
      setSeats([]);
    }, [seatVariantID]);
 
    // AC008: keep at most `quantity` seats selected when quantity decreases.
    useEffect(() => {
      setSeats((prev) => (prev.length > quantity ? prev.slice(0, quantity) : prev));
    }, [quantity]);
 
    const isEnabled = useIsEnabled();
    const onSubmit = async (e: React.FormEvent) => {
      e.preventDefault();
 
      try {
        addToCart(
          {
            id: String(product.id) || "",
            productVariantName: product.title,
            productVariantID: cartItemVariantID,
            productVariantPrice: parsePriceToInteger(product.amount, false),
            quantity,
            unitPrice: product.amount,
            productVariantImageURL: product.thumbnail,
            recurringIntervalName: product.paymentType,
            in_stock: product.in_stock,
            ...(seatsRequired && { seats }),
          },
          quantity,
          undefined,
          true,
        );
      } catch (error) {
        isEnabled &&
          showMessage("Error", "Something went wrong, please try again");
      } finally {
        closeModal();
      }
    };
 
    const handleIncrease = () => {
      Eif (quantity < (in_stock || Number.MAX_SAFE_INTEGER)) {
        setQuantity(quantity + 1);
      }
    };
    const handleDecrease = () => {
      Eif (quantity > 1) {
        setQuantity(quantity - 1);
      }
    };
 
    // PAY Builder 031 — a voluntary seat toggle drives the ticket quantity. Picking a seat past
    // the current allowance bumps the counter up; removing a seat while the allowance is full
    // pulls it back down; filling an open slot under the allowance (or deselecting a
    // "+"-reserved-but-unfilled slot) leaves it unchanged. reconcileSeatQuantity centralizes this.
    const handleSeatsChange = (next: SeatSelection[]) => {
      setSeats(next);
      setQuantity((q) => reconcileSeatQuantity(seats, next, q));
      // GB-21697 — deselecting the last seat un-chooses the whole ticket. Add to cart is
      // disabled on an empty selection and the card hides its stepper, so this is the only
      // moment the buyer can take a seated ticket back out; without it they are left with an
      // outlined card they cannot clear while the picker beside it reads (0/N).
      if (seatsRequired && seats.length > 0 && next.length === 0) {
        removeFromCart?.(cartItemID);
      }
    };
 
    // PAY Builder 031 — an involuntary release (seats the buyer had chosen just became taken).
    // Unlike a voluntary deselect, this always follows the counter down to the surviving seats
    // (floored at 1) so it can't leave an inflated quantity/total — including when the buyer had
    // added headroom with "+".
    const handleSeatsReleased = (survivors: SeatSelection[]) => {
      setSeats(survivors);
      setQuantity(Math.max(1, survivors.length));
    };
 
    const closeModal = () => {
      onClose();
    };
    const modalWidth = isMembership ? "520px" : thumbnail ? "960px" : "520px";
 
    const smallThumbnail = addSizeToImage(thumbnail || "", "large");
 
    const isIncreaseDisabled = (in_stock && quantity >= in_stock) || false;
 
    const { titleColor } = getTextColorsBasedOnBackground(
      rgbToHex(accentColor).toUpperCase(),
    );
 
    const isPlusAmountExceeded = isExceededAmount(
      subTotal,
      amount,
      quantity + 1,
    );
 
    // PAY Builder 031 — a seat may be picked BEYOND the current quantity (which then bumps it) as
    // long as inventory / max-amount headroom remains. The "+" stepper shares the same cap.
    const canSelectBeyond = !isIncreaseDisabled && !isPlusAmountExceeded;
 
    const isAddToCartAmountExceeded = isExceededAmount(
      subTotal,
      amount,
      quantity,
    );
 
    const { titleColor: textColor, isInputColorLight } =
      getTextColorsBasedOnBackground(rgbToHex(backgroundColor).toUpperCase());
 
    return (
      <GiveBaseModal
        open={open}
        title={title}
        width={isWideView ? modalWidth : "100%"}
        overrideIsMobileView={!isWideView}
        height="auto"
        onClose={closeModal}
        showFooter={false}
        customHeaderStyle={{
          backgroundColor: `${backgroundColor} !important`,
          color: textColor,
        }}
        closeIconProps={
          !isInputColorLight
            ? {
                sx: {
                  color: "white",
                },
              }
            : undefined
        }
        headerRightContent={
          displayStatus === TFormStatusEnum.PUBLIC ? (
            <>
              <GiveIconButton
                bgColor="darken"
                variant="ghost"
                onClick={(e) => setAnchorEl(e.currentTarget)}
                Icon={LinkSimpleIcon}
                color={
                  isInputColorLight ? palette.icon?.["icon-primary"] : "white"
                }
              />
              <PublicUrlShare
                variant="strict"
                anchorEl={anchorEl}
                setAnchorEl={setAnchorEl}
                query={variantID}
              />
            </>
          ) : null
        }
        PaperProps={{
          sx: {
            backgroundColor: `${backgroundColor} !important`,
            ...((isProduct || isEvent) && {
              "& .MuiDialogContent-root": {
                padding: "84px 40px 40px 40px !important",
              },
            }),
          },
        }}
        customDialogStyle={
          isMembership
            ? {
                "& .MuiDialogContent-root": {
                  padding: "64px 0px 16px 0px !important",
                },
              }
            : {}
        }
        customContentPadding="84px 20px 40px 20px"
      >
        <form data-testid="public_product_modal_container" onSubmit={onSubmit}>
          <Grid
            container
            gap="40px"
            direction={{ new_lg: "row", xs: "column" }}
            sx={{
              ...(isMembership
                ? {
                    gridTemplateRows: "repeat(2, 1fr)",
                  }
                : {
                    gridTemplateColumns: !isWideView
                      ? "repeat(1, 1fr)"
                      : "repeat(2, 1fr)",
 
                    flexWrap: !isWideView ? "wrap" : "nowrap",
                  }),
              justifyContent: "center",
              alignItems: "center",
            }}
            onSubmit={onSubmit}
          >
            {thumbnail && (
              <ProductImage
                src={smallThumbnail}
                alt={title}
                isMembership={isMembership}
                isMobile={!isWideView}
              />
            )}
 
            <ProductDetail isMembership={isMembership}>
              <GiveText variant="h3" sx={{ color: textColor }}>
                {title}
              </GiveText>
              <GiveText
                variant="bodyS"
                sx={{
                  color: isInputColorLight ? "#000000" : "white",
                  wordBreak: "break-word",
                  whiteSpace: "pre-line",
                }}
              >
                {parsedDescription}
              </GiveText>
              {!isMembership && (
                <GiveText
                  variant="bodyS"
                  color="primary"
                  sx={{ color: isInputColorLight ? "#000000" : "white" }}
                >
                  ${amount}{" "}
                  {paymentType !== "once" && (
                    <StyledSpan>{paymentType}</StyledSpan>
                  )}
                </GiveText>
              )}
              {(isEvent || isProduct) && (
                <>
                  {hideInventory === false && in_stock && (
                    <GiveText variant="bodyS" sx={{ color: accentColor }}>
                      {in_stock} available
                    </GiveText>
                  )}
 
                  {isOutOfStock && (
                    <GiveText variant="bodyS" color="error">
                      Sold Out
                    </GiveText>
                  )}
                </>
              )}
 
              {isMembership && (
                <>
                  {featureList && (
                    <GiveText
                      variant="bodyS"
                      sx={{
                        whiteSpace: "pre-wrap",
                        color: isInputColorLight ? "#000000" : "white",
                      }}
                    >
                      {featureList}
                    </GiveText>
                  )}
                  <GiveText variant="bodyS" sx={{ color: textColor }}>
                    {parseAmount(amount)} {CURRENCY} {paymentTypeSuffixes[paymentType || ""]} 
                  </GiveText>
                  {signupFee && (
                    <GiveText
                      variant="bodyS"
                      sx={{ color: isInputColorLight ? "#000000" : "white" }}
                    >
                      + {parseAmount(signupFee)} {CURRENCY} Signup Fee
                    </GiveText>
                  )}
                </>
              )}
              <ProductActions>
                {isMembership ? (
                  <SubscribeButton
                    product={product}
                    accentColor={accentColor}
                    buttonText={subscribeBtnText}
                    isPreview={isPreview}
                    showCheckoutBottomSheet={showCheckoutBottomSheet}
                  />
                ) : (
                  <Stack gap="16px" width="100%">
                    {seatsRequired && (
                      <SeatPicker
                        variantID={seatVariantID}
                        quantity={quantity}
                        canSelectBeyond={canSelectBeyond}
                        rows={seatingRows}
                        takenSeats={takenSeats}
                        value={seats}
                        onChange={handleSeatsChange}
                        onReleaseTaken={handleSeatsReleased}
                      />
                    )}
                    <Stack direction="row" gap="12px" width="100%">
                      <QuantityInput
                        quantity={quantity}
                        handleDecrement={handleDecrease}
                        handleIncrement={handleIncrease}
                        disableAddition={isIncreaseDisabled}
                        textColor={textColor}
                        isAmountExceeded={isPlusAmountExceeded}
                      />
                      <GiveTooltip
                        title={CANNOT_EXCEED_MAX_AMOUNT}
                        placement="top"
                        disableHoverListener={!isAddToCartAmountExceeded}
                      >
                        <GiveButton
                          onClick={onSubmit}
                          size="large"
                          disabled={
                            isAddToCartAmountExceeded ||
                            (seatsRequired && seats.length !== quantity)
                          }
                          label={`Add to cart - ${parseAmount(
                            Number(amount) * quantity,
                          )} ${CURRENCY}`}
                        sx={{
                          minWidth: !isWideView ? "230px" : "340px",
                          height: "42px",
                          background: accentColor,
                          borderColor: accentColor,
                          color: titleColor,
                          "&:hover": {
                            background: darken(accentColor, 0.2),
                          },
                        }}
                        />
                      </GiveTooltip>
                    </Stack>
                  </Stack>
                )}
              </ProductActions>
            </ProductDetail>
          </Grid>
        </form>
      </GiveBaseModal>
    );
  },
);
 
export default PUBLIC_PRODUCT_ITEM_MODAL;
 
const ProductDetail = styled(Stack, {
  shouldForwardProp: (prop) => prop !== "isMembership",
})<{ isMembership: boolean }>(({ isMembership }) => ({
  gap: "20px",
  ...(isMembership && {
    padding: "10px 40px",
    width: "100%",
  }),
}));
const ProductActions = styled(Stack)({
  gap: "12px",
  paddingTop: "24px",
  alignItems: "flex-start",
});
 
const ProductImage = styled("img", {
  shouldForwardProp: (prop) => prop !== "isMobile" && prop !== "isMembership",
})<{ isMobile: boolean; isMembership: boolean }>(
  ({ isMobile, isMembership }) => ({
    objectFit: "cover",
    width: isMobile ? "min(350px,100%)" : "400px",
    height: isMobile ? "350px" : "400px",
    borderRadius: "8px",
    flexShrink: 0,
    ...(isMembership && {
      width: "100%",
      height: "256px",
      borderRadius: "0px",
    }),
  }),
);
 
const StyledIcon = styled(GiveIconButton)({
  "&:hover": {
    background: "transparent !important",
  },
});
 
const StyledSpan = styled("span")({
  textTransform: "capitalize",
});