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 | 12x | import { useAddToCart } from "@hooks/merchant-api/cart";
import { usePayBuilderForm } from "@sections/PayBuilder/provider/PayBuilderFormProvider";
import { useIsPreviewMode } from "@sections/PayBuilder/provider/useIsPreviewMode";
import { convertProductToCartItem } from "@sections/PayBuilder/utils";
import { useEffect, useRef, useState } from "react";
export const useCreateInvoiceCart = (isPaidInvoice: boolean) => {
const { isPreviewMode } = useIsPreviewMode();
const isCartCreated = useRef<boolean>(false);
const { methods } = usePayBuilderForm();
const [disableGetProduct, setDisableGetProduct] = useState(true);
const { addToCartHandler, isFetchingCart, product, removeOldCartItems } =
useAddToCart({
disableFetchCart: false,
showModal: false,
disableGetProduct,
});
const items = methods.watch("Items");
useEffect(() => {
(async () => {
// to remove old cart items before checking the inventory
await removeOldCartItems();
setDisableGetProduct(false);
if (
isPreviewMode ||
!items ||
isFetchingCart ||
isPaidInvoice ||
!product
)
return;
const cartItemsToSave = items.map((item) =>
convertProductToCartItem(item),
);
/*
For invoices if one item is not in stock, it means others won't be as well, because
invoice cart creation happens automatically for all the items with all their quantities.
*/
if (items[0]?.in_stock === 0 || isCartCreated.current) return;
if (cartItemsToSave.length) {
(async () => {
isCartCreated.current = true;
await addToCartHandler(undefined, cartItemsToSave, undefined, false);
})();
}
})();
}, [isPreviewMode, items, isFetchingCart, isPaidInvoice, product]);
};
|