All files / src/sections/PayBuilder/components/cart CartItem.tsx

47.82% Statements 22/46
50% Branches 34/68
33.33% Functions 3/9
50% Lines 22/44

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                                                                          12x                                     49x 49x 49x 49x 49x                 49x             49x 49x 49x 49x   49x   49x                                                                         49x           49x                                                                                                                                                                                                                                                                                               12x         12x 110x 49x                 12x             12x       12x      
import { Stack } from "@mui/material";
 
import GiveText from "@shared/Text/GiveText";
import QuantityInput from "../products/QuantityInput";
import { TrashIcon } from "@phosphor-icons/react";
import { styled, useAppTheme } from "@theme/v2/Provider";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import { ICartItem, useCart } from "@sections/PayBuilder/provider/CartContext";
import { addSizeToImage } from "@utils/image.helpers";
import { parseAmount } from "@utils/index";
import useCheckFormType from "../hooks/useCheckFormType";
import GiveTruncateText from "@shared/Text/GiveTruncateText";
import { deleteCardItem } from "@services/api/checkout/cart";
import { useCallback, useState } from "react";
import { useQueryClient } from "react-query";
import { QKEY_LIST_CART } from "@constants/queryKeys";
import { useParams } from "react-router-dom";
import { CircularProgress } from "@mui/material";
import { showMessage } from "@common/Toast";
import { CURRENCY } from "@constants/constants";
 
interface CartItemProps {
  item: ICartItem;
  addToCart: (
    item: ICartItem,
    addedQuantity?: number,
    quantityChangeType?: string,
  ) => void;
  removeFromCart: (ProductItemTypeId: string) => void;
  isCheckout?: boolean;
  isSuccessDisplayed?: boolean;
  isInBottomsheet?: boolean;
  onClose?: () => void;
  hideDeleteButton?: boolean;
  isDisabled?: boolean;
}
 
