@coursebuilder/commerce-next
Version:
Commerce Functionality for Course Builder with Next.js
62 lines (61 loc) • 2.09 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { use } from 'react';
import { useMachine } from '@xstate/react';
import { pricingMachine, } from '@coursebuilder/core/pricing/pricing-state-machine';
const PricingContext = React.createContext(undefined);
export const PricingProvider = ({ children, ...props }) => {
const pricingData = use(props.pricingDataLoader);
const [state, send] = useMachine(pricingMachine, {
input: { ...props, pricingData },
});
const toggleBuyingMoreSeats = () => {
send({
type: 'TOGGLE_BUYING_MORE_SEATS',
});
send({
type: 'UPDATE_QUANTITY',
quantity: 5,
});
};
const toggleTeamPurchase = () => {
send({
type: 'TOGGLE_TEAM_PURCHASE',
});
};
const updateQuantity = (quantity) => {
send({
type: 'UPDATE_QUANTITY',
quantity,
});
};
const setMerchantCoupon = (merchantCoupon) => {
send({
type: 'SET_MERCHANT_COUPON',
merchantCoupon,
});
};
const hasUsedCouponWithBypassSoldOut = Boolean(state.context.formattedPrice?.usedCoupon?.fields?.bypassSoldOut);
const isSoldOut = Boolean(!hasUsedCouponWithBypassSoldOut &&
state.context.product.type === 'live' &&
pricingData.quantityAvailable !== -1 &&
(pricingData.quantityAvailable || 0) <= 0);
return (_jsx(PricingContext.Provider, { value: {
...state.context,
status: state.value === 'Ready To Buy' ? 'success' : 'pending',
toggleBuyingMoreSeats,
toggleTeamPurchase,
updateQuantity,
setMerchantCoupon,
pricingData,
organizationId: props.organizationId,
isSoldOut,
}, children: children }));
};
export const usePricing = () => {
const context = React.use(PricingContext);
if (!context) {
throw new Error('usePricing must be used within a PricingProvider');
}
return context;
};