@payloadcms/plugin-ecommerce 3.67.0-internal.87c53da → 3.67.0
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/collections/addresses/createAddressesCollection.d.ts +1 -5
- package/dist/collections/addresses/createAddressesCollection.d.ts.map +1 -1
- package/dist/collections/addresses/createAddressesCollection.js +7 -6
- package/dist/collections/addresses/createAddressesCollection.js.map +1 -1
- package/dist/collections/carts/beforeChange.d.ts.map +1 -1
- package/dist/collections/carts/beforeChange.js +13 -1
- package/dist/collections/carts/beforeChange.js.map +1 -1
- package/dist/collections/carts/createCartsCollection.d.ts +6 -4
- package/dist/collections/carts/createCartsCollection.d.ts.map +1 -1
- package/dist/collections/carts/createCartsCollection.js +36 -5
- package/dist/collections/carts/createCartsCollection.js.map +1 -1
- package/dist/collections/carts/hasCartSecretAccess.d.ts +10 -0
- package/dist/collections/carts/hasCartSecretAccess.d.ts.map +1 -0
- package/dist/collections/carts/hasCartSecretAccess.js +24 -0
- package/dist/collections/carts/hasCartSecretAccess.js.map +1 -0
- package/dist/collections/orders/createOrdersCollection.d.ts +1 -5
- package/dist/collections/orders/createOrdersCollection.d.ts.map +1 -1
- package/dist/collections/orders/createOrdersCollection.js +9 -8
- package/dist/collections/orders/createOrdersCollection.js.map +1 -1
- package/dist/collections/products/createProductsCollection.d.ts +1 -4
- package/dist/collections/products/createProductsCollection.d.ts.map +1 -1
- package/dist/collections/products/createProductsCollection.js +5 -5
- package/dist/collections/products/createProductsCollection.js.map +1 -1
- package/dist/collections/transactions/createTransactionsCollection.d.ts +1 -3
- package/dist/collections/transactions/createTransactionsCollection.d.ts.map +1 -1
- package/dist/collections/transactions/createTransactionsCollection.js +5 -5
- package/dist/collections/transactions/createTransactionsCollection.js.map +1 -1
- package/dist/collections/variants/createVariantOptionsCollection.d.ts +1 -4
- package/dist/collections/variants/createVariantOptionsCollection.d.ts.map +1 -1
- package/dist/collections/variants/createVariantOptionsCollection.js +5 -5
- package/dist/collections/variants/createVariantOptionsCollection.js.map +1 -1
- package/dist/collections/variants/createVariantTypesCollection.d.ts +1 -4
- package/dist/collections/variants/createVariantTypesCollection.d.ts.map +1 -1
- package/dist/collections/variants/createVariantTypesCollection.js +5 -5
- package/dist/collections/variants/createVariantTypesCollection.js.map +1 -1
- package/dist/collections/variants/createVariantsCollection/index.d.ts +1 -4
- package/dist/collections/variants/createVariantsCollection/index.d.ts.map +1 -1
- package/dist/collections/variants/createVariantsCollection/index.js +5 -5
- package/dist/collections/variants/createVariantsCollection/index.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -33
- package/dist/index.js.map +1 -1
- package/dist/react/provider/index.d.ts +3 -0
- package/dist/react/provider/index.d.ts.map +1 -1
- package/dist/react/provider/index.js +261 -156
- package/dist/react/provider/index.js.map +1 -1
- package/dist/translations/en.d.ts.map +1 -1
- package/dist/translations/en.js +1 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/types/index.d.ts +43 -25
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utilities/accessComposition.d.ts +55 -0
- package/dist/utilities/accessComposition.d.ts.map +1 -0
- package/dist/utilities/accessComposition.js +103 -0
- package/dist/utilities/accessComposition.js.map +1 -0
- package/dist/utilities/accessComposition.spec.js +803 -0
- package/dist/utilities/accessComposition.spec.js.map +1 -0
- package/dist/utilities/defaultProductsValidation.spec.js +383 -0
- package/dist/utilities/defaultProductsValidation.spec.js.map +1 -0
- package/dist/utilities/getCollectionSlugMap.spec.js +159 -0
- package/dist/utilities/getCollectionSlugMap.spec.js.map +1 -0
- package/dist/utilities/sanitizePluginConfig.d.ts.map +1 -1
- package/dist/utilities/sanitizePluginConfig.js +10 -2
- package/dist/utilities/sanitizePluginConfig.js.map +1 -1
- package/dist/utilities/sanitizePluginConfig.spec.js +515 -0
- package/dist/utilities/sanitizePluginConfig.spec.js.map +1 -0
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, { createContext, use, useCallback, useEffect, useMemo, useRef, useState } 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 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 = {}, serverURL = '' } = api || {}\n const baseAPIURL = `${serverURL}${apiRoute}`\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 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 return data.doc as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug, selectedCurrency.code, user?.id],\n )\n\n const getCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n const query = qs.stringify(cartQuery)\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 if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch cart: ${errorText}`)\n }\n const data = await response.json()\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 const query = qs.stringify(cartQuery)\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],\n )\n\n const deleteCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}`, {\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 update cart: ${errorText}`)\n }\n\n setCart(undefined)\n setCartID(undefined)\n },\n [baseAPIURL, cartsSlug],\n )\n\n useEffect(() => {\n if (hasRendered.current) {\n if (syncLocalStorage && cartID) {\n localStorage.setItem(localStorageConfig.key, cartID as string)\n }\n }\n }, [cartID, localStorageConfig.key, syncLocalStorage])\n\n const addItem: EcommerceContextType['addItem'] = useCallback(\n async (item, quantity = 1) => {\n if (cartID) {\n const existingCart = await getCart(cartID)\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 },\n [cartID, createCart, getCart, updateCart],\n )\n\n const removeItem: EcommerceContextType['removeItem'] = useCallback(\n async (targetID) => {\n if (!cartID) {\n return\n }\n\n const existingCart = await getCart(cartID)\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\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) => 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 },\n [cartID, getCart, updateCart],\n )\n\n const incrementItem: EcommerceContextType['incrementItem'] = useCallback(\n async (targetID) => {\n if (!cartID) {\n return\n }\n\n const existingCart = await getCart(cartID)\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\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) => 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 },\n [cartID, getCart, updateCart],\n )\n\n const decrementItem: EcommerceContextType['decrementItem'] = useCallback(\n async (targetID) => {\n if (!cartID) {\n return\n }\n\n const existingCart = await getCart(cartID)\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\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) => 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 },\n [cartID, getCart, updateCart],\n )\n\n const clearCart: EcommerceContextType['clearCart'] = useCallback(async () => {\n if (cartID) {\n await deleteCart(cartID)\n }\n }, [cartID, deleteCart])\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, we can add logic to persist the cart state\n useEffect(() => {\n if (!hasRendered.current) {\n if (syncLocalStorage) {\n const storedCart = localStorage.getItem(localStorageConfig.key)\n if (storedCart) {\n getCart(storedCart)\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(storedCart as DefaultDocumentIDType)\n })\n .catch((_) => {\n // console.error('Error fetching cart from localStorage:', error)\n // If there's an error fetching the cart, we can clear it from localStorage\n localStorage.removeItem(localStorageConfig.key)\n setCartID(undefined)\n setCart(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 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, removeItem } = useEcommerce()\n\n if (!addItem) {\n throw new Error('useCart must be used within an EcommerceProvider')\n }\n\n return { addItem, cart: cart as T, clearCart, decrementItem, incrementItem, removeItem }\n}\n\nexport const usePayments = () => {\n const { confirmOrder, initiatePayment, paymentMethods, selectedPaymentMethod } = useEcommerce()\n\n if (!initiatePayment) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { confirmOrder, initiatePayment, paymentMethods, selectedPaymentMethod }\n}\n\nexport function useAddresses<T extends AddressesCollection>() {\n const { addresses, createAddress, 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, updateAddress }\n}\n"],"names":["deepMergeSimple","qs","React","createContext","use","useCallback","useEffect","useMemo","useRef","useState","defaultContext","addItem","clearCart","confirmOrder","createAddress","currenciesConfig","defaultCurrency","supportedCurrencies","code","decimals","label","symbol","currency","decrementItem","incrementItem","initiatePayment","paymentMethods","removeItem","setCurrency","updateAddress","EcommerceContext","defaultLocalStorage","key","EcommerceProvider","addressesSlug","api","cartsSlug","children","customersSlug","debug","syncLocalStorage","localStorageConfig","apiRoute","cartsFetchQuery","serverURL","baseAPIURL","user","setUser","addresses","setAddresses","hasRendered","cartID","setCartID","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","getCart","updateCart","updatedCart","deleteCart","undefined","current","localStorage","setItem","item","quantity","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","storedCart","getItem","then","fetchedCart","catch","_","value","useEcommerce","context","useCurrency","formatCurrency","currencyToUse","toString","repeat","decimalValue","Math","pow","toFixed","useCart","usePayments","useAddresses"],"mappings":"AAAA;;AAGA,SAASA,eAAe,QAAQ,iBAAgB;AAChD,YAAYC,QAAQ,SAAQ;AAC5B,OAAOC,SAASC,aAAa,EAAEC,GAAG,EAAEC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAWpG,MAAMC,iBAAuC;IAC3CC,SAAS,WAAa;IACtBC,WAAW,WAAa;IACxBC,cAAc,WAAa;IAC3BC,eAAe,WAAa;IAC5BC,kBAAkB;QAChBC,iBAAiB;QACjBC,qBAAqB;YACnB;gBACEC,MAAM;gBACNC,UAAU;gBACVC,OAAO;gBACPC,QAAQ;YACV;SACD;IACH;IACAC,UAAU;QACRJ,MAAM;QACNC,UAAU;QACVC,OAAO;QACPC,QAAQ;IACV;IACAE,eAAe,WAAa;IAC5BC,eAAe,WAAa;IAC5BC,iBAAiB,WAAa;IAC9BC,gBAAgB,EAAE;IAClBC,YAAY,WAAa;IACzBC,aAAa,KAAO;IACpBC,eAAe,WAAa;AAC9B;AAEA,MAAMC,iCAAmB3B,cAAoCO;AAE7D,MAAMqB,sBAAsB;IAC1BC,KAAK;AACP;AAEA,OAAO,MAAMC,oBAA4C,CAAC,EACxDC,gBAAgB,WAAW,EAC3BC,GAAG,EACHC,YAAY,OAAO,EACnBC,QAA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ACzE,MAAMmI,eAAeR,QAAQS,KAAKC,GAAG,CAAC,IAAIL,cAAchI,QAAQ;QAEhE,mDAAmD;QACnD,OAAO,GAAGgI,cAAc9H,MAAM,GAAGiI,aAAaG,OAAO,CAACN,cAAchI,QAAQ,GAAG;IACjF,GACA;QAACG;KAAS;IAGZ,IAAI,CAACA,UAAU;QACb,MAAM,IAAIkE,MAAM;IAClB;IAEA,OAAO;QACLlE;QACA4H;QACAtH;QACAX,qBAAqBF,iBAAiBE,mBAAmB;IAC3D;AACF,EAAC;AAED,OAAO,SAASyI;IACd,MAAM,EAAE/I,OAAO,EAAE0C,IAAI,EAAEzC,SAAS,EAAEW,aAAa,EAAEC,aAAa,EAAEG,UAAU,EAAE,GAAGoH;IAE/E,IAAI,CAACpI,SAAS;QACZ,MAAM,IAAI6E,MAAM;IAClB;IAEA,OAAO;QAAE7E;QAAS0C,MAAMA;QAAWzC;QAAWW;QAAeC;QAAeG;IAAW;AACzF;AAEA,OAAO,MAAMgI,cAAc;IACzB,MAAM,EAAE9I,YAAY,EAAEY,eAAe,EAAEC,cAAc,EAAEiC,qBAAqB,EAAE,GAAGoF;IAEjF,IAAI,CAACtH,iBAAiB;QACpB,MAAM,IAAI+D,MAAM;IAClB;IAEA,OAAO;QAAE3E;QAAcY;QAAiBC;QAAgBiC;IAAsB;AAChF,EAAC;AAED,OAAO,SAASiG;IACd,MAAM,EAAE5G,SAAS,EAAElC,aAAa,EAAEe,aAAa,EAAE,GAAGkH;IAEpD,IAAI,CAACjI,eAAe;QAClB,MAAM,IAAI0E,MAAM;IAClB;IAEA,OAAO;QAAExC,WAAWA;QAAkBlC;QAAee;IAAc;AACrE"}
|
|
1
|
+
{"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple } 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 = {}, serverURL = '' } = api || {}\n const baseAPIURL = `${serverURL}${apiRoute}`\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","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","serverURL","baseAPIURL","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,QAAQ,iBAAgB;AAChD,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,UAAU;gBACVC,OAAO;gBACPC,QAAQ;YACV;SACD;IACH;IACAC,UAAU;QACRJ,MAAM;QACNC,UAAU;QACVC,OAAO;QACPC,QAAQ;IACV;IACAE,eAAe,WAAa;IAC5BC,eAAe,WAAa;IAC5BC,iBAAiB,WAAa;IAC9BC,WAAW;IACXC,gBAAgB,EAAE;IAClBC,YAAY,WAAa;IACzBC,aAAa,KAAO;IACpBC,eAAe,WAAa;AAC9B;AAEA,MAAMC,iCAAmB7B,cAAoCQ;AAE7D,MAAMsB,sBAAsB;IAC1BC,KAAK;AACP;AAEA,OAAO,MAAMC,oBAA4C,CAAC,EACxDC,gBAAgB,WAAW,EAC3BC,GAAG,EACHC,YAAY,OAAO,EACnBC,QAAQ,EACRvB,mBAAmB;IACjBC,iBAAiB;IACjBC,qBAAqB;QACnB;YACEC,MAAM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MAAMA;QACN9C;QACAW;QACAC;QACAE;QACAE;IACF;AACF;AAEA,OAAO,MAAMyI,cAAc;IACzB,MAAM,EAAExJ,YAAY,EAAEY,eAAe,EAAEC,SAAS,EAAEC,cAAc,EAAEqC,qBAAqB,EAAE,GACvFyF;IAEF,IAAI,CAAChI,iBAAiB;QACpB,MAAM,IAAIoE,MAAM;IAClB;IAEA,OAAO;QAAEhF;QAAcY;QAAiBC;QAAWC;QAAgBqC;IAAsB;AAC3F,EAAC;AAED,OAAO,SAASsG;IACd,MAAM,EAAEpH,SAAS,EAAEpC,aAAa,EAAEY,SAAS,EAAEI,aAAa,EAAE,GAAG2H;IAE/D,IAAI,CAAC3I,eAAe;QAClB,MAAM,IAAI+E,MAAM;IAClB;IAEA,OAAO;QAAE3C,WAAWA;QAAkBpC;QAAeY;QAAWI;IAAc;AAChF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../src/translations/en.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AAEzE,eAAO,MAAM,EAAE,EAAE,
|
|
1
|
+
{"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../src/translations/en.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AAEzE,eAAO,MAAM,EAAE,EAAE,yBA8FhB,CAAA"}
|
package/dist/translations/en.js
CHANGED
|
@@ -25,6 +25,7 @@ export const en = {
|
|
|
25
25
|
cart: 'Cart',
|
|
26
26
|
carts: 'Carts',
|
|
27
27
|
cartsCollectionDescription: "Carts represent a customer's selection of products they intend to purchase. They are related to a customer where possible and guest users do not have a customer attached.",
|
|
28
|
+
cartSecret: 'Cart Secret',
|
|
28
29
|
completed: 'Completed',
|
|
29
30
|
currency: 'Currency',
|
|
30
31
|
currencyNotSet: 'Currency not set.',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/translations/en.ts"],"sourcesContent":["import type { GenericTranslationsObject } from '@payloadcms/translations'\n\nexport const en: GenericTranslationsObject = {\n $schema: './translation-schema.json',\n 'plugin-ecommerce': {\n abandoned: 'Abandoned',\n active: 'Active',\n address: 'Address',\n addressCity: 'City',\n addressCompany: 'Company',\n addressCountry: 'Country',\n addresses: 'Addresses',\n addressesCollectionDescription:\n 'Addresses are associated with customers are used to prefill shipping and billing when placing orders.',\n addressFirstName: 'First name',\n addressLastName: 'Last name',\n addressLine1: 'Address 1',\n addressLine2: 'Address 2',\n addressPhone: 'Phone',\n addressPostalCode: 'Postal code',\n addressState: 'State',\n addressTitle: 'Title',\n amount: 'Amount',\n availableVariants: 'Available variants',\n billing: 'Billing',\n billingAddress: 'Billing address',\n cancelled: 'Cancelled',\n cart: 'Cart',\n carts: 'Carts',\n cartsCollectionDescription:\n \"Carts represent a customer's selection of products they intend to purchase. They are related to a customer where possible and guest users do not have a customer attached.\",\n completed: 'Completed',\n currency: 'Currency',\n currencyNotSet: 'Currency not set.',\n customer: 'Customer',\n customerEmail: 'Customer email',\n customers: 'Customers',\n enableCurrencyPrice: `Enable {{currency}} price`,\n enableVariants: 'Enable variants',\n expired: 'Expired',\n failed: 'Failed',\n inventory: 'Inventory',\n item: 'Item',\n items: 'Items',\n open: 'Open',\n order: 'Order',\n orderDetails: 'Order Details',\n orders: 'Orders',\n ordersCollectionDescription:\n \"Orders represent a customer's intent to purchase products from your store. They include details such as the products ordered, quantities, prices, customer information, and order status.\",\n paymentMethod: 'Payment method',\n paymentMethods: 'Payment methods',\n pending: 'Pending',\n price: 'Price',\n priceIn: 'Price ({{currency}})',\n priceNotSet: 'Price not set.',\n prices: 'Prices',\n priceSetInVariants: 'Price set in variants.',\n processing: 'Processing',\n product: 'Product',\n productPriceDescription:\n 'This price will also be used for sorting and filtering products. If you have variants enabled then you can enter the lowest or average price to help with search and filtering, but this price will not be used for checkout.',\n productRequired: 'A product is required.',\n products: 'Products',\n purchased: 'Purchased',\n purchasedAt: 'Purchased at',\n quantity: 'Quantity',\n refunded: 'Refunded',\n shipping: 'Shipping',\n shippingAddress: 'Shipping address',\n status: 'Status',\n subtotal: 'Subtotal',\n succeeded: 'Succeeded',\n transaction: 'Transaction',\n transactionDetails: 'Transaction Details',\n transactions: 'Transactions',\n transactionsCollectionDescription:\n 'Transactions represent payment attempts made for an order. An order can have multiple transactions associated with it, such as an initial payment attempt and subsequent refunds or adjustments.',\n variant: 'Variant',\n variantOption: 'Variant Option',\n variantOptions: 'Variant Options',\n variantOptionsAlreadyExists:\n 'This variant combo is already in use by another variant. Please select different options.',\n variantOptionsCollectionDescription:\n 'Variant options define the options a variant type can have, such as red or white for colors.',\n variantOptionsRequired: 'Variant options are required.',\n variantOptionsRequiredAll: 'All variant options are required.',\n variants: 'Variants',\n variantsCollectionDescription:\n \"Product variants allow you to offer different versions of a product, such as size or color variations. They refrence a product's variant options based on the variant types approved.\",\n variantType: 'Variant Type',\n variantTypes: 'Variant Types',\n variantTypesCollectionDescription:\n 'Variant types are used to define the different types of variants your products can have, such as size or color. Each variant type can have multiple options associated with it.',\n },\n}\n"],"names":["en","$schema","abandoned","active","address","addressCity","addressCompany","addressCountry","addresses","addressesCollectionDescription","addressFirstName","addressLastName","addressLine1","addressLine2","addressPhone","addressPostalCode","addressState","addressTitle","amount","availableVariants","billing","billingAddress","cancelled","cart","carts","cartsCollectionDescription","completed","currency","currencyNotSet","customer","customerEmail","customers","enableCurrencyPrice","enableVariants","expired","failed","inventory","item","items","open","order","orderDetails","orders","ordersCollectionDescription","paymentMethod","paymentMethods","pending","price","priceIn","priceNotSet","prices","priceSetInVariants","processing","product","productPriceDescription","productRequired","products","purchased","purchasedAt","quantity","refunded","shipping","shippingAddress","status","subtotal","succeeded","transaction","transactionDetails","transactions","transactionsCollectionDescription","variant","variantOption","variantOptions","variantOptionsAlreadyExists","variantOptionsCollectionDescription","variantOptionsRequired","variantOptionsRequiredAll","variants","variantsCollectionDescription","variantType","variantTypes","variantTypesCollectionDescription"],"mappings":"AAEA,OAAO,MAAMA,KAAgC;IAC3CC,SAAS;IACT,oBAAoB;QAClBC,WAAW;QACXC,QAAQ;QACRC,SAAS;QACTC,aAAa;QACbC,gBAAgB;QAChBC,gBAAgB;QAChBC,WAAW;QACXC,gCACE;QACFC,kBAAkB;QAClBC,iBAAiB;QACjBC,cAAc;QACdC,cAAc;QACdC,cAAc;QACdC,mBAAmB;QACnBC,cAAc;QACdC,cAAc;QACdC,QAAQ;QACRC,mBAAmB;QACnBC,SAAS;QACTC,gBAAgB;QAChBC,WAAW;QACXC,MAAM;QACNC,OAAO;QACPC,4BACE;QACFC,WAAW;QACXC,UAAU;QACVC,gBAAgB;QAChBC,UAAU;QACVC,eAAe;QACfC,WAAW;QACXC,qBAAqB,CAAC,yBAAyB,CAAC;QAChDC,gBAAgB;QAChBC,SAAS;QACTC,QAAQ;QACRC,WAAW;QACXC,MAAM;QACNC,OAAO;QACPC,MAAM;QACNC,OAAO;QACPC,cAAc;QACdC,QAAQ;QACRC,6BACE;QACFC,eAAe;QACfC,gBAAgB;QAChBC,SAAS;QACTC,OAAO;QACPC,SAAS;QACTC,aAAa;QACbC,QAAQ;QACRC,oBAAoB;QACpBC,YAAY;QACZC,SAAS;QACTC,yBACE;QACFC,iBAAiB;QACjBC,UAAU;QACVC,WAAW;QACXC,aAAa;QACbC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,iBAAiB;QACjBC,QAAQ;QACRC,UAAU;QACVC,WAAW;QACXC,aAAa;QACbC,oBAAoB;QACpBC,cAAc;QACdC,mCACE;QACFC,SAAS;QACTC,eAAe;QACfC,gBAAgB;QAChBC,6BACE;QACFC,qCACE;QACFC,wBAAwB;QACxBC,2BAA2B;QAC3BC,UAAU;QACVC,+BACE;QACFC,aAAa;QACbC,cAAc;QACdC,mCACE;IACJ;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/translations/en.ts"],"sourcesContent":["import type { GenericTranslationsObject } from '@payloadcms/translations'\n\nexport const en: GenericTranslationsObject = {\n $schema: './translation-schema.json',\n 'plugin-ecommerce': {\n abandoned: 'Abandoned',\n active: 'Active',\n address: 'Address',\n addressCity: 'City',\n addressCompany: 'Company',\n addressCountry: 'Country',\n addresses: 'Addresses',\n addressesCollectionDescription:\n 'Addresses are associated with customers are used to prefill shipping and billing when placing orders.',\n addressFirstName: 'First name',\n addressLastName: 'Last name',\n addressLine1: 'Address 1',\n addressLine2: 'Address 2',\n addressPhone: 'Phone',\n addressPostalCode: 'Postal code',\n addressState: 'State',\n addressTitle: 'Title',\n amount: 'Amount',\n availableVariants: 'Available variants',\n billing: 'Billing',\n billingAddress: 'Billing address',\n cancelled: 'Cancelled',\n cart: 'Cart',\n carts: 'Carts',\n cartsCollectionDescription:\n \"Carts represent a customer's selection of products they intend to purchase. They are related to a customer where possible and guest users do not have a customer attached.\",\n cartSecret: 'Cart Secret',\n completed: 'Completed',\n currency: 'Currency',\n currencyNotSet: 'Currency not set.',\n customer: 'Customer',\n customerEmail: 'Customer email',\n customers: 'Customers',\n enableCurrencyPrice: `Enable {{currency}} price`,\n enableVariants: 'Enable variants',\n expired: 'Expired',\n failed: 'Failed',\n inventory: 'Inventory',\n item: 'Item',\n items: 'Items',\n open: 'Open',\n order: 'Order',\n orderDetails: 'Order Details',\n orders: 'Orders',\n ordersCollectionDescription:\n \"Orders represent a customer's intent to purchase products from your store. They include details such as the products ordered, quantities, prices, customer information, and order status.\",\n paymentMethod: 'Payment method',\n paymentMethods: 'Payment methods',\n pending: 'Pending',\n price: 'Price',\n priceIn: 'Price ({{currency}})',\n priceNotSet: 'Price not set.',\n prices: 'Prices',\n priceSetInVariants: 'Price set in variants.',\n processing: 'Processing',\n product: 'Product',\n productPriceDescription:\n 'This price will also be used for sorting and filtering products. If you have variants enabled then you can enter the lowest or average price to help with search and filtering, but this price will not be used for checkout.',\n productRequired: 'A product is required.',\n products: 'Products',\n purchased: 'Purchased',\n purchasedAt: 'Purchased at',\n quantity: 'Quantity',\n refunded: 'Refunded',\n shipping: 'Shipping',\n shippingAddress: 'Shipping address',\n status: 'Status',\n subtotal: 'Subtotal',\n succeeded: 'Succeeded',\n transaction: 'Transaction',\n transactionDetails: 'Transaction Details',\n transactions: 'Transactions',\n transactionsCollectionDescription:\n 'Transactions represent payment attempts made for an order. An order can have multiple transactions associated with it, such as an initial payment attempt and subsequent refunds or adjustments.',\n variant: 'Variant',\n variantOption: 'Variant Option',\n variantOptions: 'Variant Options',\n variantOptionsAlreadyExists:\n 'This variant combo is already in use by another variant. Please select different options.',\n variantOptionsCollectionDescription:\n 'Variant options define the options a variant type can have, such as red or white for colors.',\n variantOptionsRequired: 'Variant options are required.',\n variantOptionsRequiredAll: 'All variant options are required.',\n variants: 'Variants',\n variantsCollectionDescription:\n \"Product variants allow you to offer different versions of a product, such as size or color variations. They refrence a product's variant options based on the variant types approved.\",\n variantType: 'Variant Type',\n variantTypes: 'Variant Types',\n variantTypesCollectionDescription:\n 'Variant types are used to define the different types of variants your products can have, such as size or color. Each variant type can have multiple options associated with it.',\n },\n}\n"],"names":["en","$schema","abandoned","active","address","addressCity","addressCompany","addressCountry","addresses","addressesCollectionDescription","addressFirstName","addressLastName","addressLine1","addressLine2","addressPhone","addressPostalCode","addressState","addressTitle","amount","availableVariants","billing","billingAddress","cancelled","cart","carts","cartsCollectionDescription","cartSecret","completed","currency","currencyNotSet","customer","customerEmail","customers","enableCurrencyPrice","enableVariants","expired","failed","inventory","item","items","open","order","orderDetails","orders","ordersCollectionDescription","paymentMethod","paymentMethods","pending","price","priceIn","priceNotSet","prices","priceSetInVariants","processing","product","productPriceDescription","productRequired","products","purchased","purchasedAt","quantity","refunded","shipping","shippingAddress","status","subtotal","succeeded","transaction","transactionDetails","transactions","transactionsCollectionDescription","variant","variantOption","variantOptions","variantOptionsAlreadyExists","variantOptionsCollectionDescription","variantOptionsRequired","variantOptionsRequiredAll","variants","variantsCollectionDescription","variantType","variantTypes","variantTypesCollectionDescription"],"mappings":"AAEA,OAAO,MAAMA,KAAgC;IAC3CC,SAAS;IACT,oBAAoB;QAClBC,WAAW;QACXC,QAAQ;QACRC,SAAS;QACTC,aAAa;QACbC,gBAAgB;QAChBC,gBAAgB;QAChBC,WAAW;QACXC,gCACE;QACFC,kBAAkB;QAClBC,iBAAiB;QACjBC,cAAc;QACdC,cAAc;QACdC,cAAc;QACdC,mBAAmB;QACnBC,cAAc;QACdC,cAAc;QACdC,QAAQ;QACRC,mBAAmB;QACnBC,SAAS;QACTC,gBAAgB;QAChBC,WAAW;QACXC,MAAM;QACNC,OAAO;QACPC,4BACE;QACFC,YAAY;QACZC,WAAW;QACXC,UAAU;QACVC,gBAAgB;QAChBC,UAAU;QACVC,eAAe;QACfC,WAAW;QACXC,qBAAqB,CAAC,yBAAyB,CAAC;QAChDC,gBAAgB;QAChBC,SAAS;QACTC,QAAQ;QACRC,WAAW;QACXC,MAAM;QACNC,OAAO;QACPC,MAAM;QACNC,OAAO;QACPC,cAAc;QACdC,QAAQ;QACRC,6BACE;QACFC,eAAe;QACfC,gBAAgB;QAChBC,SAAS;QACTC,OAAO;QACPC,SAAS;QACTC,aAAa;QACbC,QAAQ;QACRC,oBAAoB;QACpBC,YAAY;QACZC,SAAS;QACTC,yBACE;QACFC,iBAAiB;QACjBC,UAAU;QACVC,WAAW;QACXC,aAAa;QACbC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,iBAAiB;QACjBC,QAAQ;QACRC,UAAU;QACVC,WAAW;QACXC,aAAa;QACbC,oBAAoB;QACpBC,cAAc;QACdC,mCACE;QACFC,SAAS;QACTC,eAAe;QACfC,gBAAgB;QAChBC,6BACE;QACFC,qCACE;QACFC,wBAAwB;QACxBC,2BAA2B;QAC3BC,UAAU;QACVC,+BACE;QACFC,aAAa;QACbC,cAAc;QACdC,mCACE;IACJ;AACF,EAAC"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -464,6 +464,12 @@ export type CustomersConfig = {
|
|
|
464
464
|
slug: string;
|
|
465
465
|
};
|
|
466
466
|
export type CartsConfig = {
|
|
467
|
+
/**
|
|
468
|
+
* Allow guest (unauthenticated) users to create carts.
|
|
469
|
+
* When enabled, guests can create carts without being logged in.
|
|
470
|
+
* Defaults to true.
|
|
471
|
+
*/
|
|
472
|
+
allowGuestCarts?: boolean;
|
|
467
473
|
cartsCollectionOverride?: CollectionOverride;
|
|
468
474
|
};
|
|
469
475
|
export type InventoryConfig = {
|
|
@@ -527,50 +533,57 @@ export type CollectionSlugMap = {
|
|
|
527
533
|
};
|
|
528
534
|
/**
|
|
529
535
|
* Access control functions used throughout the Ecommerce plugin.
|
|
530
|
-
*
|
|
536
|
+
* Provide atomic access functions that can be composed using or, and, conditional utilities.
|
|
531
537
|
*
|
|
532
538
|
* @example
|
|
533
|
-
*
|
|
534
539
|
* ```ts
|
|
535
540
|
* access: {
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
}
|
|
542
|
-
|
|
541
|
+
* isAdmin: ({ req }) => checkRole(['admin'], req.user),
|
|
542
|
+
* isAuthenticated: ({ req }) => !!req.user,
|
|
543
|
+
* isDocumentOwner: ({ req }) => {
|
|
544
|
+
* if (!req.user) return false
|
|
545
|
+
* return { customer: { equals: req.user.id } }
|
|
546
|
+
* },
|
|
547
|
+
* adminOnlyFieldAccess: ({ req }) => checkRole(['admin'], req.user),
|
|
548
|
+
* customerOnlyFieldAccess: ({ req }) => !!req.user,
|
|
549
|
+
* adminOrPublishedStatus: ({ req }) => {
|
|
550
|
+
* if (checkRole(['admin'], req.user)) return true
|
|
551
|
+
* return { _status: { equals: 'published' } }
|
|
552
|
+
* },
|
|
553
|
+
* }
|
|
554
|
+
* ```
|
|
543
555
|
*/
|
|
544
556
|
export type AccessConfig = {
|
|
545
|
-
/**
|
|
546
|
-
* Limited to only admin users.
|
|
547
|
-
*/
|
|
548
|
-
adminOnly: Access;
|
|
549
557
|
/**
|
|
550
558
|
* Limited to only admin users, specifically for Field level access control.
|
|
551
559
|
*/
|
|
552
560
|
adminOnlyFieldAccess: FieldAccess;
|
|
553
|
-
/**
|
|
554
|
-
* Is the owner of the document via the `customer` field or is an admin.
|
|
555
|
-
*/
|
|
556
|
-
adminOrCustomerOwner: Access;
|
|
557
561
|
/**
|
|
558
562
|
* The document status is published or user is admin.
|
|
559
563
|
*/
|
|
560
564
|
adminOrPublishedStatus: Access;
|
|
561
|
-
/**
|
|
562
|
-
* Authenticated users only. Defaults to the example function.
|
|
563
|
-
*
|
|
564
|
-
* @example
|
|
565
|
-
* anyUser: ({ req }) => !!req?.user
|
|
566
|
-
*/
|
|
567
|
-
authenticatedOnly?: Access;
|
|
568
565
|
/**
|
|
569
566
|
* Limited to customers only, specifically for Field level access control.
|
|
570
567
|
*/
|
|
571
568
|
customerOnlyFieldAccess: FieldAccess;
|
|
572
569
|
/**
|
|
573
|
-
*
|
|
570
|
+
* Checks if the user is an admin.
|
|
571
|
+
* @returns true if admin, false otherwise
|
|
572
|
+
*/
|
|
573
|
+
isAdmin: Access;
|
|
574
|
+
/**
|
|
575
|
+
* Checks if the user is authenticated (any role).
|
|
576
|
+
* @returns true if authenticated, false otherwise
|
|
577
|
+
*/
|
|
578
|
+
isAuthenticated?: Access;
|
|
579
|
+
/**
|
|
580
|
+
* Checks if the user owns the document being accessed.
|
|
581
|
+
* Typically returns a Where query to filter by customer field.
|
|
582
|
+
* @returns true for full access, false for no access, or Where query for conditional access
|
|
583
|
+
*/
|
|
584
|
+
isDocumentOwner: Access;
|
|
585
|
+
/**
|
|
586
|
+
* Entirely public access. Defaults to returning true.
|
|
574
587
|
*
|
|
575
588
|
* @example
|
|
576
589
|
* publicAccess: () => true
|
|
@@ -809,6 +822,11 @@ export type EcommerceContextType<T extends EcommerceCollections = EcommerceColle
|
|
|
809
822
|
initiatePayment: (paymentMethodID: string, options?: {
|
|
810
823
|
additionalData: Record<string, unknown>;
|
|
811
824
|
}) => Promise<unknown>;
|
|
825
|
+
/**
|
|
826
|
+
* Indicates whether any cart operation is currently in progress.
|
|
827
|
+
* Useful for disabling buttons and preventing race conditions.
|
|
828
|
+
*/
|
|
829
|
+
isLoading: boolean;
|
|
812
830
|
paymentMethods: PaymentAdapterClient[];
|
|
813
831
|
/**
|
|
814
832
|
* Remove an item from the cart by its index ID.
|
|
@@ -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,CAAA;IACjB,QAAQ,CAAC,EAAE,qBAAqB,GAAG,eAAe,CAAC,WAAW,CAAC,CAAA;IAC/D,EAAE,EAAE,qBA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,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC/D;;OAEG;IACH,gBAAgB,EAAE,gBAAgB,CAAA;IAClC;;OAEG;IACH,QAAQ,EAAE,QAAQ,CAAA;IAClB;;;OAGG;IACH,aAAa,EAAE,CAAC,IAAI,EAAE,qBAAqB,KAAK,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,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 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 * You must provide these when configuring the plugin.\n *\n * @example\n *\n * ```ts\n * access: {\n adminOnly,\n adminOnlyFieldAccess,\n adminOrCustomerOwner,\n adminOrPublishedStatus,\n customerOnlyFieldAccess,\n }\n ```\n */\nexport type AccessConfig = {\n /**\n * Limited to only admin users.\n */\n adminOnly: Access\n /**\n * Limited to only admin users, specifically for Field level access control.\n */\n adminOnlyFieldAccess: FieldAccess\n /**\n * Is the owner of the document via the `customer` field or is an admin.\n */\n adminOrCustomerOwner: Access\n /**\n * The document status is published or user is admin.\n */\n adminOrPublishedStatus: Access\n /**\n * Authenticated users only. Defaults to the example function.\n *\n * @example\n * anyUser: ({ req }) => !!req?.user\n */\n authenticatedOnly?: Access\n /**\n * Limited to customers only, specifically for Field level access control.\n */\n customerOnlyFieldAccess: FieldAccess\n /**\n * Entirely public access. Defaults to the example function.\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 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":"AAoyBA,WAgFC"}
|
|
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"}
|