@commercelayer/react-components 4.19.0 → 4.20.1-beta.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.
Files changed (61) hide show
  1. package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
  2. package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.js +1 -1
  3. package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
  4. package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
  5. package/lib/cjs/components/orders/AddToCartButton.d.ts +6 -6
  6. package/lib/cjs/components/orders/AddToCartButton.js +1 -1
  7. package/lib/cjs/components/orders/GiftCardAmount.d.ts +3 -3
  8. package/lib/cjs/components/orders/GiftCardAmount.js +1 -1
  9. package/lib/cjs/components/orders/OrderContainer.d.ts +8 -4
  10. package/lib/cjs/components/orders/OrderContainer.js +1 -1
  11. package/lib/cjs/components/orders/PlaceOrderButton.d.ts +6 -6
  12. package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
  13. package/lib/cjs/components/orders/TotalAmount.d.ts +3 -3
  14. package/lib/cjs/components/orders/TotalAmount.js +1 -1
  15. package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
  16. package/lib/cjs/components/payment_source/KlarnaPayment.d.ts +4 -4
  17. package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
  18. package/lib/cjs/components/payment_source/StripeExpressPayment.d.ts +2 -2
  19. package/lib/cjs/components/payment_source/StripeExpressPayment.js +1 -1
  20. package/lib/cjs/context/OrderContext.d.ts +5 -3
  21. package/lib/cjs/context/OrderContext.js +1 -1
  22. package/lib/cjs/reducers/OrderReducer.d.ts +34 -20
  23. package/lib/cjs/reducers/OrderReducer.js +1 -1
  24. package/lib/cjs/reducers/PaymentMethodReducer.d.ts +26 -26
  25. package/lib/cjs/reducers/PlaceOrderReducer.d.ts +11 -11
  26. package/lib/cjs/utils/adyen/manageGiftCard.d.ts +16 -0
  27. package/lib/cjs/utils/adyen/manageGiftCard.js +2 -0
  28. package/lib/cjs/utils/expressPaymentHelper.d.ts +8 -8
  29. package/lib/cjs/utils/expressPaymentHelper.js +1 -1
  30. package/lib/esm/components/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
  31. package/lib/esm/components/gift_cards/GiftCardOrCouponCode.js +1 -1
  32. package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
  33. package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
  34. package/lib/esm/components/orders/AddToCartButton.d.ts +6 -6
  35. package/lib/esm/components/orders/AddToCartButton.js +1 -1
  36. package/lib/esm/components/orders/GiftCardAmount.d.ts +3 -3
  37. package/lib/esm/components/orders/GiftCardAmount.js +1 -1
  38. package/lib/esm/components/orders/OrderContainer.d.ts +8 -4
  39. package/lib/esm/components/orders/OrderContainer.js +1 -1
  40. package/lib/esm/components/orders/PlaceOrderButton.d.ts +6 -6
  41. package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
  42. package/lib/esm/components/orders/TotalAmount.d.ts +3 -3
  43. package/lib/esm/components/orders/TotalAmount.js +1 -1
  44. package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
  45. package/lib/esm/components/payment_source/KlarnaPayment.d.ts +4 -4
  46. package/lib/esm/components/payment_source/KlarnaPayment.js +1 -1
  47. package/lib/esm/components/payment_source/StripeExpressPayment.d.ts +2 -2
  48. package/lib/esm/components/payment_source/StripeExpressPayment.js +1 -1
  49. package/lib/esm/context/OrderContext.d.ts +5 -3
  50. package/lib/esm/context/OrderContext.js +1 -1
  51. package/lib/esm/reducers/OrderReducer.d.ts +34 -20
  52. package/lib/esm/reducers/OrderReducer.js +1 -1
  53. package/lib/esm/reducers/PaymentMethodReducer.d.ts +26 -26
  54. package/lib/esm/reducers/PlaceOrderReducer.d.ts +11 -11
  55. package/lib/esm/utils/adyen/manageGiftCard.d.ts +16 -0
  56. package/lib/esm/utils/adyen/manageGiftCard.js +2 -0
  57. package/lib/esm/utils/expressPaymentHelper.d.ts +8 -8
  58. package/lib/esm/utils/expressPaymentHelper.js +1 -1
  59. package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
  60. package/lib/tsconfig.prod.tsbuildinfo +1 -1
  61. package/package.json +19 -19
@@ -1,7 +1,7 @@
1
- import { type JSX } from 'react';
2
- import type { BaseMetadataObject } from '../../typings/index';
3
- import type { OrderCreate, Order } from '@commercelayer/sdk';
4
- import type { DefaultChildrenType } from '../../typings/globals';
1
+ import { type JSX } from "react";
2
+ import type { BaseMetadataObject } from "../../typings/index";
3
+ import type { OrderCreate, Order } from "@commercelayer/sdk";
4
+ import type { DefaultChildrenType } from "../../typings/globals";
5
5
  interface Props {
6
6
  children: DefaultChildrenType;
7
7
  /**
@@ -20,6 +20,10 @@ interface Props {
20
20
  * Callback called when the order is updated
21
21
  */
22
22
  fetchOrder?: (order: Order) => void;
23
+ /**
24
+ * Indicate if Adyen gift card management is enabled
25
+ */
26
+ manageAdyenGiftCard?: boolean;
23
27
  }
