UNPKG

@coursebuilder/commerce-next

Version:

Commerce Functionality for Course Builder with Next.js

51 lines (50 loc) 1.64 kB
'use client'; import { jsx as _jsx } from "react/jsx-runtime"; import * as React from 'react'; const defaultPriceCheckContext = { addPrice: () => { }, isDowngrade: () => false, isDiscount: () => false, }; /** * used to check if a given price is a downgrade for the customer */ export function usePriceCheck() { return React.useContext(PriceCheckContext); } export const PriceCheckContext = React.createContext(defaultPriceCheckContext); export const PriceCheckProvider = ({ children, purchasedProductIds, }) => { const [prices, setPrices] = React.useState({}); const addPrice = React.useCallback((price, productId) => { setPrices((prevPrices) => ({ ...prevPrices, [productId]: price, })); }, [prices]); const isDowngrade = React.useCallback((price) => { if (!price || !purchasedProductIds || purchasedProductIds.length === 0) { return false; } for (const productId of purchasedProductIds) { for (const key in prices) { if (key === productId) { if (prices[key].unitPrice > price.unitPrice) { return true; } } } } return false; }, [prices]); const isDiscount = React.useCallback((price) => { if (!price) { return false; } return price.fullPrice > price.calculatedPrice; }, []); return (_jsx(PriceCheckContext.Provider, { value: { addPrice, isDowngrade, isDiscount, }, children: children })); };