@payloadcms/plugin-ecommerce 3.70.0-canary.9 → 3.71.0-internal-debug.80dab4c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/react/provider/index.d.ts +1 -0
- package/dist/react/provider/index.d.ts.map +1 -1
- package/dist/react/provider/index.js +14 -1
- package/dist/react/provider/index.js.map +1 -1
- package/dist/types/index.d.ts +4 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +6 -6
|
@@ -21,6 +21,7 @@ export declare function useCart<T extends CartsCollection>(): {
|
|
|
21
21
|
decrementItem: (item: DefaultDocumentIDType) => Promise<void>;
|
|
22
22
|
incrementItem: (item: DefaultDocumentIDType) => Promise<void>;
|
|
23
23
|
isLoading: boolean;
|
|
24
|
+
refreshCart: () => Promise<void>;
|
|
24
25
|
removeItem: (item: DefaultDocumentIDType) => Promise<void>;
|
|
25
26
|
};
|
|
26
27
|
export declare const usePayments: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/provider/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAa,MAAM,SAAS,CAAA;AAI/D,OAAO,KASN,MAAM,OAAO,CAAA;AAEd,OAAO,KAAK,EACV,mBAAmB,EAEnB,eAAe,EACf,YAAY,EACZ,QAAQ,EACR,oBAAoB,EACrB,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/provider/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAa,MAAM,SAAS,CAAA;AAI/D,OAAO,KASN,MAAM,OAAO,CAAA;AAEd,OAAO,KAAK,EACV,mBAAmB,EAEnB,eAAe,EACf,YAAY,EACZ,QAAQ,EACR,oBAAoB,EACrB,MAAM,sBAAsB,CAAA;AAyC7B,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,YAAY,CAu1BpD,CAAA;AAED,eAAO,MAAM,YAAY,4BAQxB,CAAA;AAED,eAAO,MAAM,WAAW;;6BAIX,IAAI,GAAG,MAAM,YAAY;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAG,MAAM;;;CAkCrE,CAAA;AAED,wBAAgB,OAAO,CAAC,CAAC,SAAS,eAAe;;;;;UAkB/B,CAAC;;;;;;;EAQlB;AAED,eAAO,MAAM,WAAW;;;;;;;;;;CASvB,CAAA;AAED,wBAAgB,YAAY,CAAC,CAAC,SAAS,mBAAmB;eAOvB,CAAC,EAAE;;;;;;;;;;EACrC"}
|
|
@@ -30,6 +30,7 @@ const defaultContext = {
|
|
|
30
30
|
initiatePayment: async ()=>{},
|
|
31
31
|
isLoading: false,
|
|
32
32
|
paymentMethods: [],
|
|
33
|
+
refreshCart: async ()=>{},
|
|
33
34
|
removeItem: async ()=>{},
|
|
34
35
|
setCurrency: ()=>{},
|
|
35
36
|
updateAddress: async ()=>{}
|
|
@@ -191,6 +192,16 @@ export const EcommerceProvider = ({ addressesSlug = 'addresses', api, cartsSlug
|
|
|
191
192
|
cartsSlug,
|
|
192
193
|
cartSecret
|
|
193
194
|
]);
|
|
195
|
+
const refreshCart = useCallback(async ()=>{
|
|
196
|
+
if (!cartID) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const updatedCart = await getCart(cartID);
|
|
200
|
+
setCart(updatedCart);
|
|
201
|
+
}, [
|
|
202
|
+
cartID,
|
|
203
|
+
getCart
|
|
204
|
+
]);
|
|
194
205
|
const deleteCart = useCallback(async (cartID)=>{
|
|
195
206
|
// Build query params with secret if provided
|
|
196
207
|
const queryParams = cartSecret ? {
|
|
@@ -806,6 +817,7 @@ export const EcommerceProvider = ({ addressesSlug = 'addresses', api, cartsSlug
|
|
|
806
817
|
initiatePayment,
|
|
807
818
|
isLoading,
|
|
808
819
|
paymentMethods,
|
|
820
|
+
refreshCart,
|
|
809
821
|
removeItem,
|
|
810
822
|
selectedPaymentMethod,
|
|
811
823
|
setCurrency,
|
|
@@ -852,7 +864,7 @@ export const useCurrency = ()=>{
|
|
|
852
864
|
};
|
|
853
865
|
};
|
|
854
866
|
export function useCart() {
|
|
855
|
-
const { addItem, cart, clearCart, decrementItem, incrementItem, isLoading, removeItem } = useEcommerce();
|
|
867
|
+
const { addItem, cart, clearCart, decrementItem, incrementItem, isLoading, refreshCart, removeItem } = useEcommerce();
|
|
856
868
|
if (!addItem) {
|
|
857
869
|
throw new Error('useCart must be used within an EcommerceProvider');
|
|
858
870
|
}
|
|
@@ -863,6 +875,7 @@ export function useCart() {
|
|
|
863
875
|
decrementItem,
|
|
864
876
|
incrementItem,
|
|
865
877
|
isLoading,
|
|
878
|
+
refreshCart,
|
|
866
879
|
removeItem
|
|
867
880
|
};
|
|
868
881
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple, formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, {\n createContext,\n use,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from 'react'\n\nimport type {\n AddressesCollection,\n CartItem,\n CartsCollection,\n ContextProps,\n Currency,\n EcommerceContextType,\n} from '../../types/index.js'\n\nconst defaultContext: EcommerceContextType = {\n addItem: async () => {},\n clearCart: async () => {},\n confirmOrder: async () => {},\n createAddress: async () => {},\n currenciesConfig: {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n currency: {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n decrementItem: async () => {},\n incrementItem: async () => {},\n initiatePayment: async () => {},\n isLoading: false,\n paymentMethods: [],\n removeItem: async () => {},\n setCurrency: () => {},\n updateAddress: async () => {},\n}\n\nconst EcommerceContext = createContext<EcommerceContextType>(defaultContext)\n\nconst defaultLocalStorage = {\n key: 'cart',\n}\n\nexport const EcommerceProvider: React.FC<ContextProps> = ({\n addressesSlug = 'addresses',\n api,\n cartsSlug = 'carts',\n children,\n currenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n customersSlug = 'users',\n debug = false,\n paymentMethods = [],\n syncLocalStorage = true,\n}) => {\n const localStorageConfig =\n syncLocalStorage && typeof syncLocalStorage === 'object'\n ? {\n ...defaultLocalStorage,\n ...syncLocalStorage,\n }\n : defaultLocalStorage\n\n const { apiRoute = '/api', cartsFetchQuery = {} } = api || {}\n const baseAPIURL = formatAdminURL({\n apiRoute,\n path: '',\n })\n\n const [isLoading, startTransition] = useTransition()\n\n const [user, setUser] = useState<null | TypedUser>(null)\n\n const [addresses, setAddresses] = useState<AddressesCollection[]>()\n\n const hasRendered = useRef(false)\n\n /**\n * The ID of the cart associated with the current session.\n * This is used to identify the cart in the database or local storage.\n * It can be null if no cart has been created yet.\n */\n const [cartID, setCartID] = useState<DefaultDocumentIDType>()\n /**\n * The secret for accessing guest carts without authentication.\n * This is generated when a guest user creates a cart.\n */\n const [cartSecret, setCartSecret] = useState<string | undefined>(undefined)\n const [cart, setCart] = useState<CartsCollection>()\n\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(\n () =>\n currenciesConfig.supportedCurrencies.find(\n (c) => c.code === currenciesConfig.defaultCurrency,\n )!,\n )\n\n const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<null | string>(null)\n\n const cartQuery = useMemo(() => {\n const priceField = `priceIn${selectedCurrency.code}`\n\n const baseQuery = {\n depth: 0,\n populate: {\n products: {\n [priceField]: true,\n },\n variants: {\n options: true,\n [priceField]: true,\n },\n },\n select: {\n items: true,\n subtotal: true,\n },\n }\n\n return deepMergeSimple(baseQuery, cartsFetchQuery)\n }, [selectedCurrency.code, cartsFetchQuery])\n\n const createCart = useCallback(\n async (initialData: Record<string, unknown>) => {\n const query = qs.stringify(cartQuery)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}?${query}`, {\n body: JSON.stringify({\n ...initialData,\n currency: selectedCurrency.code,\n customer: user?.id,\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to create cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart creation error: ${data.error}`)\n }\n\n // Store the secret for guest cart access\n if (!user && data.doc?.secret) {\n setCartSecret(data.doc.secret)\n }\n\n return data.doc as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug, selectedCurrency.code, user],\n )\n\n const getCart = useCallback(\n async (cartID: DefaultDocumentIDType, options?: { secret?: string }) => {\n const secret = options?.secret\n\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(secret ? { secret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart fetch error: ${data.error}`)\n }\n\n return data as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug],\n )\n\n const updateCart = useCallback(\n async (cartID: DefaultDocumentIDType, data: Partial<CartsCollection>) => {\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(cartSecret ? { secret: cartSecret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n body: JSON.stringify(data),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update cart: ${errorText}`)\n }\n\n const updatedCart = await response.json()\n\n setCart(updatedCart.doc as CartsCollection)\n },\n [baseAPIURL, cartQuery, cartsSlug, cartSecret],\n )\n\n const deleteCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n // Build query params with secret if provided\n const queryParams = cartSecret ? { secret: cartSecret } : {}\n const query = qs.stringify(queryParams)\n const url = `${baseAPIURL}/${cartsSlug}/${cartID}${query ? `?${query}` : ''}`\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'DELETE',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to delete cart: ${errorText}`)\n }\n\n setCart(undefined)\n setCartID(undefined)\n setCartSecret(undefined)\n },\n [baseAPIURL, cartsSlug, cartSecret],\n )\n\n // Persist cart ID and secret to localStorage\n useEffect(() => {\n if (hasRendered.current) {\n if (syncLocalStorage) {\n if (cartID) {\n localStorage.setItem(localStorageConfig.key, cartID as string)\n } else {\n localStorage.removeItem(localStorageConfig.key)\n }\n\n if (cartSecret) {\n localStorage.setItem(`${localStorageConfig.key}_secret`, cartSecret)\n } else {\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n }\n }\n }\n }, [cartID, cartSecret, localStorageConfig.key, syncLocalStorage])\n\n const addItem: EcommerceContextType['addItem'] = useCallback(\n async (item, quantity = 1) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n\n setCartID(undefined)\n setCart(undefined)\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => {\n const productID =\n typeof cartItem.product === 'object' ? cartItem.product.id : item.product\n const variantID =\n cartItem.variant && typeof cartItem.variant === 'object'\n ? cartItem.variant.id\n : item.variant\n\n return (\n productID === item.product &&\n (item.variant && variantID ? variantID === item.variant : true)\n )\n }) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, update its quantity\n updatedItems[existingItemIndex].quantity =\n updatedItems[existingItemIndex].quantity + quantity\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart\n updatedItems = [...(existingCart.items ?? []), { ...item, quantity }]\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If no cartID exists, create a new cart\n const newCart = await createCart({ items: [{ ...item, quantity }] })\n\n setCartID(newCart.id)\n setCart(newCart)\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, createCart, getCart, startTransition, updateCart],\n )\n\n const removeItem: EcommerceContextType['removeItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n if (existingItemIndex !== -1) {\n // If the item exists, remove it from the cart\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n updatedItems.splice(existingItemIndex, 1)\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const incrementItem: EcommerceContextType['incrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, increment its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity + 1 // Increment by 1\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart with quantity 1\n updatedItems = [...(existingCart.items ?? []), { product: targetID, quantity: 1 }]\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const decrementItem: EcommerceContextType['decrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, decrement its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity - 1 // Decrement by 1\n\n // If the quantity reaches 0, remove the item from the cart\n if (updatedItems[existingItemIndex].quantity <= 0) {\n updatedItems.splice(existingItemIndex, 1)\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const clearCart: EcommerceContextType['clearCart'] = useCallback(async () => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n await deleteCart(cartID)\n }\n resolve()\n })\n })\n }, [cartID, deleteCart, startTransition])\n\n const setCurrency: EcommerceContextType['setCurrency'] = useCallback(\n (currency) => {\n if (selectedCurrency.code === currency) {\n return\n }\n\n const foundCurrency = currenciesConfig.supportedCurrencies.find((c) => c.code === currency)\n if (!foundCurrency) {\n throw new Error(`Currency with code \"${currency}\" not found in config`)\n }\n\n setSelectedCurrency(foundCurrency)\n },\n [currenciesConfig.supportedCurrencies, selectedCurrency.code],\n )\n\n const initiatePayment = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n const paymentMethod = paymentMethods.find((method) => method.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (!cartID) {\n throw new Error(`No cart is provided.`)\n }\n\n setSelectedPaymentMethod(paymentMethodID)\n\n if (paymentMethod.initiatePayment) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/initiate`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n try {\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error initiating payment:', error)\n }\n throw new Error(error instanceof Error ? error.message : 'Failed to initiate payment')\n }\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support payment initiation`)\n }\n },\n [baseAPIURL, cartID, debug, paymentMethods, selectedCurrency.code],\n )\n\n const confirmOrder = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n if (!cartID) {\n throw new Error(`Cart is empty.`)\n }\n\n const paymentMethod = paymentMethods.find((pm) => pm.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (paymentMethod.confirmOrder) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/confirm-order`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support order confirmation`)\n }\n },\n [baseAPIURL, cartID, paymentMethods, selectedCurrency.code],\n )\n\n const getUser = useCallback(async () => {\n try {\n const query = qs.stringify({\n depth: 0,\n select: {\n id: true,\n carts: true,\n },\n })\n\n const response = await fetch(`${baseAPIURL}/${customersSlug}/me?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch user: ${errorText}`)\n }\n\n const userData = await response.json()\n\n if (userData.error) {\n throw new Error(`User fetch error: ${userData.error}`)\n }\n\n if (userData.user) {\n setUser(userData.user as TypedUser)\n return userData.user as TypedUser\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user:', error)\n }\n setUser(null)\n throw new Error(\n `Failed to fetch user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [baseAPIURL, customersSlug, debug])\n\n const getAddresses = useCallback(async () => {\n if (!user) {\n return\n }\n\n try {\n const query = qs.stringify({\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n const response = await fetch(`${baseAPIURL}/${addressesSlug}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n\n throw new Error(errorText)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address fetch error: ${data.error}`)\n }\n\n if (data.docs && data.docs.length > 0) {\n setAddresses(data.docs)\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching addresses:', error)\n }\n setAddresses(undefined)\n throw new Error(\n `Failed to fetch addresses: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [user, baseAPIURL, addressesSlug, debug])\n\n const updateAddress = useCallback<EcommerceContextType['updateAddress']>(\n async (addressID, address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}/${addressID}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n const createAddress = useCallback<EcommerceContextType['createAddress']>(\n async (address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n // If localStorage is enabled, restore cart from storage\n useEffect(() => {\n if (!hasRendered.current) {\n if (syncLocalStorage) {\n const storedCartID = localStorage.getItem(localStorageConfig.key)\n const storedSecret = localStorage.getItem(`${localStorageConfig.key}_secret`)\n\n if (storedCartID) {\n getCart(storedCartID, { secret: storedSecret || undefined })\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(storedCartID as DefaultDocumentIDType)\n if (storedSecret) {\n setCartSecret(storedSecret)\n }\n })\n .catch((_) => {\n // console.error('Error fetching cart from localStorage:', error)\n // If there's an error fetching the cart, clear it from localStorage\n localStorage.removeItem(localStorageConfig.key)\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n setCartID(undefined)\n setCart(undefined)\n setCartSecret(undefined)\n })\n }\n }\n\n hasRendered.current = true\n\n void getUser().then((user) => {\n if (user && user.cart?.docs && user.cart.docs.length > 0) {\n // If the user has carts, we can set the cartID to the first cart\n const cartID =\n typeof user.cart.docs[0] === 'object' ? user.cart.docs[0].id : user.cart.docs[0]\n\n if (cartID) {\n getCart(cartID)\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(cartID)\n })\n .catch((error) => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user cart:', error)\n }\n\n setCart(undefined)\n setCartID(undefined)\n\n throw new Error(`Failed to fetch user cart: ${error.message}`)\n })\n }\n }\n })\n }\n }, [debug, getAddresses, getCart, getUser, localStorageConfig.key, syncLocalStorage])\n\n useEffect(() => {\n if (user) {\n // If the user is logged in, fetch their addresses\n void getAddresses()\n } else {\n // If no user is logged in, clear addresses\n setAddresses(undefined)\n }\n }, [getAddresses, user])\n\n return (\n <EcommerceContext\n value={{\n addItem,\n addresses,\n cart,\n clearCart,\n confirmOrder,\n createAddress,\n currenciesConfig,\n currency: selectedCurrency,\n decrementItem,\n incrementItem,\n initiatePayment,\n isLoading,\n paymentMethods,\n removeItem,\n selectedPaymentMethod,\n setCurrency,\n updateAddress,\n }}\n >\n {children}\n </EcommerceContext>\n )\n}\n\nexport const useEcommerce = () => {\n const context = use(EcommerceContext)\n\n if (!context) {\n throw new Error('useEcommerce must be used within an EcommerceProvider')\n }\n\n return context\n}\n\nexport const useCurrency = () => {\n const { currenciesConfig, currency, setCurrency } = useEcommerce()\n\n const formatCurrency = useCallback(\n (value?: null | number, options?: { currency?: Currency }): string => {\n if (value === undefined || value === null) {\n return ''\n }\n\n const currencyToUse = options?.currency || currency\n\n if (!currencyToUse) {\n return value.toString()\n }\n\n if (value === 0) {\n return `${currencyToUse.symbol}0.${'0'.repeat(currencyToUse.decimals)}`\n }\n\n // Convert from base value (e.g., cents) to decimal value (e.g., dollars)\n const decimalValue = value / Math.pow(10, currencyToUse.decimals)\n\n // Format with the correct number of decimal places\n return `${currencyToUse.symbol}${decimalValue.toFixed(currencyToUse.decimals)}`\n },\n [currency],\n )\n\n if (!currency) {\n throw new Error('useCurrency must be used within an EcommerceProvider')\n }\n\n return {\n currency,\n formatCurrency,\n setCurrency,\n supportedCurrencies: currenciesConfig.supportedCurrencies,\n }\n}\n\nexport function useCart<T extends CartsCollection>() {\n const { addItem, cart, clearCart, decrementItem, incrementItem, isLoading, removeItem } =\n useEcommerce()\n\n if (!addItem) {\n throw new Error('useCart must be used within an EcommerceProvider')\n }\n\n return {\n addItem,\n cart: cart as T,\n clearCart,\n decrementItem,\n incrementItem,\n isLoading,\n removeItem,\n }\n}\n\nexport const usePayments = () => {\n const { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod } =\n useEcommerce()\n\n if (!initiatePayment) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod }\n}\n\nexport function useAddresses<T extends AddressesCollection>() {\n const { addresses, createAddress, isLoading, updateAddress } = useEcommerce()\n\n if (!createAddress) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { addresses: addresses as T[], createAddress, isLoading, updateAddress }\n}\n"],"names":["deepMergeSimple","formatAdminURL","qs","React","createContext","use","useCallback","useEffect","useMemo","useRef","useState","useTransition","defaultContext","addItem","clearCart","confirmOrder","createAddress","currenciesConfig","defaultCurrency","supportedCurrencies","code","decimals","label","symbol","currency","decrementItem","incrementItem","initiatePayment","isLoading","paymentMethods","removeItem","setCurrency","updateAddress","EcommerceContext","defaultLocalStorage","key","EcommerceProvider","addressesSlug","api","cartsSlug","children","customersSlug","debug","syncLocalStorage","localStorageConfig","apiRoute","cartsFetchQuery","baseAPIURL","path","startTransition","user","setUser","addresses","setAddresses","hasRendered","cartID","setCartID","cartSecret","setCartSecret","undefined","cart","setCart","selectedCurrency","setSelectedCurrency","find","c","selectedPaymentMethod","setSelectedPaymentMethod","cartQuery","priceField","baseQuery","depth","populate","products","variants","options","select","items","subtotal","createCart","initialData","query","stringify","response","fetch","body","JSON","customer","id","credentials","headers","method","ok","errorText","text","Error","data","json","error","doc","secret","getCart","queryParams","updateCart","updatedCart","deleteCart","url","current","localStorage","setItem","item","quantity","Promise","resolve","existingCart","existingItemIndex","findIndex","cartItem","productID","product","variantID","variant","updatedItems","newCart","targetID","splice","foundCurrency","paymentMethodID","paymentMethod","name","fetchURL","additionalData","responseError","responseData","console","message","pm","getUser","carts","userData","getAddresses","limit","pagination","docs","length","addressID","address","storedCartID","getItem","storedSecret","then","fetchedCart","catch","_","value","useEcommerce","context","useCurrency","formatCurrency","currencyToUse","toString","repeat","decimalValue","Math","pow","toFixed","useCart","usePayments","useAddresses"],"mappings":"AAAA;;AAGA,SAASA,eAAe,EAAEC,cAAc,QAAQ,iBAAgB;AAChE,YAAYC,QAAQ,SAAQ;AAC5B,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e;QAClB,MAAM,IAAI+E,MAAM;IAClB;IAEA,OAAO;QAAE3C,WAAWA;QAAkBpC;QAAeY;QAAWI;IAAc;AAChF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple, formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, {\n createContext,\n use,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from 'react'\n\nimport type {\n AddressesCollection,\n CartItem,\n CartsCollection,\n ContextProps,\n Currency,\n EcommerceContextType,\n} from '../../types/index.js'\n\nconst defaultContext: EcommerceContextType = {\n addItem: async () => {},\n clearCart: async () => {},\n confirmOrder: async () => {},\n createAddress: async () => {},\n currenciesConfig: {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n currency: {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n decrementItem: async () => {},\n incrementItem: async () => {},\n initiatePayment: async () => {},\n isLoading: false,\n paymentMethods: [],\n refreshCart: async () => {},\n removeItem: async () => {},\n setCurrency: () => {},\n updateAddress: async () => {},\n}\n\nconst EcommerceContext = createContext<EcommerceContextType>(defaultContext)\n\nconst defaultLocalStorage = {\n key: 'cart',\n}\n\nexport const EcommerceProvider: React.FC<ContextProps> = ({\n addressesSlug = 'addresses',\n api,\n cartsSlug = 'carts',\n children,\n currenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n customersSlug = 'users',\n debug = false,\n paymentMethods = [],\n syncLocalStorage = true,\n}) => {\n const localStorageConfig =\n syncLocalStorage && typeof syncLocalStorage === 'object'\n ? {\n ...defaultLocalStorage,\n ...syncLocalStorage,\n }\n : defaultLocalStorage\n\n const { apiRoute = '/api', cartsFetchQuery = {} } = api || {}\n const baseAPIURL = formatAdminURL({\n apiRoute,\n path: '',\n })\n\n const [isLoading, startTransition] = useTransition()\n\n const [user, setUser] = useState<null | TypedUser>(null)\n\n const [addresses, setAddresses] = useState<AddressesCollection[]>()\n\n const hasRendered = useRef(false)\n\n /**\n * The ID of the cart associated with the current session.\n * This is used to identify the cart in the database or local storage.\n * It can be null if no cart has been created yet.\n */\n const [cartID, setCartID] = useState<DefaultDocumentIDType>()\n /**\n * The secret for accessing guest carts without authentication.\n * This is generated when a guest user creates a cart.\n */\n const [cartSecret, setCartSecret] = useState<string | undefined>(undefined)\n const [cart, setCart] = useState<CartsCollection>()\n\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(\n () =>\n currenciesConfig.supportedCurrencies.find(\n (c) => c.code === currenciesConfig.defaultCurrency,\n )!,\n )\n\n const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<null | string>(null)\n\n const cartQuery = useMemo(() => {\n const priceField = `priceIn${selectedCurrency.code}`\n\n const baseQuery = {\n depth: 0,\n populate: {\n products: {\n [priceField]: true,\n },\n variants: {\n options: true,\n [priceField]: true,\n },\n },\n select: {\n items: true,\n subtotal: true,\n },\n }\n\n return deepMergeSimple(baseQuery, cartsFetchQuery)\n }, [selectedCurrency.code, cartsFetchQuery])\n\n const createCart = useCallback(\n async (initialData: Record<string, unknown>) => {\n const query = qs.stringify(cartQuery)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}?${query}`, {\n body: JSON.stringify({\n ...initialData,\n currency: selectedCurrency.code,\n customer: user?.id,\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to create cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart creation error: ${data.error}`)\n }\n\n // Store the secret for guest cart access\n if (!user && data.doc?.secret) {\n setCartSecret(data.doc.secret)\n }\n\n return data.doc as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug, selectedCurrency.code, user],\n )\n\n const getCart = useCallback(\n async (cartID: DefaultDocumentIDType, options?: { secret?: string }) => {\n const secret = options?.secret\n\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(secret ? { secret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart fetch error: ${data.error}`)\n }\n\n return data as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug],\n )\n\n const updateCart = useCallback(\n async (cartID: DefaultDocumentIDType, data: Partial<CartsCollection>) => {\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(cartSecret ? { secret: cartSecret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n body: JSON.stringify(data),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update cart: ${errorText}`)\n }\n\n const updatedCart = await response.json()\n\n setCart(updatedCart.doc as CartsCollection)\n },\n [baseAPIURL, cartQuery, cartsSlug, cartSecret],\n )\n\n const refreshCart = useCallback<EcommerceContextType['refreshCart']>(async () => {\n if (!cartID) {\n return\n }\n const updatedCart = await getCart(cartID)\n setCart(updatedCart)\n }, [cartID, getCart])\n\n const deleteCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n // Build query params with secret if provided\n const queryParams = cartSecret ? { secret: cartSecret } : {}\n const query = qs.stringify(queryParams)\n const url = `${baseAPIURL}/${cartsSlug}/${cartID}${query ? `?${query}` : ''}`\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'DELETE',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to delete cart: ${errorText}`)\n }\n\n setCart(undefined)\n setCartID(undefined)\n setCartSecret(undefined)\n },\n [baseAPIURL, cartsSlug, cartSecret],\n )\n\n // Persist cart ID and secret to localStorage\n useEffect(() => {\n if (hasRendered.current) {\n if (syncLocalStorage) {\n if (cartID) {\n localStorage.setItem(localStorageConfig.key, cartID as string)\n } else {\n localStorage.removeItem(localStorageConfig.key)\n }\n\n if (cartSecret) {\n localStorage.setItem(`${localStorageConfig.key}_secret`, cartSecret)\n } else {\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n }\n }\n }\n }, [cartID, cartSecret, localStorageConfig.key, syncLocalStorage])\n\n const addItem: EcommerceContextType['addItem'] = useCallback(\n async (item, quantity = 1) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n\n setCartID(undefined)\n setCart(undefined)\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => {\n const productID =\n typeof cartItem.product === 'object' ? cartItem.product.id : item.product\n const variantID =\n cartItem.variant && typeof cartItem.variant === 'object'\n ? cartItem.variant.id\n : item.variant\n\n return (\n productID === item.product &&\n (item.variant && variantID ? variantID === item.variant : true)\n )\n }) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, update its quantity\n updatedItems[existingItemIndex].quantity =\n updatedItems[existingItemIndex].quantity + quantity\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart\n updatedItems = [...(existingCart.items ?? []), { ...item, quantity }]\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If no cartID exists, create a new cart\n const newCart = await createCart({ items: [{ ...item, quantity }] })\n\n setCartID(newCart.id)\n setCart(newCart)\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, createCart, getCart, startTransition, updateCart],\n )\n\n const removeItem: EcommerceContextType['removeItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n if (existingItemIndex !== -1) {\n // If the item exists, remove it from the cart\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n updatedItems.splice(existingItemIndex, 1)\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const incrementItem: EcommerceContextType['incrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, increment its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity + 1 // Increment by 1\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart with quantity 1\n updatedItems = [...(existingCart.items ?? []), { product: targetID, quantity: 1 }]\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const decrementItem: EcommerceContextType['decrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, decrement its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity - 1 // Decrement by 1\n\n // If the quantity reaches 0, remove the item from the cart\n if (updatedItems[existingItemIndex].quantity <= 0) {\n updatedItems.splice(existingItemIndex, 1)\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const clearCart: EcommerceContextType['clearCart'] = useCallback(async () => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n await deleteCart(cartID)\n }\n resolve()\n })\n })\n }, [cartID, deleteCart, startTransition])\n\n const setCurrency: EcommerceContextType['setCurrency'] = useCallback(\n (currency) => {\n if (selectedCurrency.code === currency) {\n return\n }\n\n const foundCurrency = currenciesConfig.supportedCurrencies.find((c) => c.code === currency)\n if (!foundCurrency) {\n throw new Error(`Currency with code \"${currency}\" not found in config`)\n }\n\n setSelectedCurrency(foundCurrency)\n },\n [currenciesConfig.supportedCurrencies, selectedCurrency.code],\n )\n\n const initiatePayment = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n const paymentMethod = paymentMethods.find((method) => method.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (!cartID) {\n throw new Error(`No cart is provided.`)\n }\n\n setSelectedPaymentMethod(paymentMethodID)\n\n if (paymentMethod.initiatePayment) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/initiate`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n try {\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error initiating payment:', error)\n }\n throw new Error(error instanceof Error ? error.message : 'Failed to initiate payment')\n }\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support payment initiation`)\n }\n },\n [baseAPIURL, cartID, debug, paymentMethods, selectedCurrency.code],\n )\n\n const confirmOrder = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n if (!cartID) {\n throw new Error(`Cart is empty.`)\n }\n\n const paymentMethod = paymentMethods.find((pm) => pm.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (paymentMethod.confirmOrder) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/confirm-order`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support order confirmation`)\n }\n },\n [baseAPIURL, cartID, paymentMethods, selectedCurrency.code],\n )\n\n const getUser = useCallback(async () => {\n try {\n const query = qs.stringify({\n depth: 0,\n select: {\n id: true,\n carts: true,\n },\n })\n\n const response = await fetch(`${baseAPIURL}/${customersSlug}/me?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch user: ${errorText}`)\n }\n\n const userData = await response.json()\n\n if (userData.error) {\n throw new Error(`User fetch error: ${userData.error}`)\n }\n\n if (userData.user) {\n setUser(userData.user as TypedUser)\n return userData.user as TypedUser\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user:', error)\n }\n setUser(null)\n throw new Error(\n `Failed to fetch user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [baseAPIURL, customersSlug, debug])\n\n const getAddresses = useCallback(async () => {\n if (!user) {\n return\n }\n\n try {\n const query = qs.stringify({\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n const response = await fetch(`${baseAPIURL}/${addressesSlug}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n\n throw new Error(errorText)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address fetch error: ${data.error}`)\n }\n\n if (data.docs && data.docs.length > 0) {\n setAddresses(data.docs)\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching addresses:', error)\n }\n setAddresses(undefined)\n throw new Error(\n `Failed to fetch addresses: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [user, baseAPIURL, addressesSlug, debug])\n\n const updateAddress = useCallback<EcommerceContextType['updateAddress']>(\n async (addressID, address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}/${addressID}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n const createAddress = useCallback<EcommerceContextType['createAddress']>(\n async (address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n // If localStorage is enabled, restore cart from storage\n useEffect(() => {\n if (!hasRendered.current) {\n if (syncLocalStorage) {\n const storedCartID = localStorage.getItem(localStorageConfig.key)\n const storedSecret = localStorage.getItem(`${localStorageConfig.key}_secret`)\n\n if (storedCartID) {\n getCart(storedCartID, { secret: storedSecret || undefined })\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(storedCartID as DefaultDocumentIDType)\n if (storedSecret) {\n setCartSecret(storedSecret)\n }\n })\n .catch((_) => {\n // console.error('Error fetching cart from localStorage:', error)\n // If there's an error fetching the cart, clear it from localStorage\n localStorage.removeItem(localStorageConfig.key)\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n setCartID(undefined)\n setCart(undefined)\n setCartSecret(undefined)\n })\n }\n }\n\n hasRendered.current = true\n\n void getUser().then((user) => {\n if (user && user.cart?.docs && user.cart.docs.length > 0) {\n // If the user has carts, we can set the cartID to the first cart\n const cartID =\n typeof user.cart.docs[0] === 'object' ? user.cart.docs[0].id : user.cart.docs[0]\n\n if (cartID) {\n getCart(cartID)\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(cartID)\n })\n .catch((error) => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user cart:', error)\n }\n\n setCart(undefined)\n setCartID(undefined)\n\n throw new Error(`Failed to fetch user cart: ${error.message}`)\n })\n }\n }\n })\n }\n }, [debug, getAddresses, getCart, getUser, localStorageConfig.key, syncLocalStorage])\n\n useEffect(() => {\n if (user) {\n // If the user is logged in, fetch their addresses\n void getAddresses()\n } else {\n // If no user is logged in, clear addresses\n setAddresses(undefined)\n }\n }, [getAddresses, user])\n\n return (\n <EcommerceContext\n value={{\n addItem,\n addresses,\n cart,\n clearCart,\n confirmOrder,\n createAddress,\n currenciesConfig,\n currency: selectedCurrency,\n decrementItem,\n incrementItem,\n initiatePayment,\n isLoading,\n paymentMethods,\n refreshCart,\n removeItem,\n selectedPaymentMethod,\n setCurrency,\n updateAddress,\n }}\n >\n {children}\n </EcommerceContext>\n )\n}\n\nexport const useEcommerce = () => {\n const context = use(EcommerceContext)\n\n if (!context) {\n throw new Error('useEcommerce must be used within an EcommerceProvider')\n }\n\n return context\n}\n\nexport const useCurrency = () => {\n const { currenciesConfig, currency, setCurrency } = useEcommerce()\n\n const formatCurrency = useCallback(\n (value?: null | number, options?: { currency?: Currency }): string => {\n if (value === undefined || value === null) {\n return ''\n }\n\n const currencyToUse = options?.currency || currency\n\n if (!currencyToUse) {\n return value.toString()\n }\n\n if (value === 0) {\n return `${currencyToUse.symbol}0.${'0'.repeat(currencyToUse.decimals)}`\n }\n\n // Convert from base value (e.g., cents) to decimal value (e.g., dollars)\n const decimalValue = value / Math.pow(10, currencyToUse.decimals)\n\n // Format with the correct number of decimal places\n return `${currencyToUse.symbol}${decimalValue.toFixed(currencyToUse.decimals)}`\n },\n [currency],\n )\n\n if (!currency) {\n throw new Error('useCurrency must be used within an EcommerceProvider')\n }\n\n return {\n currency,\n formatCurrency,\n setCurrency,\n supportedCurrencies: currenciesConfig.supportedCurrencies,\n }\n}\n\nexport function useCart<T extends CartsCollection>() {\n const {\n addItem,\n cart,\n clearCart,\n decrementItem,\n incrementItem,\n isLoading,\n refreshCart,\n removeItem,\n } = useEcommerce()\n\n if (!addItem) {\n throw new Error('useCart must be used within an EcommerceProvider')\n }\n\n return {\n addItem,\n cart: cart as T,\n clearCart,\n decrementItem,\n incrementItem,\n isLoading,\n refreshCart,\n removeItem,\n }\n}\n\nexport const usePayments = () => {\n const { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod } =\n useEcommerce()\n\n if (!initiatePayment) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod }\n}\n\nexport function useAddresses<T extends AddressesCollection>() {\n const { addresses, createAddress, isLoading, updateAddress } = useEcommerce()\n\n if (!createAddress) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { addresses: addresses as T[], createAddress, isLoading, updateAddress }\n}\n"],"names":["deepMergeSimple","formatAdminURL","qs","React","createContext","use","useCallback","useEffect","useMemo","useRef","useState","useTransition","defaultContext","addItem","clearCart","confirmOrder","createAddress","currenciesConfig","defaultCurrency","supportedCurrencies","code","decimals","label","symbol","currency","decrementItem","incrementItem","initiatePayment","isLoading","paymentMethods","refreshCart","removeItem","setCurrency","updateAddress","EcommerceContext","defaultLocalStorage","key","EcommerceProvider","addressesSlug","api","cartsSlug","children","customersSlug","debug","syncLocalStorage","localStorageConfig","apiRoute","cartsFetchQuery","baseAPIURL","path","startTransition","user","setUser","addresses","setAddresses","hasRendered","cartID","setCartID","cartSecret","setCartSecret","undefined","cart","setCart","selectedCurrency","setSelectedCurrency","find","c","selectedPaymentMethod","setSelectedPaymentMethod","cartQuery","priceField","baseQuery","depth","populate","products","variants","options","select","items","subtotal","createCart","initialData","query","stringify","response","fetch","body","JSON","customer","id","credentials","headers","method","ok","errorText","text","Error","data","json","error","doc","secret","getCart","queryParams","updateCart","updatedCart","deleteCart","url","current","localStorage","setItem","item","quantity","Promise","resolve","existingCart","existingItemIndex","findIndex","cartItem","productID","product","variantID","variant","updatedItems","newCart","targetID","splice","foundCurrency","paymentMethodID","paymentMethod","name","fetchURL","additionalData","responseError","responseData","console","message","pm","getUser","carts","userData","getAddresses","limit","pagination","docs","length","addressID","address","storedCartID","getItem","storedSecret","then","fetchedCart","catch","_","value","useEcommerce","context","useCurrency","formatCurrency","currencyToUse","toString","repeat","decimalValue","Math","pow","toFixed","useCart","usePayments","useAddresses"],"mappings":"AAAA;;AAGA,SAASA,eAAe,EAAEC,cAAc,QAAQ,iBAAgB;AAChE,YAAYC,QAAQ,SAAQ;AAC5B,OAAOC,SACLC,aAAa,EACbC,GAAG,EACHC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,aAAa,QACR,QAAO;AAWd,MAAMC,iBAAuC;IAC3CC,SAAS,WAAa;IACtBC,WAAW,WAAa;IACxBC,cAAc,WAAa;IAC3BC,eAAe,WAAa;IAC5BC,kBAAkB;QAChBC,iBAAiB;QACjBC,qBAAqB;YACnB;gBACEC,MAAM;gBACNC,UA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ts
CHANGED
|
@@ -828,6 +828,10 @@ export type EcommerceContextType<T extends EcommerceCollections = EcommerceColle
|
|
|
828
828
|
*/
|
|
829
829
|
isLoading: boolean;
|
|
830
830
|
paymentMethods: PaymentAdapterClient[];
|
|
831
|
+
/**
|
|
832
|
+
* Refresh the cart.
|
|
833
|
+
*/
|
|
834
|
+
refreshCart: () => Promise<void>;
|
|
831
835
|
/**
|
|
832
836
|
* Remove an item from the cart by its index ID.
|
|
833
837
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,gBAAgB,EAChB,qBAAqB,EACrB,QAAQ,EACR,KAAK,EACL,WAAW,EACX,UAAU,EACV,cAAc,EACd,YAAY,EACZ,UAAU,EACV,eAAe,EACf,KAAK,EACN,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE;IAAE,aAAa,EAAE,KAAK,EAAE,CAAA;CAAE,KAAK,KAAK,EAAE,CAAA;AAE1E,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE;IACtC,iBAAiB,EAAE,gBAAgB,CAAA;CACpC,KAAK,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;AAElD,MAAM,MAAM,QAAQ,GAAG;IACrB,EAAE,EAAE,qBAAqB,CAAA;IACzB,OAAO,EAAE,qBAAqB,GAAG,eAAe,CAAC,UAAU,CAAC,CAAA;IAC5D,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,qBAAqB,GAAG,eAAe,CAAC,UAAU,CAAC,CAAA;CAC9D,CAAA;AAED,KAAK,eAAe,GAAG;IACrB,QAAQ,CAAC,EAAE,MAAM,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AK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7D;;OAEG;IACH,aAAa,EAAE,CAAC,IAAI,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7D;;;;OAIG;IACH,eAAe,EAAE,CACf,eAAe,EAAE,MAAM,EACvB,OAAO,CAAC,EAAE;QAAE,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,KAClD,OAAO,CAAC,OAAO,CAAC,CAAA;IACrB;;;OAGG;IACH,SAAS,EAAE,OAAO,CAAA;IAClB,cAAc,EAAE,oBAAoB,EAAE,CAAA;IACtC;;OAEG;IACH,WAAW,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAChC;;OAEG;IACH,UAAU,EAAE,CAAC,IAAI,EAAE,qBAAqB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1D;;;OAGG;IACH,qBAAqB,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;IACrC;;;OAGG;IACH,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;IACvC;;OAEG;IACH,aAAa,EAAE,CAAC,SAAS,EAAE,qBAAqB,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAClG,CAAA"}
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type {\n Access,\n CollectionConfig,\n DefaultDocumentIDType,\n Endpoint,\n Field,\n FieldAccess,\n GroupField,\n PayloadRequest,\n PopulateType,\n SelectType,\n TypedCollection,\n Where,\n} from 'payload'\nimport type React from 'react'\n\nimport type { TypedEcommerce } from './utilities.js'\n\nexport type FieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\nexport type CollectionOverride = (args: {\n defaultCollection: CollectionConfig\n}) => CollectionConfig | Promise<CollectionConfig>\n\nexport type CartItem = {\n id: DefaultDocumentIDType\n product: DefaultDocumentIDType | TypedCollection['products']\n quantity: number\n variant?: DefaultDocumentIDType | TypedCollection['variants']\n}\n\ntype DefaultCartType = {\n currency?: string\n customer?: DefaultDocumentIDType | TypedCollection['customers']\n id: DefaultDocumentIDType\n items: CartItem[]\n subtotal?: number\n}\n\nexport type Cart = DefaultCartType\n\ntype InitiatePaymentReturnType = {\n /**\n * Allows for additional data to be returned, such as payment method specific data\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n message: string\n}\n\ntype InitiatePayment = (args: {\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n data: {\n /**\n * Billing address for the payment.\n */\n billingAddress: TypedCollection['addresses']\n /**\n * Cart items.\n */\n cart: Cart\n /**\n * Currency code to use for the payment.\n */\n currency: string\n customerEmail: string\n /**\n * Shipping address for the payment.\n */\n shippingAddress?: TypedCollection['addresses']\n }\n req: PayloadRequest\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n * For example, this is used to create a record of the payment intent in the transactions collection.\n */\n transactionsSlug: string\n}) => InitiatePaymentReturnType | Promise<InitiatePaymentReturnType>\n\ntype ConfirmOrderReturnType = {\n /**\n * Allows for additional data to be returned, such as payment method specific data\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n message: string\n orderID: DefaultDocumentIDType\n transactionID: DefaultDocumentIDType\n}\n\ntype ConfirmOrder = (args: {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n * For example, this is used to retrieve the cart for the order.\n */\n cartsSlug?: string\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Data made available to the payment method when confirming an order. You should get the cart items from the transaction.\n */\n data: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any // Allows for additional data to be passed through, such as payment method specific data\n customerEmail?: string\n }\n /**\n * The slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n req: PayloadRequest\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n * For example, this is used to create a record of the payment intent in the transactions collection.\n */\n transactionsSlug?: string\n}) => ConfirmOrderReturnType | Promise<ConfirmOrderReturnType>\n\n/**\n * The full payment adapter config expected as part of the config for the Ecommerce plugin.\n *\n * You can insert this type directly or return it from a function constructing it.\n */\nexport type PaymentAdapter = {\n /**\n * The function that is called via the `/api/payments/{provider_name}/confirm-order` endpoint to confirm an order after a payment has been made.\n *\n * You should handle the order confirmation logic here.\n *\n * @example\n *\n * ```ts\n * const confirmOrder: ConfirmOrder = async ({ data: { customerEmail }, ordersSlug, req, transactionsSlug }) => {\n // Confirm the payment with Stripe or another payment provider here\n // Create an order in the orders collection here\n // Update the record of the payment intent in the transactions collection here\n return {\n message: 'Order confirmed successfully',\n orderID: 'order_123',\n transactionID: 'txn_123',\n // Include any additional data required for the payment method here\n }\n }\n * ```\n */\n confirmOrder: ConfirmOrder\n /**\n * An array of endpoints to be bootstrapped to Payload's API in order to support the payment method. All API paths are relative to `/api/payments/{provider_name}`.\n *\n * So for example, path `/webhooks` in the Stripe adapter becomes `/api/payments/stripe/webhooks`.\n *\n * @example '/webhooks'\n */\n endpoints?: Endpoint[]\n /**\n * A group configuration to be used in the admin interface to display the payment method.\n *\n * @example\n *\n * ```ts\n * const groupField: GroupField = {\n name: 'stripe',\n type: 'group',\n admin: {\n condition: (data) => data?.paymentMethod === 'stripe',\n },\n fields: [\n {\n name: 'stripeCustomerID',\n type: 'text',\n label: 'Stripe Customer ID',\n required: true,\n },\n {\n name: 'stripePaymentIntentID',\n type: 'text',\n label: 'Stripe PaymentIntent ID',\n required: true,\n },\n ],\n }\n * ```\n */\n group: GroupField\n /**\n * The function that is called via the `/api/payments/{provider_name}/initiate` endpoint to initiate a payment for an order.\n *\n * You should handle the payment initiation logic here.\n *\n * @example\n *\n * ```ts\n * const initiatePayment: InitiatePayment = async ({ data: { cart, currency, customerEmail, billingAddress, shippingAddress }, req, transactionsSlug }) => {\n // Create a payment intent with Stripe or another payment provider here\n // Create a record of the payment intent in the transactions collection here\n return {\n message: 'Payment initiated successfully',\n // Include any additional data required for the payment method here\n }\n }\n * ```\n */\n initiatePayment: InitiatePayment\n /**\n * The label of the payment method\n * @example\n * 'Bank Transfer'\n */\n label?: string\n /**\n * The name of the payment method\n * @example 'stripe'\n */\n name: string\n}\n\nexport type PaymentAdapterClient = {\n confirmOrder: boolean\n initiatePayment: boolean\n} & Pick<PaymentAdapter, 'label' | 'name'>\n\nexport type Currency = {\n /**\n * The ISO 4217 currency code\n * @example 'usd'\n */\n code: string\n /**\n * The number of decimal places the currency uses\n * @example 2\n */\n decimals: number\n /**\n * A user friendly name for the currency.\n *\n * @example 'US Dollar'\n */\n label: string\n /**\n * The symbol of the currency\n * @example '$'\n */\n symbol: string\n}\n\n/**\n * Commonly used arguments for a Payment Adapter function, it's use is entirely optional.\n */\nexport type PaymentAdapterArgs = {\n /**\n * Overrides the default fields of the collection. Affects the payment fields on collections such as transactions.\n */\n groupOverrides?: { fields?: FieldsOverride } & Partial<Omit<GroupField, 'fields'>>\n /**\n * The visually readable label for the payment method.\n * @example 'Bank Transfer'\n */\n label?: string\n}\n\n/**\n * Commonly used arguments for a Payment Adapter function, it's use is entirely optional.\n */\nexport type PaymentAdapterClientArgs = {\n /**\n * The visually readable label for the payment method.\n * @example 'Bank Transfer'\n */\n label?: string\n}\n\nexport type VariantsConfig = {\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantOptionsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantOptionsCollectionOverride?: CollectionOverride\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantsCollectionOverride?: CollectionOverride\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantTypesCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantTypesCollectionOverride?: CollectionOverride\n}\n\nexport type ProductsConfig = {\n /**\n * Override the default products collection. If you override the collection, you should ensure it has the required fields for products or re-use the default fields.\n *\n * @example\n *\n * ```ts\n products: {\n productsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n productsCollectionOverride?: CollectionOverride\n /**\n * Customise the validation used for checking products or variants before a transaction is created or a payment can be confirmed.\n */\n validation?: ProductsValidation\n /**\n * Enable variants and provide configuration for the variant collections.\n *\n * Defaults to true.\n */\n variants?: boolean | VariantsConfig\n}\n\nexport type OrdersConfig = {\n /**\n * Override the default orders collection. If you override the collection, you should ensure it has the required fields for orders or re-use the default fields.\n *\n * @example\n *\n * ```ts\n orders: {\n ordersCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n ordersCollectionOverride?: CollectionOverride\n}\n\nexport type TransactionsConfig = {\n /**\n * Override the default transactions collection. If you override the collection, you should ensure it has the required fields for transactions or re-use the default fields.\n *\n * @example\n *\n * ```ts\n transactions: {\n transactionsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n transactionsCollectionOverride?: CollectionOverride\n}\n\nexport type CustomQuery = {\n depth?: number\n select?: SelectType\n where?: Where\n}\n\nexport type PaymentsConfig = {\n paymentMethods?: PaymentAdapter[]\n productsQuery?: CustomQuery\n variantsQuery?: CustomQuery\n}\n\nexport type CountryType = {\n /**\n * A user friendly name for the country.\n */\n label: string\n /**\n * The ISO 3166-1 alpha-2 country code.\n * @example 'US'\n */\n value: string\n}\n\n/**\n * Configuration for the addresses used by the Ecommerce plugin. Use this to override the default collection or fields used throughout\n */\ntype AddressesConfig = {\n /**\n * Override the default addresses collection. If you override the collection, you should ensure it has the required fields for addresses or re-use the default fields.\n *\n * @example\n * ```ts\n * addressesCollectionOverride: (defaultCollection) => {\n * return {\n * ...defaultCollection,\n * fields: [\n * ...defaultCollection.fields,\n * // add custom fields here\n * ],\n * }\n * }\n * ```\n */\n addressesCollectionOverride?: CollectionOverride\n /**\n * These fields will be applied to all locations where addresses are used, such as Orders and Transactions. Preferred use over the collectionOverride config.\n */\n addressFields?: FieldsOverride\n /**\n * Provide an array of countries to support for addresses. This will be used in the admin interface to provide a select field of countries.\n *\n * Defaults to a set of commonly used countries.\n *\n * @example\n * ```\n * [\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ]\n */\n supportedCountries?: CountryType[]\n}\n\nexport type CustomersConfig = {\n /**\n * Slug of the customers collection, defaults to 'users'.\n * This is used to link carts and orders to customers.\n */\n slug: string\n}\n\nexport type CartsConfig = {\n /**\n * Allow guest (unauthenticated) users to create carts.\n * When enabled, guests can create carts without being logged in.\n * Defaults to true.\n */\n allowGuestCarts?: boolean\n cartsCollectionOverride?: CollectionOverride\n}\n\nexport type InventoryConfig = {\n /**\n * Override the default field used to track inventory levels. Defaults to 'inventory'.\n */\n fieldName?: string\n}\n\nexport type CurrenciesConfig = {\n /**\n * Defaults to the first supported currency.\n *\n * @example 'USD'\n */\n defaultCurrency: string\n /**\n *\n */\n supportedCurrencies: Currency[]\n}\n\n/**\n * A function that validates a product or variant before a transaction is created or completed.\n * This should throw an error if validation fails as it will be caught by the function calling it.\n */\nexport type ProductsValidation = (args: {\n /**\n * The full currencies config, allowing you to check against supported currencies and their settings.\n */\n currenciesConfig?: CurrenciesConfig\n /**\n * The ISO 4217 currency code being usen in this transaction.\n */\n currency?: string\n /**\n * The full product data.\n */\n product: TypedCollection['products']\n /**\n * Quantity to check the inventory amount against.\n */\n quantity: number\n /**\n * The full variant data, if a variant was selected for the product otherwise it will be undefined.\n */\n variant?: TypedCollection['variants']\n}) => Promise<void> | void\n\n/**\n * A map of collection slugs used by the Ecommerce plugin.\n * Provides an easy way to track the slugs of collections even when they are overridden.\n */\nexport type CollectionSlugMap = {\n addresses: string\n carts: string\n customers: string\n orders: string\n products: string\n transactions: string\n variantOptions: string\n variants: string\n variantTypes: string\n}\n\n/**\n * Access control functions used throughout the Ecommerce plugin.\n * Provide atomic access functions that can be composed using or, and, conditional utilities.\n *\n * @example\n * ```ts\n * access: {\n * isAdmin: ({ req }) => checkRole(['admin'], req.user),\n * isAuthenticated: ({ req }) => !!req.user,\n * isDocumentOwner: ({ req }) => {\n * if (!req.user) return false\n * return { customer: { equals: req.user.id } }\n * },\n * adminOnlyFieldAccess: ({ req }) => checkRole(['admin'], req.user),\n * customerOnlyFieldAccess: ({ req }) => !!req.user,\n * adminOrPublishedStatus: ({ req }) => {\n * if (checkRole(['admin'], req.user)) return true\n * return { _status: { equals: 'published' } }\n * },\n * }\n * ```\n */\nexport type AccessConfig = {\n /**\n * Limited to only admin users, specifically for Field level access control.\n */\n adminOnlyFieldAccess: FieldAccess\n /**\n * The document status is published or user is admin.\n */\n adminOrPublishedStatus: Access\n /**\n * Limited to customers only, specifically for Field level access control.\n */\n customerOnlyFieldAccess: FieldAccess\n /**\n * Checks if the user is an admin.\n * @returns true if admin, false otherwise\n */\n isAdmin: Access\n /**\n * Checks if the user is authenticated (any role).\n * @returns true if authenticated, false otherwise\n */\n isAuthenticated?: Access\n /**\n * Checks if the user owns the document being accessed.\n * Typically returns a Where query to filter by customer field.\n * @returns true for full access, false for no access, or Where query for conditional access\n */\n isDocumentOwner: Access\n /**\n * Entirely public access. Defaults to returning true.\n *\n * @example\n * publicAccess: () => true\n */\n publicAccess?: Access\n}\n\nexport type EcommercePluginConfig = {\n /**\n * Customise the access control for the plugin.\n *\n * @example\n * ```ts\n * ```\n */\n access: AccessConfig\n /**\n * Enable the addresses collection to allow customers, transactions and orders to have multiple addresses for shipping and billing. Accepts an override to customise the addresses collection.\n * Defaults to supporting a default set of countries.\n */\n addresses?: AddressesConfig | boolean\n /**\n * Configure the target collection used for carts.\n *\n * Defaults to true.\n */\n carts?: boolean | CartsConfig\n /**\n * Configure supported currencies and default settings.\n *\n * Defaults to supporting USD.\n */\n currencies?: CurrenciesConfig\n /**\n * Configure the target collection used for customers.\n *\n * @example\n * ```ts\n * customers: {\n * slug: 'users', // default\n * }\n *\n */\n customers: CustomersConfig\n /**\n * Enable tracking of inventory for products and variants. Accepts a config object to override the default collection settings.\n *\n * Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Enables orders and accepts a config object to override the default collection settings.\n *\n * Defaults to true.\n */\n orders?: boolean | OrdersConfig\n /**\n * Enable tracking of payments. Accepts a config object to override the default collection settings.\n *\n * Defaults to true when the paymentMethods array is provided.\n */\n payments?: PaymentsConfig\n /**\n * Enables products and variants. Accepts a config object to override the product collection and each variant collection type.\n *\n * Defaults to true.\n */\n products?: boolean | ProductsConfig\n /**\n * Override the default slugs used across the plugin. This lets the plugin know which slugs to use for various internal operations and fields.\n */\n slugMap?: Partial<CollectionSlugMap>\n /**\n * Enable tracking of transactions. Accepts a config object to override the default collection settings.\n *\n * Defaults to true when the paymentMethods array is provided.\n */\n transactions?: boolean | TransactionsConfig\n}\n\nexport type SanitizedEcommercePluginConfig = {\n access: Required<AccessConfig>\n addresses: { addressFields: Field[] } & Omit<AddressesConfig, 'addressFields'>\n currencies: Required<CurrenciesConfig>\n inventory?: InventoryConfig\n payments: {\n paymentMethods: [] | PaymentAdapter[]\n }\n} & Omit<\n Required<EcommercePluginConfig>,\n 'access' | 'addresses' | 'currencies' | 'inventory' | 'payments'\n>\n\nexport type EcommerceCollections = TypedEcommerce['collections']\n\nexport type AddressesCollection = EcommerceCollections['addresses']\nexport type CartsCollection = EcommerceCollections['carts']\n\nexport type SyncLocalStorageConfig = {\n /**\n * Key to use for localStorage.\n * Defaults to 'cart'.\n */\n key?: string\n}\n\ntype APIProps = {\n /**\n * The route for the Payload API, defaults to `/api`.\n */\n apiRoute?: string\n /**\n * Customise the query used to fetch carts. Use this when you need to fetch additional data and optimise queries using depth, select and populate.\n *\n * Defaults to `{ depth: 0 }`.\n */\n cartsFetchQuery?: {\n depth?: number\n populate?: PopulateType\n select?: SelectType\n }\n /**\n * The route for the Payload API, defaults to ``. Eg for a Payload app running on `http://localhost:3000`, the default serverURL would be `http://localhost:3000`.\n */\n serverURL?: string\n}\n\nexport type ContextProps = {\n /**\n * The slug for the addresses collection.\n *\n * Defaults to 'addresses'.\n */\n addressesSlug?: string\n api?: APIProps\n /**\n * The slug for the carts collection.\n *\n * Defaults to 'carts'.\n */\n cartsSlug?: string\n children?: React.ReactNode\n /**\n * The configuration for currencies used in the ecommerce context.\n * This is used to handle currency formatting and calculations, defaults to USD.\n */\n currenciesConfig?: CurrenciesConfig\n /**\n * The slug for the customers collection.\n *\n * Defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enable debug mode for the ecommerce context. This will log additional information to the console.\n * Defaults to false.\n */\n debug?: boolean\n /**\n * Whether to enable support for variants in the cart.\n * This allows adding products with specific variants to the cart.\n * Defaults to false.\n */\n enableVariants?: boolean\n /**\n * Supported payment methods for the ecommerce context.\n */\n paymentMethods?: PaymentAdapterClient[]\n /**\n * Whether to enable localStorage for cart persistence.\n * Defaults to true.\n */\n syncLocalStorage?: boolean | SyncLocalStorageConfig\n}\n\n/**\n * Type used internally to represent the cart item to be added.\n */\ntype CartItemArgument = {\n /**\n * The ID of the product to add to the cart. Always required.\n */\n product: DefaultDocumentIDType\n /**\n * The ID of the variant to add to the cart. Optional, if not provided, the product will be added without a variant.\n */\n variant?: DefaultDocumentIDType\n}\n\nexport type EcommerceContextType<T extends EcommerceCollections = EcommerceCollections> = {\n /**\n * Add an item to the cart.\n */\n addItem: (item: CartItemArgument, quantity?: number) => Promise<void>\n /**\n * All current addresses for the current user.\n * This is used to manage shipping and billing addresses.\n */\n addresses?: T['addresses'][]\n /**\n * The current data of the cart.\n */\n cart?: T['addresses']\n /**\n * The ID of the current cart corresponding to the cart in the database or local storage.\n */\n cartID?: DefaultDocumentIDType\n /**\n * Clear the cart, removing all items.\n */\n clearCart: () => Promise<void>\n /**\n * Initiate a payment using the selected payment method.\n * This method should be called after the cart is ready for checkout.\n * It requires the payment method ID and any necessary payment data.\n */\n confirmOrder: (\n paymentMethodID: string,\n options?: { additionalData: Record<string, unknown> },\n ) => Promise<unknown>\n /**\n * Create a new address by providing the data.\n */\n createAddress: (data: Partial<T['addresses']>) => Promise<void>\n /**\n * The configuration for the currencies used in the ecommerce context.\n */\n currenciesConfig: CurrenciesConfig\n /**\n * The currently selected currency used for the cart and price formatting automatically.\n */\n currency: Currency\n /**\n * Decrement an item in the cart by its index ID.\n * If quantity reaches 0, the item will be removed from the cart.\n */\n decrementItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * Increment an item in the cart by its index ID.\n */\n incrementItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * Initiate a payment using the selected payment method.\n * This method should be called after the cart is ready for checkout.\n * It requires the payment method ID and any necessary payment data.\n */\n initiatePayment: (\n paymentMethodID: string,\n options?: { additionalData: Record<string, unknown> },\n ) => Promise<unknown>\n /**\n * Indicates whether any cart operation is currently in progress.\n * Useful for disabling buttons and preventing race conditions.\n */\n isLoading: boolean\n paymentMethods: PaymentAdapterClient[]\n /**\n * Remove an item from the cart by its index ID.\n */\n removeItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * The name of the currently selected payment method.\n * This is used to determine which payment method to use when initiating a payment.\n */\n selectedPaymentMethod?: null | string\n /**\n * Change the currency for the cart, it defaults to the configured currency.\n * This will update the currency used for pricing and calculations.\n */\n setCurrency: (currency: string) => void\n /**\n * Update an address by providing the data and the ID.\n */\n updateAddress: (addressID: DefaultDocumentIDType, data: Partial<T['addresses']>) => Promise<void>\n}\n"],"names":[],"mappings":"AAizBA,WAqFC"}
|
|
1
|
+
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type {\n Access,\n CollectionConfig,\n DefaultDocumentIDType,\n Endpoint,\n Field,\n FieldAccess,\n GroupField,\n PayloadRequest,\n PopulateType,\n SelectType,\n TypedCollection,\n Where,\n} from 'payload'\nimport type React from 'react'\n\nimport type { TypedEcommerce } from './utilities.js'\n\nexport type FieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\nexport type CollectionOverride = (args: {\n defaultCollection: CollectionConfig\n}) => CollectionConfig | Promise<CollectionConfig>\n\nexport type CartItem = {\n id: DefaultDocumentIDType\n product: DefaultDocumentIDType | TypedCollection['products']\n quantity: number\n variant?: DefaultDocumentIDType | TypedCollection['variants']\n}\n\ntype DefaultCartType = {\n currency?: string\n customer?: DefaultDocumentIDType | TypedCollection['customers']\n id: DefaultDocumentIDType\n items: CartItem[]\n subtotal?: number\n}\n\nexport type Cart = DefaultCartType\n\ntype InitiatePaymentReturnType = {\n /**\n * Allows for additional data to be returned, such as payment method specific data\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n message: string\n}\n\ntype InitiatePayment = (args: {\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n data: {\n /**\n * Billing address for the payment.\n */\n billingAddress: TypedCollection['addresses']\n /**\n * Cart items.\n */\n cart: Cart\n /**\n * Currency code to use for the payment.\n */\n currency: string\n customerEmail: string\n /**\n * Shipping address for the payment.\n */\n shippingAddress?: TypedCollection['addresses']\n }\n req: PayloadRequest\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n * For example, this is used to create a record of the payment intent in the transactions collection.\n */\n transactionsSlug: string\n}) => InitiatePaymentReturnType | Promise<InitiatePaymentReturnType>\n\ntype ConfirmOrderReturnType = {\n /**\n * Allows for additional data to be returned, such as payment method specific data\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n message: string\n orderID: DefaultDocumentIDType\n transactionID: DefaultDocumentIDType\n}\n\ntype ConfirmOrder = (args: {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n * For example, this is used to retrieve the cart for the order.\n */\n cartsSlug?: string\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Data made available to the payment method when confirming an order. You should get the cart items from the transaction.\n */\n data: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any // Allows for additional data to be passed through, such as payment method specific data\n customerEmail?: string\n }\n /**\n * The slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n req: PayloadRequest\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n * For example, this is used to create a record of the payment intent in the transactions collection.\n */\n transactionsSlug?: string\n}) => ConfirmOrderReturnType | Promise<ConfirmOrderReturnType>\n\n/**\n * The full payment adapter config expected as part of the config for the Ecommerce plugin.\n *\n * You can insert this type directly or return it from a function constructing it.\n */\nexport type PaymentAdapter = {\n /**\n * The function that is called via the `/api/payments/{provider_name}/confirm-order` endpoint to confirm an order after a payment has been made.\n *\n * You should handle the order confirmation logic here.\n *\n * @example\n *\n * ```ts\n * const confirmOrder: ConfirmOrder = async ({ data: { customerEmail }, ordersSlug, req, transactionsSlug }) => {\n // Confirm the payment with Stripe or another payment provider here\n // Create an order in the orders collection here\n // Update the record of the payment intent in the transactions collection here\n return {\n message: 'Order confirmed successfully',\n orderID: 'order_123',\n transactionID: 'txn_123',\n // Include any additional data required for the payment method here\n }\n }\n * ```\n */\n confirmOrder: ConfirmOrder\n /**\n * An array of endpoints to be bootstrapped to Payload's API in order to support the payment method. All API paths are relative to `/api/payments/{provider_name}`.\n *\n * So for example, path `/webhooks` in the Stripe adapter becomes `/api/payments/stripe/webhooks`.\n *\n * @example '/webhooks'\n */\n endpoints?: Endpoint[]\n /**\n * A group configuration to be used in the admin interface to display the payment method.\n *\n * @example\n *\n * ```ts\n * const groupField: GroupField = {\n name: 'stripe',\n type: 'group',\n admin: {\n condition: (data) => data?.paymentMethod === 'stripe',\n },\n fields: [\n {\n name: 'stripeCustomerID',\n type: 'text',\n label: 'Stripe Customer ID',\n required: true,\n },\n {\n name: 'stripePaymentIntentID',\n type: 'text',\n label: 'Stripe PaymentIntent ID',\n required: true,\n },\n ],\n }\n * ```\n */\n group: GroupField\n /**\n * The function that is called via the `/api/payments/{provider_name}/initiate` endpoint to initiate a payment for an order.\n *\n * You should handle the payment initiation logic here.\n *\n * @example\n *\n * ```ts\n * const initiatePayment: InitiatePayment = async ({ data: { cart, currency, customerEmail, billingAddress, shippingAddress }, req, transactionsSlug }) => {\n // Create a payment intent with Stripe or another payment provider here\n // Create a record of the payment intent in the transactions collection here\n return {\n message: 'Payment initiated successfully',\n // Include any additional data required for the payment method here\n }\n }\n * ```\n */\n initiatePayment: InitiatePayment\n /**\n * The label of the payment method\n * @example\n * 'Bank Transfer'\n */\n label?: string\n /**\n * The name of the payment method\n * @example 'stripe'\n */\n name: string\n}\n\nexport type PaymentAdapterClient = {\n confirmOrder: boolean\n initiatePayment: boolean\n} & Pick<PaymentAdapter, 'label' | 'name'>\n\nexport type Currency = {\n /**\n * The ISO 4217 currency code\n * @example 'usd'\n */\n code: string\n /**\n * The number of decimal places the currency uses\n * @example 2\n */\n decimals: number\n /**\n * A user friendly name for the currency.\n *\n * @example 'US Dollar'\n */\n label: string\n /**\n * The symbol of the currency\n * @example '$'\n */\n symbol: string\n}\n\n/**\n * Commonly used arguments for a Payment Adapter function, it's use is entirely optional.\n */\nexport type PaymentAdapterArgs = {\n /**\n * Overrides the default fields of the collection. Affects the payment fields on collections such as transactions.\n */\n groupOverrides?: { fields?: FieldsOverride } & Partial<Omit<GroupField, 'fields'>>\n /**\n * The visually readable label for the payment method.\n * @example 'Bank Transfer'\n */\n label?: string\n}\n\n/**\n * Commonly used arguments for a Payment Adapter function, it's use is entirely optional.\n */\nexport type PaymentAdapterClientArgs = {\n /**\n * The visually readable label for the payment method.\n * @example 'Bank Transfer'\n */\n label?: string\n}\n\nexport type VariantsConfig = {\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantOptionsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantOptionsCollectionOverride?: CollectionOverride\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantsCollectionOverride?: CollectionOverride\n /**\n * Override the default variants collection. If you override the collection, you should ensure it has the required fields for variants or re-use the default fields.\n *\n * @example\n *\n * ```ts\n * variants: {\n variantTypesCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'customField',\n label: 'Custom Field',\n type: 'text',\n },\n ],\n })\n }\n ```\n */\n variantTypesCollectionOverride?: CollectionOverride\n}\n\nexport type ProductsConfig = {\n /**\n * Override the default products collection. If you override the collection, you should ensure it has the required fields for products or re-use the default fields.\n *\n * @example\n *\n * ```ts\n products: {\n productsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n productsCollectionOverride?: CollectionOverride\n /**\n * Customise the validation used for checking products or variants before a transaction is created or a payment can be confirmed.\n */\n validation?: ProductsValidation\n /**\n * Enable variants and provide configuration for the variant collections.\n *\n * Defaults to true.\n */\n variants?: boolean | VariantsConfig\n}\n\nexport type OrdersConfig = {\n /**\n * Override the default orders collection. If you override the collection, you should ensure it has the required fields for orders or re-use the default fields.\n *\n * @example\n *\n * ```ts\n orders: {\n ordersCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n ordersCollectionOverride?: CollectionOverride\n}\n\nexport type TransactionsConfig = {\n /**\n * Override the default transactions collection. If you override the collection, you should ensure it has the required fields for transactions or re-use the default fields.\n *\n * @example\n *\n * ```ts\n transactions: {\n transactionsCollectionOverride: ({ defaultCollection }) => ({\n ...defaultCollection,\n fields: [\n ...defaultCollection.fields,\n {\n name: 'notes',\n label: 'Notes',\n type: 'textarea',\n },\n ],\n })\n }\n ```\n */\n transactionsCollectionOverride?: CollectionOverride\n}\n\nexport type CustomQuery = {\n depth?: number\n select?: SelectType\n where?: Where\n}\n\nexport type PaymentsConfig = {\n paymentMethods?: PaymentAdapter[]\n productsQuery?: CustomQuery\n variantsQuery?: CustomQuery\n}\n\nexport type CountryType = {\n /**\n * A user friendly name for the country.\n */\n label: string\n /**\n * The ISO 3166-1 alpha-2 country code.\n * @example 'US'\n */\n value: string\n}\n\n/**\n * Configuration for the addresses used by the Ecommerce plugin. Use this to override the default collection or fields used throughout\n */\ntype AddressesConfig = {\n /**\n * Override the default addresses collection. If you override the collection, you should ensure it has the required fields for addresses or re-use the default fields.\n *\n * @example\n * ```ts\n * addressesCollectionOverride: (defaultCollection) => {\n * return {\n * ...defaultCollection,\n * fields: [\n * ...defaultCollection.fields,\n * // add custom fields here\n * ],\n * }\n * }\n * ```\n */\n addressesCollectionOverride?: CollectionOverride\n /**\n * These fields will be applied to all locations where addresses are used, such as Orders and Transactions. Preferred use over the collectionOverride config.\n */\n addressFields?: FieldsOverride\n /**\n * Provide an array of countries to support for addresses. This will be used in the admin interface to provide a select field of countries.\n *\n * Defaults to a set of commonly used countries.\n *\n * @example\n * ```\n * [\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ]\n */\n supportedCountries?: CountryType[]\n}\n\nexport type CustomersConfig = {\n /**\n * Slug of the customers collection, defaults to 'users'.\n * This is used to link carts and orders to customers.\n */\n slug: string\n}\n\nexport type CartsConfig = {\n /**\n * Allow guest (unauthenticated) users to create carts.\n * When enabled, guests can create carts without being logged in.\n * Defaults to true.\n */\n allowGuestCarts?: boolean\n cartsCollectionOverride?: CollectionOverride\n}\n\nexport type InventoryConfig = {\n /**\n * Override the default field used to track inventory levels. Defaults to 'inventory'.\n */\n fieldName?: string\n}\n\nexport type CurrenciesConfig = {\n /**\n * Defaults to the first supported currency.\n *\n * @example 'USD'\n */\n defaultCurrency: string\n /**\n *\n */\n supportedCurrencies: Currency[]\n}\n\n/**\n * A function that validates a product or variant before a transaction is created or completed.\n * This should throw an error if validation fails as it will be caught by the function calling it.\n */\nexport type ProductsValidation = (args: {\n /**\n * The full currencies config, allowing you to check against supported currencies and their settings.\n */\n currenciesConfig?: CurrenciesConfig\n /**\n * The ISO 4217 currency code being usen in this transaction.\n */\n currency?: string\n /**\n * The full product data.\n */\n product: TypedCollection['products']\n /**\n * Quantity to check the inventory amount against.\n */\n quantity: number\n /**\n * The full variant data, if a variant was selected for the product otherwise it will be undefined.\n */\n variant?: TypedCollection['variants']\n}) => Promise<void> | void\n\n/**\n * A map of collection slugs used by the Ecommerce plugin.\n * Provides an easy way to track the slugs of collections even when they are overridden.\n */\nexport type CollectionSlugMap = {\n addresses: string\n carts: string\n customers: string\n orders: string\n products: string\n transactions: string\n variantOptions: string\n variants: string\n variantTypes: string\n}\n\n/**\n * Access control functions used throughout the Ecommerce plugin.\n * Provide atomic access functions that can be composed using or, and, conditional utilities.\n *\n * @example\n * ```ts\n * access: {\n * isAdmin: ({ req }) => checkRole(['admin'], req.user),\n * isAuthenticated: ({ req }) => !!req.user,\n * isDocumentOwner: ({ req }) => {\n * if (!req.user) return false\n * return { customer: { equals: req.user.id } }\n * },\n * adminOnlyFieldAccess: ({ req }) => checkRole(['admin'], req.user),\n * customerOnlyFieldAccess: ({ req }) => !!req.user,\n * adminOrPublishedStatus: ({ req }) => {\n * if (checkRole(['admin'], req.user)) return true\n * return { _status: { equals: 'published' } }\n * },\n * }\n * ```\n */\nexport type AccessConfig = {\n /**\n * Limited to only admin users, specifically for Field level access control.\n */\n adminOnlyFieldAccess: FieldAccess\n /**\n * The document status is published or user is admin.\n */\n adminOrPublishedStatus: Access\n /**\n * Limited to customers only, specifically for Field level access control.\n */\n customerOnlyFieldAccess: FieldAccess\n /**\n * Checks if the user is an admin.\n * @returns true if admin, false otherwise\n */\n isAdmin: Access\n /**\n * Checks if the user is authenticated (any role).\n * @returns true if authenticated, false otherwise\n */\n isAuthenticated?: Access\n /**\n * Checks if the user owns the document being accessed.\n * Typically returns a Where query to filter by customer field.\n * @returns true for full access, false for no access, or Where query for conditional access\n */\n isDocumentOwner: Access\n /**\n * Entirely public access. Defaults to returning true.\n *\n * @example\n * publicAccess: () => true\n */\n publicAccess?: Access\n}\n\nexport type EcommercePluginConfig = {\n /**\n * Customise the access control for the plugin.\n *\n * @example\n * ```ts\n * ```\n */\n access: AccessConfig\n /**\n * Enable the addresses collection to allow customers, transactions and orders to have multiple addresses for shipping and billing. Accepts an override to customise the addresses collection.\n * Defaults to supporting a default set of countries.\n */\n addresses?: AddressesConfig | boolean\n /**\n * Configure the target collection used for carts.\n *\n * Defaults to true.\n */\n carts?: boolean | CartsConfig\n /**\n * Configure supported currencies and default settings.\n *\n * Defaults to supporting USD.\n */\n currencies?: CurrenciesConfig\n /**\n * Configure the target collection used for customers.\n *\n * @example\n * ```ts\n * customers: {\n * slug: 'users', // default\n * }\n *\n */\n customers: CustomersConfig\n /**\n * Enable tracking of inventory for products and variants. Accepts a config object to override the default collection settings.\n *\n * Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Enables orders and accepts a config object to override the default collection settings.\n *\n * Defaults to true.\n */\n orders?: boolean | OrdersConfig\n /**\n * Enable tracking of payments. Accepts a config object to override the default collection settings.\n *\n * Defaults to true when the paymentMethods array is provided.\n */\n payments?: PaymentsConfig\n /**\n * Enables products and variants. Accepts a config object to override the product collection and each variant collection type.\n *\n * Defaults to true.\n */\n products?: boolean | ProductsConfig\n /**\n * Override the default slugs used across the plugin. This lets the plugin know which slugs to use for various internal operations and fields.\n */\n slugMap?: Partial<CollectionSlugMap>\n /**\n * Enable tracking of transactions. Accepts a config object to override the default collection settings.\n *\n * Defaults to true when the paymentMethods array is provided.\n */\n transactions?: boolean | TransactionsConfig\n}\n\nexport type SanitizedEcommercePluginConfig = {\n access: Required<AccessConfig>\n addresses: { addressFields: Field[] } & Omit<AddressesConfig, 'addressFields'>\n currencies: Required<CurrenciesConfig>\n inventory?: InventoryConfig\n payments: {\n paymentMethods: [] | PaymentAdapter[]\n }\n} & Omit<\n Required<EcommercePluginConfig>,\n 'access' | 'addresses' | 'currencies' | 'inventory' | 'payments'\n>\n\nexport type EcommerceCollections = TypedEcommerce['collections']\n\nexport type AddressesCollection = EcommerceCollections['addresses']\nexport type CartsCollection = EcommerceCollections['carts']\n\nexport type SyncLocalStorageConfig = {\n /**\n * Key to use for localStorage.\n * Defaults to 'cart'.\n */\n key?: string\n}\n\ntype APIProps = {\n /**\n * The route for the Payload API, defaults to `/api`.\n */\n apiRoute?: string\n /**\n * Customise the query used to fetch carts. Use this when you need to fetch additional data and optimise queries using depth, select and populate.\n *\n * Defaults to `{ depth: 0 }`.\n */\n cartsFetchQuery?: {\n depth?: number\n populate?: PopulateType\n select?: SelectType\n }\n /**\n * The route for the Payload API, defaults to ``. Eg for a Payload app running on `http://localhost:3000`, the default serverURL would be `http://localhost:3000`.\n */\n serverURL?: string\n}\n\nexport type ContextProps = {\n /**\n * The slug for the addresses collection.\n *\n * Defaults to 'addresses'.\n */\n addressesSlug?: string\n api?: APIProps\n /**\n * The slug for the carts collection.\n *\n * Defaults to 'carts'.\n */\n cartsSlug?: string\n children?: React.ReactNode\n /**\n * The configuration for currencies used in the ecommerce context.\n * This is used to handle currency formatting and calculations, defaults to USD.\n */\n currenciesConfig?: CurrenciesConfig\n /**\n * The slug for the customers collection.\n *\n * Defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enable debug mode for the ecommerce context. This will log additional information to the console.\n * Defaults to false.\n */\n debug?: boolean\n /**\n * Whether to enable support for variants in the cart.\n * This allows adding products with specific variants to the cart.\n * Defaults to false.\n */\n enableVariants?: boolean\n /**\n * Supported payment methods for the ecommerce context.\n */\n paymentMethods?: PaymentAdapterClient[]\n /**\n * Whether to enable localStorage for cart persistence.\n * Defaults to true.\n */\n syncLocalStorage?: boolean | SyncLocalStorageConfig\n}\n\n/**\n * Type used internally to represent the cart item to be added.\n */\ntype CartItemArgument = {\n /**\n * The ID of the product to add to the cart. Always required.\n */\n product: DefaultDocumentIDType\n /**\n * The ID of the variant to add to the cart. Optional, if not provided, the product will be added without a variant.\n */\n variant?: DefaultDocumentIDType\n}\n\nexport type EcommerceContextType<T extends EcommerceCollections = EcommerceCollections> = {\n /**\n * Add an item to the cart.\n */\n addItem: (item: CartItemArgument, quantity?: number) => Promise<void>\n /**\n * All current addresses for the current user.\n * This is used to manage shipping and billing addresses.\n */\n addresses?: T['addresses'][]\n /**\n * The current data of the cart.\n */\n cart?: T['addresses']\n /**\n * The ID of the current cart corresponding to the cart in the database or local storage.\n */\n cartID?: DefaultDocumentIDType\n /**\n * Clear the cart, removing all items.\n */\n clearCart: () => Promise<void>\n /**\n * Initiate a payment using the selected payment method.\n * This method should be called after the cart is ready for checkout.\n * It requires the payment method ID and any necessary payment data.\n */\n confirmOrder: (\n paymentMethodID: string,\n options?: { additionalData: Record<string, unknown> },\n ) => Promise<unknown>\n /**\n * Create a new address by providing the data.\n */\n createAddress: (data: Partial<T['addresses']>) => Promise<void>\n /**\n * The configuration for the currencies used in the ecommerce context.\n */\n currenciesConfig: CurrenciesConfig\n /**\n * The currently selected currency used for the cart and price formatting automatically.\n */\n currency: Currency\n /**\n * Decrement an item in the cart by its index ID.\n * If quantity reaches 0, the item will be removed from the cart.\n */\n decrementItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * Increment an item in the cart by its index ID.\n */\n incrementItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * Initiate a payment using the selected payment method.\n * This method should be called after the cart is ready for checkout.\n * It requires the payment method ID and any necessary payment data.\n */\n initiatePayment: (\n paymentMethodID: string,\n options?: { additionalData: Record<string, unknown> },\n ) => Promise<unknown>\n /**\n * Indicates whether any cart operation is currently in progress.\n * Useful for disabling buttons and preventing race conditions.\n */\n isLoading: boolean\n paymentMethods: PaymentAdapterClient[]\n /**\n * Refresh the cart.\n */\n refreshCart: () => Promise<void>\n /**\n * Remove an item from the cart by its index ID.\n */\n removeItem: (item: DefaultDocumentIDType) => Promise<void>\n /**\n * The name of the currently selected payment method.\n * This is used to determine which payment method to use when initiating a payment.\n */\n selectedPaymentMethod?: null | string\n /**\n * Change the currency for the cart, it defaults to the configured currency.\n * This will update the currency used for pricing and calculations.\n */\n setCurrency: (currency: string) => void\n /**\n * Update an address by providing the data and the ID.\n */\n updateAddress: (addressID: DefaultDocumentIDType, data: Partial<T['addresses']>) => Promise<void>\n}\n"],"names":[],"mappings":"AAizBA,WAyFC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-ecommerce",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.71.0-internal-debug.80dab4c",
|
|
4
4
|
"description": "Ecommerce plugin for Payload",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload",
|
|
@@ -69,8 +69,8 @@
|
|
|
69
69
|
],
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"qs-esm": "7.0.2",
|
|
72
|
-
"@payloadcms/translations": "3.
|
|
73
|
-
"@payloadcms/ui": "3.
|
|
72
|
+
"@payloadcms/translations": "3.71.0-internal-debug.80dab4c",
|
|
73
|
+
"@payloadcms/ui": "3.71.0-internal-debug.80dab4c"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"@types/json-schema": "7.0.15",
|
|
@@ -78,13 +78,13 @@
|
|
|
78
78
|
"@types/react-dom": "19.2.1",
|
|
79
79
|
"stripe": "18.3.0",
|
|
80
80
|
"@payloadcms/eslint-config": "3.28.0",
|
|
81
|
-
"payload": "3.
|
|
82
|
-
"@payloadcms/next": "3.
|
|
81
|
+
"payload": "3.71.0-internal-debug.80dab4c",
|
|
82
|
+
"@payloadcms/next": "3.71.0-internal-debug.80dab4c"
|
|
83
83
|
},
|
|
84
84
|
"peerDependencies": {
|
|
85
85
|
"react": "^19.0.1 || ^19.1.2 || ^19.2.1",
|
|
86
86
|
"react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1",
|
|
87
|
-
"payload": "3.
|
|
87
|
+
"payload": "3.71.0-internal-debug.80dab4c"
|
|
88
88
|
},
|
|
89
89
|
"publishConfig": {
|
|
90
90
|
"registry": "https://registry.npmjs.org/"
|