const CartItem = ({
  item,
  removeFromCart,
  addToCart,
  isCheckout = false,
  isSuccessDisplayed = false,
  isInBottomsheet = false,
  hideDeleteButton = false,
  isDisabled = false,
}: CartItemProps) => {
  const {
    productVariantID: id,
    productVariantImageURL,
    productVariantName,
    productVariantPrice,
    in_stock,
    recurringIntervalName,
    quantity,
    signupFee,
  } = item;
  const { palette } = useAppTheme();
  const { outOfStockItemIds } = useCart();
  const { isMembership, isInvoice } = useCheckFormType();
  const handleIncrement = () => {
    if (
      typeof in_stock === "number" &&
      (in_stock === 0 || quantity >= in_stock)
    )
      return;
    addToCart(item, 1, "increment");
  };
 
  const handleDecrement = () => {
    if (quantity > 1) {
      addToCart(item, 1, "decrement");
    } else {
      removeFromCart(id as any);
    }
  };
  const smallThumbnail = addSizeToImage(productVariantImageURL || "", "small");
  const isOutOfStock = outOfStockItemIds.includes(id);
  const queryClient = useQueryClient();
  const { id: productID } = useParams();
 
  const [isLoading, setIsLoading] = useState(false);
 
  const handleDelete = useCallback(async () => {
    const itemId = Number(item.id);
    if (!item.id || isNaN(itemId) || itemId === 0) {
      showMessage("Error", "Cannot delete item: Invalid ID");
      return;
    }
 
    setIsLoading(true);
    try {
      await deleteCardItem(itemId);
 
      // For memberships with signup fees, also delete the signup fee item
      if (item.signupID && !isNaN(Number(item.signupID))) {
        await deleteCardItem(Number(item.signupID));
      }
 
      // Optimistically update cache to avoid race conditions with stale data from backend
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      queryClient.setQueryData(QKEY_LIST_CART, (oldData: any) => {
        if (!oldData || !oldData.items) return oldData;
        return {
          ...oldData,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          items: oldData.items.filter(
            (i: any) => String(i.productVariantID) !== String(id),
          ),
        };
      });
 
      removeFromCart(String(id));
    } catch (error) {
      showMessage("Error", "Something went wrong, please try again");
    } finally {
      setIsLoading(false);
    }
  }, [id, item.id, item.signupID, productID, queryClient, removeFromCart]);
 
  const deleteButtonIcon = isLoading ? (
    <CircularProgress size={16} />
  ) : (
    <TrashIcon size={16} />
  );
 
  return (
    <>
      <StyledWrapper isLarge={!isSuccessDisplayed || !!productVariantImageURL}>
        {productVariantImageURL && (
          <StyledImage
            src={smallThumbnail as string}
            alt={productVariantName}
            width="80px"
            height="80px"
          />
        )}
        <StyledSummary>
          <Stack gap={isCheckout ? "4px" : "12px"}>
            <GiveTruncateText
              variant="bodyS"
              lineClamp={1}
              fontSize="16px"
              sx={{
                wordBreak: "break-all",
              }}
            >
              {productVariantName}
            </GiveTruncateText>
 
            {isOutOfStock ? (
              <Stack spacing={1}>
                <GiveText variant="bodyS" color="error">
                  Sold Out
                </GiveText>
                {!isSuccessDisplayed && !isInvoice && (
                  <GiveIconButton
                    onClick={handleDelete}
                    CustomIcon={deleteButtonIcon}
                    disabled={isDisabled}
                    variant="ghost"
                    size="extraSmall"
                    sx={{
                      color: palette.primitive?.error[50],
                    }}
                  />
                )}
              </Stack>
            ) : (
              <Stack
                gap="16px"
                direction={isCheckout ? "column" : "row"}
                alignItems={isCheckout ? "start" : "center"}
              >
                {!isCheckout ? (
                  <>
                    <QuantityInput
                      sx={{
                        borderRadius: "8px",
                        padding: "4px 6px",
                        "& > div": { height: "22px" },
                      }}
                      quantity={quantity}
                      handleIncrement={handleIncrement}
                      handleDecrement={handleDecrement}
                      disableAddition={
                        (in_stock && quantity >= in_stock) ||
                        isDisabled ||
                        false
                      }
                    />
                  </>
                ) : (
                  <>
                    {!isMembership && (
                      <>
                        <GiveText variant="bodyS" color="secondary">
                          Quantity: {quantity}
                        </GiveText>
                        {!isSuccessDisplayed &&
                          !isInBottomsheet &&
                          !isInvoice && (
                            <GiveIconButton
                              onClick={handleDelete}
                              CustomIcon={deleteButtonIcon}
                              disabled={isDisabled}
                              variant="ghost"
                              size="extraSmall"
                              sx={{
                                color: palette.primitive?.error[50],
                              }}
                            />
                          )}
                      </>
                    )}
                  </>
                )}
              </Stack>
            )}
          </Stack>
          <GiveText
            variant="bodyS"
            fontSize="16px"
            sx={{ marginLeft: isInBottomsheet ? "auto" : 0 }}
          >
            {parseAmount(productVariantPrice)} {CURRENCY}
            <StyledSpan>
              {" "}
              {recurringIntervalName === "once" ? "" : recurringIntervalName}
            </StyledSpan>
          </GiveText>
          {isInBottomsheet && !hideDeleteButton && (
            <GiveIconButton
              onClick={handleDelete}
              CustomIcon={deleteButtonIcon}
              disabled={isDisabled}
              variant="ghost"
              size="extraSmall"
              sx={{
                color: palette.primitive?.error[50],
                paddingTop: 0,
              }}
            />
          )}
        </StyledSummary>
      </StyledWrapper>
 
      {signupFee && isMembership && (
        <>
          <SignupWrapper
            alignItems="center"
            justifyContent="space-between"
            flexDirection="row"
            mt="16px"
          >
            <GiveText fontWeight={400} color="primary" fontSize="14px">
              Signup Fee
            </GiveText>
            <GiveText fontWeight={400} color="primary" fontSize="14px">
              {parseAmount(signupFee)} {CURRENCY}
            </GiveText>
          </SignupWrapper>
        </>
      )}
    </>
  );
};
 
export default CartItem;
 
const SignupWrapper = styled(Stack)(({ theme }) => ({
  borderBottom: `1px solid ${theme.palette.primitive?.transparent["darken-10"]}`,
  paddingBottom: "16px",
}));
 
const StyledWrapper = styled(Stack, {
  shouldForwardProp: (prop) => prop !== "isLarge",
})<{ isLarge?: boolean }>(({ theme, isLarge }) => ({
  padding: "16px 0",
  height: isLarge ? "112px" : "70px",
  gap: "16px",
  borderBottom: `1px solid ${theme.palette.primitive?.transparent["darken-10"]}`,
  flexDirection: "row",
  alignItems: "center",
}));
 
const StyledSummary = styled(Stack)({
  flexDirection: "row",
  alignItems: "flex-start",
  flex: 1,
  gap: "16px",
  justifyContent: "space-between",
});
const StyledImage = styled("img")({
  objectFit: "cover",
  borderRadius: "8px",
});
const StyledSpan = styled("span")({
  textTransform: "capitalize",
});