24
28
  /**
25
29
  * This component is responsible for fetching the order and store it in its context.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart,paymentSourceRequest}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
@@ -1,14 +1,14 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- import type { BaseError } from '../../typings/errors';
4
- import type { Order } from '@commercelayer/sdk';
5
- interface ChildrenProps extends Omit<Props, 'children'> {
1
+ import { type ReactNode, type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ import type { BaseError } from "../../typings/errors";
4
+ import type { Order } from "@commercelayer/sdk";
5
+ interface ChildrenProps extends Omit<Props, "children"> {
6
6
  /**
7
7
  * Callback function to place the order
8
8
  */
9
9
  handleClick: () => Promise<void>;
10
10
  }
11
- interface Props extends Omit<JSX.IntrinsicElements['button'], 'children' | 'onClick'> {
11
+ interface Props extends Omit<JSX.IntrinsicElements["button"], "children" | "onClick"> {
12
12
  children?: ChildrenFunction<ChildrenProps>;
13
13
  /**
14
14
  * The label of the button
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick&&placed&&onClick(placed)):(setForceDisable(!1),onClick&&placed&&onClick(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import PlaceOrderContext from"../../context/PlaceOrderContext";import isFunction from"lodash/isFunction";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";export function PlaceOrderButton(props){const ref=useRef(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=useContext(PlaceOrderContext),[notPermitted,setNotPermitted]=useState(!0),[forceDisable,setForceDisable]=useState(disabled),[isLoading,setIsLoading]=useState(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),isFree=order?.total_amount_with_taxes_cents===0;useEffect(()=>{if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=getCardDetails({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,currentPaymentMethodRef?.current?.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),useEffect(()=>{if(paymentType==="stripe_payments"&&options?.stripe?.paymentIntentClientSecret&&order?.payment_source?.publishable_key&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=order?.payment_source?.publishable_key,paymentIntentClientSecret=options?.stripe?.paymentIntentClientSecret,getPaymentIntent=async()=>{const paymentIntentResult=await checkPaymentIntent({publicApiKey,paymentIntentClientSecret});switch(paymentIntentResult.status){case"valid":handleClick();break;case"processing":setTimeout(()=>{getPaymentIntent()},1e3);break;case"invalid":setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentIntentResult.message}]);break}};getPaymentIntent()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),useEffect(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null;if(paymentType==="adyen_payments"&&options?.adyen?.redirectResult&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:options?.adyen?.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{const resultCode2=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode2)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else(paymentType==="adyen_payments"&&options?.adyen?.MD&&options?.adyen?.PaRes&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&ref?.current?.disabled===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&order?.payment_source?.payment_response?.merchantReference?.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),useEffect(()=>{paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&getCardDetails({paymentType,customerPayment:{payment_source:checkPaymentSource}});currentPaymentMethodRef?.current?.onsubmit&&[!options?.paypalPayerId,!options?.adyen?.MD,!options?.checkoutCom?.session_id].every(Boolean)?(isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&checkPaymentSource?.payment_response?.resultCode==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&await setPlaceOrder({paymentSource:checkPaymentSource,currentCustomerPaymentSourceId});placed&&setPlaceOrderStatus!=null?placed.placed?(setPlaceOrderStatus({status:"placing"}),onClick?.(placed)):(setForceDisable(!1),onClick?.(placed),setIsLoading(!1),setPlaceOrderStatus({status:"standby"})):(setForceDisable(!1),setIsLoading(!1))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
@@ -1,4 +1,4 @@
1
- import type { BaseAmountComponent } from '../../typings/index';
2
- import type { JSX } from "react";
3
- export declare function TotalAmount(props: BaseAmountComponent): JSX.Element;
1
+ import type { BaseAmountComponent } from "../../typings/index";
2
+ import { type JSX } from "react";
3
+ export declare function TotalAmount(props: BaseAmountComponent): JSX.Element | null;
4
4
  export default TotalAmount;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";export function TotalAmount(props){return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props})}export default TotalAmount;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function TotalAmount(props){const{manageAdyenGiftCard,order}=useContext(OrderContext);if(manageAdyenGiftCard){const giftCardData=manageGiftCard({order});if(!giftCardData)return null;const parentProps={price:`${giftCardData?.formattedOrderTotal}`,...props};return props.children?_jsx(Parent,{...parentProps,children:props.children}):_jsx("span",{...props,children:`${giftCardData?.formattedOrderTotal}`})}return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props})}export default TotalAmount;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import Parent from"../utils/Parent";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import{getPublicIP}from"../../utils/getPublicIp";import CustomerContext from"../../context/CustomerContext";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),shopperIp=await getPublicIP(),controlCode=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}))?.payment_response?.resultCode;if(controlCode==="Authorised")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",recurringProcessingModel:"CardOnFile",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])}return{resultCode}}catch(error){return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error.message}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null,options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?dropinRef.current?.handleAction(action):actions.resolve({resultCode})})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref}))}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))};dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import Parent from"../utils/Parent";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import{getPublicIP}from"../../utils/getPublicIp";import CustomerContext from"../../context/CustomerContext";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"});console.log("Control",control);const controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",recurringProcessingModel:"CardOnFile",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(console.log("Control code",controlCode),console.log("Payment method type",paymentMethodType),["Cancelled","Refused"].includes(controlCode)&&paymentMethodType==="giftcard"&&currentPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt(control?.payment_response?.additionalData?.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return console.log("totalPartialAmount",totalPartialAmount),await updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),console.log("Authorize first credit card amount"),await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),await updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}});return console.log("First gift card authorization",firstAuthorization),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null,options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),dropinRef.current?.mount("#adyen-dropin"))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref}))}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))};dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
@@ -1,7 +1,7 @@
1
- import { type JSX } from 'react';
2
- import type { PaymentMethodConfig } from '../../reducers/PaymentMethodReducer';
3
- import type { PaymentSourceProps } from './PaymentSource';
4
- type KlarnaPaymentProps = PaymentMethodConfig['klarnaPayment'] & JSX.IntrinsicElements['div'] & Partial<PaymentSourceProps['templateCustomerSaveToWallet']> & {
1
+ import { type JSX } from "react";
2
+ import type { PaymentMethodConfig } from "../../reducers/PaymentMethodReducer";
3
+ import type { PaymentSourceProps } from "./PaymentSource";
4
+ type KlarnaPaymentProps = PaymentMethodConfig["klarnaPayment"] & JSX.IntrinsicElements["div"] & Partial<PaymentSourceProps["templateCustomerSaveToWallet"]> & {
5
5
  show?: boolean;
6
6
  clientToken: string;
7
7
  locale?: string | null;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async function(res){if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
@@ -1,6 +1,6 @@
1
- import { type JSX } from 'react';
1
+ import { type JSX } from "react";
2
2
  interface Props {
3
3
  clientSecret: string;
4
4
  }
5
- export declare function StripeExpressPayment({ clientSecret }: Props): JSX.Element | null;
5
+ export declare function StripeExpressPayment({ clientSecret, }: Props): JSX.Element | null;
6
6
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{getAvailableExpressPayments,getExpressShippingMethods,setExpressFakeAddress,setExpressPlaceOrder,setExpressShippingMethod,expressRedirectUrl}from"../../utils/expressPaymentHelper";import{isEmpty}from"../../utils/isEmpty";import{PaymentRequestButtonElement,useStripe}from"@stripe/react-stripe-js";import{useContext,useEffect,useState}from"react";export function StripeExpressPayment({clientSecret}){const stripe=useStripe(),[paymentRequest,setPaymentRequest]=useState(null),{accessToken,endpoint}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{paymentMethods,paymentSource}=useContext(PaymentMethodContext);return useEffect(()=>{if(stripe==null||order==null)return;const pr=stripe.paymentRequest({country:order?.country_code??"US",currency:order?.currency_code?.toLowerCase()??"",total:{label:`#${order?.number??""}`,amount:order?.total_amount_with_taxes_cents??0},requestPayerName:!0,requestPayerEmail:!0,requestPayerPhone:!0,requestShipping:!0});pr.canMakePayment().then(result=>{result&&setPaymentRequest(pr)}).catch(err=>{console.error("Can make payment:",err)})},[isEmpty(stripe),isEmpty(order)]),paymentRequest!=null&&stripe!=null?(paymentRequest.on("shippingaddresschange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const requiresBillingInfo=order?.requires_billing_info??!1,orderWithShipments=await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:"Fake name",last_name:"Fake lastname",country_code:ev.shippingAddress.country??"",line_1:"Fake street 123",city:ev.shippingAddress.city??"Fake city",zip_code:ev.shippingAddress.postalCode??"12345",state_code:ev.shippingAddress.region??"Fake state",phone:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0}}),shippingOptions=getExpressShippingMethods(orderWithShipments);shippingOptions!=null&&!isEmpty(shippingOptions)?ev.updateWith({status:"success",shippingOptions,total:{label:`#${orderWithShipments?.number??""}`,amount:orderWithShipments?.total_amount_with_taxes_cents??0}}):ev.updateWith({status:"invalid_shipping_address"})}else ev.updateWith({status:"fail"})}),paymentRequest.on("shippingoptionchange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const updatedOrder=await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev.shippingOption.id,params:{include:["shipments.available_shipping_methods"]}});ev.updateWith({status:"success",total:{label:`#${updatedOrder?.number??""}`,amount:updatedOrder?.total_amount_with_taxes_cents??0}})}else ev.updateWith({status:"fail"})}),paymentRequest.on("paymentmethod",async ev=>{if(order?.id==null)throw new Error("Order is null");if(paymentMethods==null)throw new Error("Payment methods are null");const[paymentMethod]=getAvailableExpressPayments(paymentMethods);if(paymentMethod==null)throw new Error("Payment method is null");if(paymentSource==null)throw new Error("Payment source is null");const requiresBillingInfo=order?.requires_billing_info??!1,paymentResource=paymentMethod?.payment_source_type;if(accessToken!=null&&endpoint!=null){const[firstName,lastName]=ev.payerName?.split(" ")??[],[line]=ev.shippingAddress?.addressLine??"",email=ev.payerEmail??"";await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:firstName??"Fake name",last_name:lastName??"Fake lastname",country_code:ev?.shippingAddress?.country??"",line_1:line??"Fake street 123",city:ev?.shippingAddress?.city??"Fake city",zip_code:ev?.shippingAddress?.postalCode??"12345",state_code:ev?.shippingAddress?.region??"Fake state",phone:ev?.payerPhone??"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0},email}),await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev?.shippingOption?.id,params:{include:["shipments.available_shipping_methods"]}});const placeOrderParams={config:{accessToken,endpoint},orderId:order?.id,paymentResource,paymentSourceId:paymentSource?.id};await setExpressPlaceOrder(placeOrderParams);const{paymentIntent,error:confirmError}=await stripe.confirmCardPayment(clientSecret,{payment_method:ev.paymentMethod.id},{handleActions:!1});if(confirmError)ev.complete("fail"),console.error("Confirm card payment:",confirmError);else if(ev.complete("success"),paymentIntent.status==="requires_action"){const{error}=await stripe.confirmCardPayment(clientSecret);if(error)console.error("Confirm card payment:",error);else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}}),_jsx(_Fragment,{children:_jsx(PaymentRequestButtonElement,{className:"",options:{paymentRequest}})})):null}
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{getAvailableExpressPayments,getExpressShippingMethods,setExpressFakeAddress,setExpressPlaceOrder,setExpressShippingMethod,expressRedirectUrl}from"../../utils/expressPaymentHelper";import{isEmpty}from"../../utils/isEmpty";import{PaymentRequestButtonElement,useStripe}from"@stripe/react-stripe-js";import{useContext,useEffect,useState}from"react";export function StripeExpressPayment({clientSecret}){const stripe=useStripe(),[paymentRequest,setPaymentRequest]=useState(null),{accessToken,endpoint}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{paymentMethods,paymentSource}=useContext(PaymentMethodContext);return useEffect(()=>{if(stripe==null||order==null)return;const pr=stripe.paymentRequest({country:order?.country_code??"US",currency:order?.currency_code?.toLowerCase()??"",total:{label:`#${order?.number??""}`,amount:order?.total_amount_with_taxes_cents??0},requestPayerName:!0,requestPayerEmail:!0,requestPayerPhone:!0,requestShipping:!0});pr.canMakePayment().then(result=>{result&&setPaymentRequest(pr)}).catch(err=>{console.error("Can make payment:",err)})},[isEmpty(stripe),isEmpty(order)]),paymentRequest!=null&&stripe!=null?(paymentRequest.on("shippingaddresschange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const requiresBillingInfo=order?.requires_billing_info??!1,orderWithShipments=await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:"Fake name",last_name:"Fake lastname",country_code:ev.shippingAddress.country??"",line_1:"Fake street 123",city:ev.shippingAddress.city??"Fake city",zip_code:ev.shippingAddress.postalCode??"12345",state_code:ev.shippingAddress.region??"Fake state",phone:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0}}),shippingOptions=getExpressShippingMethods(orderWithShipments);shippingOptions!=null&&!isEmpty(shippingOptions)?ev.updateWith({status:"success",shippingOptions,total:{label:`#${orderWithShipments?.number??""}`,amount:orderWithShipments?.total_amount_with_taxes_cents??0}}):ev.updateWith({status:"invalid_shipping_address"})}else ev.updateWith({status:"fail"})}),paymentRequest.on("shippingoptionchange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const updatedOrder=await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev.shippingOption.id,params:{include:["shipments.available_shipping_methods"]}});ev.updateWith({status:"success",total:{label:`#${updatedOrder?.number??""}`,amount:updatedOrder?.total_amount_with_taxes_cents??0}})}else ev.updateWith({status:"fail"})}),paymentRequest.on("paymentmethod",async ev=>{if(order?.id==null)throw new Error("Order is null");if(paymentMethods==null)throw new Error("Payment methods are null");const[paymentMethod]=getAvailableExpressPayments(paymentMethods);if(paymentMethod==null)throw new Error("Payment method is null");if(paymentSource==null)throw new Error("Payment source is null");const requiresBillingInfo=order?.requires_billing_info??!1,paymentResource=paymentMethod?.payment_source_type;if(accessToken!=null&&endpoint!=null){const[firstName,lastName]=ev.payerName?.split(" ")??[],[line]=ev.shippingAddress?.addressLine??"",email=ev.payerEmail??"";await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:firstName??"Fake name",last_name:lastName??"Fake lastname",country_code:ev?.shippingAddress?.country??"",line_1:line??"Fake street 123",city:ev?.shippingAddress?.city??"Fake city",zip_code:ev?.shippingAddress?.postalCode??"12345",state_code:ev?.shippingAddress?.region??"Fake state",phone:ev?.payerPhone??"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0},email}),await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev?.shippingOption?.id,params:{include:["shipments.available_shipping_methods"]}});const placeOrderParams={config:{accessToken,endpoint},orderId:order?.id,paymentResource,paymentSourceId:paymentSource?.id};await setExpressPlaceOrder(placeOrderParams);const{paymentIntent,error:confirmError}=await stripe.confirmCardPayment(clientSecret,{payment_method:ev.paymentMethod.id},{handleActions:!1});if(confirmError)ev.complete("fail"),console.error("Confirm card payment:",confirmError);else if(ev.complete("success"),paymentIntent.status==="requires_action"){const{error}=await stripe.confirmCardPayment(clientSecret);if(error)console.error("Confirm card payment:",error);else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),await expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),await expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}}),_jsx(_Fragment,{children:_jsx(PaymentRequestButtonElement,{className:"",options:{paymentRequest}})})):null}
@@ -1,6 +1,6 @@
1
- import type { Order } from '@commercelayer/sdk';
2
- import { type OrderState, type SaveAddressToCustomerAddressBook, createOrder, setGiftCardOrCouponCode, removeGiftCardOrCouponCode, addResourceToInclude, updateOrder, type getOrderContext, type addToCart } from '../reducers/OrderReducer';
3
- import type { BaseError } from '../typings/errors';
1
+ import type { Order } from "@commercelayer/sdk";
2
+ import { type OrderState, type SaveAddressToCustomerAddressBook, createOrder, paymentSourceRequest, setGiftCardOrCouponCode, removeGiftCardOrCouponCode, addResourceToInclude, updateOrder, type getOrderContext, type addToCart } from "../reducers/OrderReducer";
3
+ import type { BaseError } from "../typings/errors";
4
4
  interface DefaultContext extends OrderState {
5
5
  createOrder: typeof createOrder;
6
6
  addToCart?: typeof addToCart;
@@ -12,6 +12,7 @@ interface DefaultContext extends OrderState {
12
12
  getOrder: getOrderContext;
13
13
  updateOrder: typeof updateOrder;
14
14
  setOrder: (order: Order) => void;
15
+ paymentSourceRequest: typeof paymentSourceRequest;
15
16
  }
16
17
  export declare const defaultOrderContext: {
17
18
  createOrder: typeof createOrder;
@@ -23,6 +24,7 @@ export declare const defaultOrderContext: {
23
24
  addResourceToInclude: typeof addResourceToInclude;
24
25
  getOrder: () => Promise<undefined>;
25
26
  updateOrder: typeof updateOrder;
27
+ paymentSourceRequest: typeof paymentSourceRequest;
26
28
  };
27
29
  declare const OrderContext: import("react").Context<DefaultContext>;
28
30
  export default OrderContext;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{createContext}from"react";import{createOrder,setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,updateOrder}from"../reducers/OrderReducer";export const defaultOrderContext={createOrder,setOrderErrors:()=>{},setOrder:()=>{},setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,getOrder:async()=>{},updateOrder};const OrderContext=createContext(defaultOrderContext);export default OrderContext;
2
+ import{createContext}from"react";import{createOrder,paymentSourceRequest,setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,updateOrder}from"../reducers/OrderReducer";export const defaultOrderContext={createOrder,setOrderErrors:()=>{},setOrder:()=>{},setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,getOrder:async()=>{},updateOrder,paymentSourceRequest};const OrderContext=createContext(defaultOrderContext);export default OrderContext;
@@ -1,11 +1,11 @@
1
- import type { Dispatch } from 'react';
2
- import { type SetLocalOrder, type DeleteLocalOrder } from '../utils/localStorage';
3
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
4
- import type { BaseMetadataObject } from '../typings/index';
5
- import type { BaseError } from '../typings/errors';
6
- import type { AddressResource } from './AddressReducer';
7
- import type { Order, OrderUpdate } from '@commercelayer/sdk';
8
- import type { LooseAutocomplete } from '../typings/globals';
1
+ import type { Dispatch } from "react";
2
+ import { type SetLocalOrder, type DeleteLocalOrder } from "../utils/localStorage";
3
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
4
+ import type { BaseMetadataObject } from "../typings/index";
5
+ import type { BaseError } from "../typings/errors";
6
+ import type { AddressResource } from "./AddressReducer";
7
+ import type { Order, OrderUpdate, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
8
+ import type { LooseAutocomplete } from "../typings/globals";
9
9
  export type GetOrderParams = Partial<{
10
10
  clearWhenPlaced: boolean;
11
11
  config: CommerceLayerConfig;
@@ -16,8 +16,8 @@ export type GetOrderParams = Partial<{
16
16
  state: OrderState;
17
17
  }>;
18
18
  export type GetOrder = (params: GetOrderParams) => Promise<undefined | Order>;
19
- type CreateOrderParams = Pick<AddToCartParams, 'config' | 'dispatch' | 'persistKey' | 'state' | 'orderMetadata' | 'orderAttributes' | 'setLocalOrder'>;
20
- export interface AddToCartImportParams extends Omit<AddToCartParams, 'skuCode' | 'skuId' | 'quantity' | 'option' | 'lineItem'> {
19
+ type CreateOrderParams = Pick<AddToCartParams, "config" | "dispatch" | "persistKey" | "state" | "orderMetadata" | "orderAttributes" | "setLocalOrder">;
20
+ export interface AddToCartImportParams extends Omit<AddToCartParams, "skuCode" | "skuId" | "quantity" | "option" | "lineItem"> {
21
21
  lineItems: CustomLineItem[];
22
22
  }
23
23
  export type AddToCartReturn = Promise<{
@@ -26,7 +26,7 @@ export type AddToCartReturn = Promise<{
26
26
  }>;
27
27
  export type AddToCartImport = (params: AddToCartImportParams) => AddToCartReturn;
28
28
  export type UnsetOrderState = (dispatch: Dispatch<OrderActions>) => void;
29
- export type ResourceIncluded = 'billing_address' | 'shipping_address' | 'line_items.line_item_options.sku_option' | 'line_items.item' | 'available_customer_payment_sources.payment_source' | 'available_customer_payment_sources.payment_method' | 'shipments.available_shipping_methods' | 'shipments.stock_transfers' | 'shipments.stock_transfers.line_item' | 'shipments.stock_line_items.line_item' | 'shipments.shipping_method' | 'shipments.stock_location' | 'shipments.parcels' | 'shipments.parcels.parcel_line_items' | 'payment_source' | 'available_payment_methods' | 'payment_method';
29
+ export type ResourceIncluded = "billing_address" | "shipping_address" | "line_items.line_item_options.sku_option" | "line_items.item" | "available_customer_payment_sources.payment_source" | "available_customer_payment_sources.payment_method" | "shipments.available_shipping_methods" | "shipments.stock_transfers" | "shipments.stock_transfers.line_item" | "shipments.stock_line_items.line_item" | "shipments.shipping_method" | "shipments.stock_location" | "shipments.parcels" | "shipments.parcels.parcel_line_items" | "payment_source" | "available_payment_methods" | "payment_method";
30
30
  type ResourceIncludedLoaded = Partial<Record<ResourceIncluded, boolean>>;
31
31
  export interface OrderPayload {
32
32
  loading?: boolean;
@@ -36,30 +36,44 @@ export interface OrderPayload {
36
36
  include?: ResourceIncluded[] | undefined;
37
37
  includeLoaded?: ResourceIncludedLoaded;
38
38
  withoutIncludes?: boolean;
39
+ manageAdyenGiftCard?: boolean;
39
40
  }
40
- export type AddToCartImportValues = Pick<AddToCartImportParams, 'lineItems'>;
41
+ export type AddToCartImportValues = Pick<AddToCartImportParams, "lineItems">;
41
42
  export type getOrderContext = (id: string) => Promise<undefined | Order>;
42
43
  export type OrderState = Partial<OrderPayload>;
43
44
  export interface OrderActions {
44
45
  type: OrderActionType;
45
46
  payload: OrderPayload;
46
47
  }
47
- export type OrderActionType = 'setLoading' | 'setOrderId' | 'setOrder' | 'setSingleQuantity' | 'setCurrentSkuCodes' | 'setCurrentSkuPrices' | 'setCurrentItem' | 'setErrors' | 'setSaveAddressToCustomerAddressBook' | 'setGiftCardOrCouponCode' | 'setIncludesResource';
48
+ export type OrderActionType = "setLoading" | "setOrderId" | "setOrder" | "setSingleQuantity" | "setCurrentSkuCodes" | "setCurrentSkuPrices" | "setCurrentItem" | "setErrors" | "setSaveAddressToCustomerAddressBook" | "setGiftCardOrCouponCode" | "setIncludesResource";
48
49
  export declare function createOrder(params: CreateOrderParams): Promise<string>;
49
50
  export declare const getApiOrder: GetOrder;
50
51
  export interface UpdateOrderArgs {
51
52
  id: string;
52
- attributes: Omit<OrderUpdate, 'id'>;
53
+ attributes: Omit<OrderUpdate, "id">;
53
54
  dispatch?: Dispatch<OrderActions>;
54
55
  include?: string[];
55
56
  config?: CommerceLayerConfig;
56
57
  state?: OrderState;
57
58
  }
58
- export declare function updateOrder({ id, attributes, dispatch, config, include, state }: UpdateOrderArgs): Promise<{
59
+ export declare function updateOrder({ id, attributes, dispatch, config, include, state, }: UpdateOrderArgs): Promise<{
59
60
  success: boolean;
60
61
  error?: unknown;
61
62
  order?: Order;
62
63
  }>;
64
+ interface TResourceRequest {
65
+ resource: Extract<keyof CommerceLayerClient, "adyen_payments">;
66
+ requestType: "update";
67
+ attributes: TResourceRequest["resource"] extends "adyen_payments" ? AdyenPaymentUpdate : ResourceUpdate;
68
+ order: Order;
69
+ dispatch?: Dispatch<OrderActions>;
70
+ config?: CommerceLayerConfig;
71
+ state?: OrderState;
72
+ }
73
+ export declare function paymentSourceRequest({ resource, requestType, dispatch, attributes, config, order, state, }: TResourceRequest): Promise<{
74
+ success: boolean;
75
+ order?: Order;
76
+ }>;
63
77
  export declare const setOrder: (order: Order, dispatch?: Dispatch<OrderActions>) => void;
64
78
  export interface AddResourceToInclude {
65
79
  resourcesIncluded?: ResourceIncluded[];
@@ -68,7 +82,7 @@ export interface AddResourceToInclude {
68
82
  resourceIncludedLoaded?: ResourceIncludedLoaded;
69
83
  newResourceLoaded?: ResourceIncludedLoaded;
70
84
  }
71
- export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded }: AddResourceToInclude): void;
85
+ export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded, }: AddResourceToInclude): void;
72
86
  export interface LineItemOption {
73
87
  /**
74
88
  * SKU Option ID. Ex: mNJEgsJwBn
@@ -80,7 +94,7 @@ export interface LineItemOption {
80
94
  options: Record<string, string>;
81
95
  quantity?: number;
82
96
  }
83
- type TFrequency = 'hourly' | 'daily' | 'weekly' | 'monthly' | 'two-month' | 'three-month' | 'four-month' | 'six-month' | 'yearly';
97
+ type TFrequency = "hourly" | "daily" | "weekly" | "monthly" | "two-month" | "three-month" | "four-month" | "six-month" | "yearly";
84
98
  export interface CustomLineItem {
85
99
  name?: string;
86
100
  imageUrl?: string | null;
@@ -134,11 +148,11 @@ interface TSetGiftCardOrCouponCodeParams {
134
148
  include?: string[];
135
149
  state?: OrderState;
136
150
  }
137
- export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state }: TSetGiftCardOrCouponCodeParams): Promise<{
151
+ export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state, }: TSetGiftCardOrCouponCodeParams): Promise<{
138
152
  success: boolean;
139
153
  order?: Order;
140
154
  }>;
141
- export type CodeType = 'coupon' | 'gift_card';
155
+ export type CodeType = "coupon" | "gift_card";
142
156
  export type OrderCodeType = `${CodeType}_code`;
143
157
  interface TRemoveGiftCardOrCouponCodeParams {
144
158
  codeType: OrderCodeType;
@@ -148,7 +162,7 @@ interface TRemoveGiftCardOrCouponCodeParams {
148
162
  include?: string[];
149
163
  state?: OrderState;
150
164
  }
151
- export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state }: TRemoveGiftCardOrCouponCodeParams): Promise<{
165
+ export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state, }: TRemoveGiftCardOrCouponCodeParams): Promise<{
152
166
  success: boolean;
153
167
  order?: Order;
154
168
  }>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
2
+ import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?getSdk(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=getErrors({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
@@ -1,17 +1,17 @@
1
- import type { AdyenPaymentConfig } from '../components/payment_source/AdyenPayment';
2
- import type { BraintreeConfig } from '../components/payment_source/BraintreePayment';
3
- import type { PaypalConfig } from '../components/payment_source/PaypalPayment';
4
- import type { StripeConfig } from '../components/payment_source/StripePayment';
5
- import type { WireTransferConfig } from '../components/payment_source/WireTransferPayment';
6
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
7
- import type { getOrderContext, updateOrder } from './OrderReducer';
8
- import type { BaseError } from '../typings/errors';
9
- import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from '@commercelayer/sdk';
10
- import type { Dispatch, MutableRefObject } from 'react';
11
- import type { CheckoutComConfig } from '../components/payment_source/CheckoutComPayment';
12
- import type { ExternalPaymentConfig } from '../components/payment_source/ExternalPayment';
13
- import type { ResourceKeys } from '../utils/getPaymentAttributes';
14
- export type PaymentSourceType = Order['payment_source'];
1
+ import type { AdyenPaymentConfig } from "../components/payment_source/AdyenPayment";
2
+ import type { BraintreeConfig } from "../components/payment_source/BraintreePayment";
3
+ import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
4
+ import type { StripeConfig } from "../components/payment_source/StripePayment";
5
+ import type { WireTransferConfig } from "../components/payment_source/WireTransferPayment";
6
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
7
+ import type { getOrderContext, updateOrder } from "./OrderReducer";
8
+ import type { BaseError } from "../typings/errors";
9
+ import type { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from "@commercelayer/sdk";
10
+ import type { Dispatch, MutableRefObject } from "react";
11
+ import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
12
+ import type { ExternalPaymentConfig } from "../components/payment_source/ExternalPayment";
13
+ import type { ResourceKeys } from "../utils/getPaymentAttributes";
14
+ export type PaymentSourceType = Order["payment_source"];
15
15
  interface Card {
16
16
  type: string;
17
17
  brand: string;
@@ -25,7 +25,7 @@ export interface PaymentSourceObject {
25
25
  payment_method?: Card;
26
26
  };
27
27
  payment_response?: {
28
- resultCode?: 'Authorised';
28
+ resultCode?: "Authorised";
29
29
  };
30
30
  };
31
31
  braintree_payments: BraintreePayment & {
@@ -43,13 +43,13 @@ export interface PaymentSourceObject {
43
43
  };
44
44
  payment_method?: {
45
45
  card: Card;
46
- type: string | 'klarna' | 'card';
46
+ type: string | "klarna" | "card";
47
47
  };
48
48
  };
49
49
  wire_transfers: WireTransfer;
50
50
  checkout_com_payments: CheckoutComPayment & {
51
51
  payment_response: {
52
- source?: Pick<Card, 'last4'> & {
52
+ source?: Pick<Card, "last4"> & {
53
53
  scheme: string;
54
54
  expiry_year: number;
55
55
  expiry_month: number;
@@ -58,7 +58,7 @@ export interface PaymentSourceObject {
58
58
  };
59
59
  klarna_payments: KlarnaPayment;
60
60
  }
61
- export type PaymentMethodActionType = 'setErrors' | 'setPaymentMethods' | 'setPaymentMethodConfig' | 'setPaymentSource' | 'setPaymentRef' | 'setLoading';
61
+ export type PaymentMethodActionType = "setErrors" | "setPaymentMethods" | "setPaymentMethodConfig" | "setPaymentSource" | "setPaymentRef" | "setLoading";
62
62
  export type PaymentRef = MutableRefObject<null | HTMLFormElement>;
63
63
  export interface PaymentMethodActionPayload {
64
64
  errors: BaseError[];
@@ -68,10 +68,10 @@ export interface PaymentMethodActionPayload {
68
68
  currentPaymentMethodRef: PaymentRef;
69
69
  currentCustomerPaymentSourceId: string | null;
70
70
  config: PaymentMethodConfig;
71
- paymentSource: Order['payment_source'] | null;
71
+ paymentSource: Order["payment_source"] | null;
72
72
  loading: boolean;
73
73
  }
74
- export declare function setLoading({ loading, dispatch }: {
74
+ export declare function setLoading({ loading, dispatch, }: {
75
75
  loading: boolean;
76
76
  dispatch?: Dispatch<PaymentMethodAction>;
77
77
  }): void;
@@ -94,8 +94,8 @@ type GetPaymentMethods = (args: {
94
94
  }) => Promise<void>;
95
95
  export declare const getPaymentMethods: GetPaymentMethods;
96
96
  export type PaymentResource = keyof PaymentSourceObject;
97
- export type PaymentResourceKey = 'braintreePayment' | 'stripePayment' | 'klarnaPayment' | 'wireTransfer' | 'paypalPayment' | 'adyenPayment' | 'checkoutComPayment';
98
- export type SDKPaymentResource = 'AdyenPayment' | 'BraintreePayment' | 'ExternalPayment' | 'PaypalPayment' | 'StripePayment' | 'WireTransfer' | 'CheckoutComPayment';
97
+ export type PaymentResourceKey = "braintreePayment" | "stripePayment" | "klarnaPayment" | "wireTransfer" | "paypalPayment" | "adyenPayment" | "checkoutComPayment";
98
+ export type SDKPaymentResource = "AdyenPayment" | "BraintreePayment" | "ExternalPayment" | "PaypalPayment" | "StripePayment" | "WireTransfer" | "CheckoutComPayment";
99
99
  interface TSetPaymentMethodParams {
100
100
  config?: CommerceLayerConfig;
101
101
  dispatch?: Dispatch<PaymentMethodAction>;
@@ -107,7 +107,7 @@ interface TSetPaymentMethodParams {
107
107
  paymentMethodId: string;
108
108
  paymentResource?: PaymentResource;
109
109
  }
110
- export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource }: TSetPaymentMethodParams): Promise<{
110
+ export declare function setPaymentMethod({ config, dispatch, order, paymentMethodId, updateOrder, setOrderErrors, paymentResource, }: TSetPaymentMethodParams): Promise<{
111
111
  success: boolean;
112
112
  order?: Order;
113
113
  }>;
@@ -116,7 +116,7 @@ export type SetPaymentSourceResponse = {
116
116
  order: Order;
117
117
  paymentSource: PaymentSourceTypes;
118
118
  } | null;
119
- export interface SetPaymentSourceParams extends Omit<PaymentMethodState, 'config'> {
119
+ export interface SetPaymentSourceParams extends Omit<PaymentMethodState, "config"> {
120
120
  config?: CommerceLayerConfig;
121
121
  dispatch?: Dispatch<PaymentMethodAction>;
122
122
  getOrder?: getOrderContext;
@@ -127,7 +127,7 @@ export interface SetPaymentSourceParams extends Omit<PaymentMethodState, 'config
127
127
  customerPaymentSourceId?: string;
128
128
  updateOrder?: typeof updateOrder;
129
129
  }
130
- export declare function setPaymentSource({ config, dispatch, getOrder, attributes, order, paymentResource, customerPaymentSourceId, paymentSourceId, updateOrder, errors: currentErrors }: SetPaymentSourceParams): Promise<PaymentSourceType | undefined | null>;
130
+ export declare function setPaymentSource({ config, dispatch, getOrder, attributes, order, paymentResource, customerPaymentSourceId, paymentSourceId, updateOrder, errors: currentErrors, }: SetPaymentSourceParams): Promise<PaymentSourceType | undefined | null>;
131
131
  export type UpdatePaymentSource = (args: {
132
132
  id: string;
133
133
  attributes: Record<string, any>;
@@ -149,7 +149,7 @@ export interface PaymentMethodConfig {
149
149
  braintreePayment?: BraintreeConfig;
150
150
  checkoutComPayment?: CheckoutComConfig;
151
151
  externalPayment?: ExternalPaymentConfig;
152
- klarnaPayment?: Pick<AdyenPaymentConfig, 'placeOrderCallback'> & Pick<StripeConfig, 'containerClassName'>;
152
+ klarnaPayment?: Pick<AdyenPaymentConfig, "placeOrderCallback"> & Pick<StripeConfig, "containerClassName">;
153
153
  paypalPayment?: PaypalConfig;
154
154
  stripePayment?: StripeConfig;
155
155
  wireTransfer?: Partial<WireTransferConfig>;