All files / src/sections/PayBuilder/views/events/components EventTickets.tsx

84% Statements 42/50
69.35% Branches 43/62
75% Functions 6/8
84.78% Lines 39/46

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                                                                      13x         29x 29x 29x 29x 29x 29x 29x         29x   29x   28x     28x         28x   37x   28x                           37x                                                                 13x               49x 49x 49x 49x 49x 49x 49x 49x     49x   49x                   49x 49x 49x               49x         49x                       49x           49x             49x                 49x 2x 2x                                           49x                                                                                                                                                        
import { CURRENCY } from "@constants/constants";
import NiceModal from "@ebay/nice-modal-react";
import { Box, rgbToHex, Stack } from "@mui/material";
import { isExceededAmount } from "@sections/PayBuilder/Checkout/helpers";
import { CheckoutNavButton } from "@sections/PayBuilder/components/products/CheckoutNavButton";
import QuantityInput from "@sections/PayBuilder/components/products/QuantityInput";
import { TFormStatus } from "@sections/PayBuilder/components/products/types";
import { useStockLabel } from "@sections/PayBuilder/hooks/useStockLabel";
import { useCart } from "@sections/PayBuilder/provider/CartContext";
import { usePayBuilderContext } from "@sections/PayBuilder/provider/PayBuilderContext";
import { usePayBuilderForm } from "@sections/PayBuilder/provider/PayBuilderFormProvider";
import { usePublicSeating } from "@hooks/payment-forms/usePublicSeating";
import {
  areSeatsIncomplete,
  isTicketSelected,
} from "@sections/PayBuilder/seating.helpers";
import { ProductItemType } from "@sections/PayBuilder/types";
import {
  FormType,
  getTextColorsBasedOnBackground,
  sortProducts,
} from "@sections/PayBuilder/utils";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import { parsePriceToInteger } from "@utils/helpers";
import { addSizeToImage } from "@utils/image.helpers";
import { PUBLIC_PRODUCT_ITEM_MODAL } from "modals/modal_names";
import { useAppSelector } from "@redux/hooks";
import { selectCart } from "@redux/slices/cart";
import GiveEmptyStateWrapper from "@shared/EmptyState/GiveEmptyStateWrapper";
import { checkEnd } from "@utils/date.helpers";
 
interface Props {
  isPeekMode?: boolean;
}
const EventTicketList = ({ isPeekMode }: Props) => {
  const {
    parsedValues: { accentColor, background },
    methods,
    data,
  } = usePayBuilderForm();
  const { Items } = methods.watch();
  const theme = useAppTheme();
  const { cartItems } = useCart();
  const sortedTickets = sortProducts(Items);
  const { displayStatus } = usePayBuilderContext();
  const isPublic = methods.getValues().publishedStatus === "public";
 
  // PAY Builder 031 — the event's seating config (shared react-query cache with the
  // per-ticket EventTicketItem lookups). `data.id` is the product id the
  // /products/{id}/seating endpoint expects.
  const { data: seating } = usePublicSeating(data?.id ?? "", Boolean(data?.id));
 
  if (!sortedTickets || sortedTickets.length === 0) return null;
 
  const hasQuantity = cartItems?.some((item) => item?.quantity > 0);
  // PAY Builder 031 — keep the page-level checkout button disabled until every
  // assigned-seating ticket in the cart has its seats chosen (see areSeatsIncomplete).
  const seatsIncomplete = areSeatsIncomplete(
    seating?.assignSeating ?? false,
    cartItems,
  );
  const hasEnded =
    checkEnd(data?.startsAt, data?.endsAt || 0, data?.includeTime) < Date.now();
  const isEmpty =
    Items?.filter((x) => x.display).length === 0 || (hasEnded && isPublic);
 
  return (
    <Stack
      spacing={1}
      sx={{
        borderRadius: "16px",
        gap: "20px",
        padding: "20px",
        border: `1px solid ${theme.palette.border?.primary}`,
        width: "375px",
      }}
    >
      <GiveEmptyStateWrapper isEmpty={isEmpty} section="events" noWrapper>
        <Stack gap="8px">
          {sortedTickets.map((item) => {
            return (
              <EventTicketItem
                key={item.id}
                product={item}
                accentColor={accentColor}
                background={background}
                displayStatus={displayStatus}
              />
            );
          })}
        </Stack>
        <CheckoutNavButton
          fullWidth
          disabled={cartItems?.length === 0 || !hasQuantity || seatsIncomplete}
          isPeekMode={isPeekMode}
        />
      </GiveEmptyStateWrapper>
    </Stack>
  );
};
 
export default EventTicketList;
 
type EventTicketItemProps = {
  product: ProductItemType;
  accentColor: string;
  background: string;
  displayStatus?: TFormStatus;
  // Inside a NiceModal (the mobile Tickets bottom sheet) the PayBuilder form context
  // is empty, so the sheet passes the event product id in as a prop instead.
  eventProductId?: string | number;
};
 
export const EventTicketItem = ({
  product,
  accentColor,
  background,
  displayStatus,
  eventProductId: eventProductIdProp,
}: EventTicketItemProps) => {
  const { id, title, amount, in_stock, thumbnail, paymentType, hideInventory } =
    product;
  const { palette } = useAppTheme();
  const smallThumbnail = addSizeToImage(thumbnail || "", "large");
  const { addToCart, removeFromCart, getItemInCart, subTotal } = useCart();
  const cartProduct = getItemInCart(id);
  const quantity = cartProduct ? cartProduct.quantity : 0;
  const isOutOfStock = in_stock === 0;
  const { titleColor } = getTextColorsBasedOnBackground(
    rgbToHex(background).toUpperCase(),
  );
  const isAmountExceeded = isExceededAmount(subTotal, amount);
 
  const { isCartLoading } = useAppSelector(selectCart);
 
  // AC008/AC009 — fetch the event's public seating config (assignSeating, rows,
  // takenSeats) to pass into the seat-picking modal. Keyed on the event product id
  // (react-query dedupes across tickets). formData is the flattened payment-form object;
  // its `id` IS the product id the /products/{id}/seating endpoint expects (same id
  // merchant-side watch("productId") holds). NOT formData.product.id — that wrapper only
  // lives in the QFORM cache. On assigned-seating events the card hides the +/- stepper:
  // quantity follows the seats picked in the modal, and the page-level checkout button
  // is gated on seat completeness.
  const { data: formData } = usePayBuilderForm();
  const eventProductId = eventProductIdProp ?? formData?.id;
  const { data: seating } = usePublicSeating(
    eventProductId ?? "",
    Boolean(eventProductId),
  );
 
  // GB-21697 — on a seating event the border is the card's only in-cart affordance, so it
  // must follow the chosen seats, not the mere presence of a (possibly seatless, hydrated)
  // cart item. See isTicketSelected.
  const isSelected = isTicketSelected(
    seating?.assignSeating ?? false,
    cartProduct,
  );
 
  const item = {
    id: String(product.id),
    productVariantName: product.title,
    productVariantID: product.id,
    productVariantPrice: parsePriceToInteger(amount || "", false),
    quantity: quantity,
    unitPrice: amount || "",
    productVariantImageURL: product.thumbnail || "",
    recurringIntervalName: paymentType,
    in_stock: in_stock,
  };
 
  const stock = useStockLabel({
    in_stock,
    hideInventory,
    showAvailableStock: hideInventory === false,
  });
 
  const handleIncrease = (e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (quantity < (in_stock || Number.MAX_SAFE_INTEGER)) {
      addToCart(item, 1, "increment", false);
    }
  };
 
  const handleDecrease = (e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (quantity > 1) {
      addToCart(item, 1, "decrement", false);
    } else {
      removeFromCart(String(product.id));
    }
  };
 
  const onProductClick = () => {
    Iif (isOutOfStock || isCartLoading) return;
    NiceModal.show(PUBLIC_PRODUCT_ITEM_MODAL, {
      product,
      addToCart,
      // GB-21697 — the picker is the only place a seated ticket can be un-chosen, since this
      // card hides its +/- stepper. Clearing the seat selection drops the cart entry.
      removeFromCart,
      accentColor,
      // open the modal reflecting the quantity already chosen on the card stepper
      productQuantity: quantity || 1,
      backgroundColor: background,
      secondaryColor: palette.text.secondary,
      displayStatus,
      subTotal,
      assignSeating: seating?.assignSeating ?? false,
      seatingRows: seating?.rows ?? [],
      takenSeats: seating?.takenSeats ?? [],
      // A ticket row is always an event product; the modal mounts outside the route
      // match, so it can't derive this itself (GB-21654 — the mobile seat picker).
      formType: FormType.EVENTS,
    });
  };
 
  return (
    <Stack
      sx={{
        width: "100%",
        borderRadius: "12px",
        border: `1px solid ${isSelected ? accentColor : palette.border?.primary
          }`,
        cursor: "pointer",
        ...((isOutOfStock || isCartLoading) && {
          pointerEvents: "none",
          "& img": {
            filter: "grayscale(1)",
          },
        }),
      }}
      onClick={onProductClick}
    >
      {smallThumbnail && (
        <Box
          component="img"
          src={smallThumbnail}
          alt={title}
          sx={{
            height: "85px",
            objectFit: "cover",
            borderTopLeftRadius: "12px",
            borderTopRightRadius: "12px",
          }}
        />
      )}
      <Stack
        direction="row"
        sx={{ padding: "16px" }}
        justifyContent="space-between"
        alignItems="center"
      >
        <Stack spacing={1}>
          <GiveText variant="bodyS" fontWeight={600} sx={{ color: titleColor }}>
            {title}
          </GiveText>
          <Stack direction="row" alignItems="center" spacing={1}>
            <GiveText variant="bodyS" sx={{ color: titleColor }}>
              {amount} {CURRENCY}
            </GiveText>
            <GiveText
              variant="bodyXS"
              sx={{
                color: isOutOfStock
                  ? palette.primitive?.error[50]
                  : accentColor,
              }}
            >
              {stock}
            </GiveText>
          </Stack>
        </Stack>
        <Stack>
          {!isOutOfStock && !seating?.assignSeating && (
            <QuantityInput
              handleDecrement={handleDecrease}
              handleIncrement={handleIncrease}
              disabled={isCartLoading}
              quantity={quantity}
              textColor={titleColor}
              isAmountExceeded={isAmountExceeded}
              sx={{
                padding: "8px 12px",
                minWidth: "80px",
              }}
            />
          )}
        </Stack>
      </Stack>
    </Stack>
  );
};