@commercelayer/react-components 4.19.0 → 4.20.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.
@@ -1,7 +1,7 @@
1
- import { type PropsWithoutRef, type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- import type { AddToCartReturn, CustomLineItem, LineItemOption } from '../../reducers/OrderReducer';
4
- interface TAddToCartButton extends Omit<Props, 'children'> {
1
+ import { type PropsWithoutRef, type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ import type { AddToCartReturn, CustomLineItem, LineItemOption } from "../../reducers/OrderReducer";
4
+ interface TAddToCartButton extends Omit<Props, "children"> {
5
5
  handleClick: () => AddToCartReturn;
6
6
  }
7
7
  type BuyNowMode = {
@@ -29,13 +29,13 @@ type THostedCart = {
29
29
  /**
30
30
  * If you have a self-hosted cart, you can pass the protocol to redirect to it.
31
31
  */
32
- protocol?: 'http' | 'https';
32
+ protocol?: "http" | "https";
33
33
  } | {
34
34
  redirectToHostedCart?: false;
35
35
  hostedCartUrl?: never;
36
36
  protocol?: never;
37
37
  };
38
- type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements['button'], 'children'>>;
38
+ type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements["button"], "children">>;
39
39
  type Props = {
40
40
  /**
41
41
  * Code of a bundle
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddToCartButton=AddToCartButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),ExternalFunctionContext_1=tslib_1.__importDefault(require("../../context/ExternalFunctionContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),getDomain_1=require("../../utils/getDomain"),events_1=require("../../utils/events"),organization_1=require("../../utils/organization");function AddToCartButton(props){var _a;const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https"}=props,p=tslib_1.__rest(props,["label","children","skuCode","bundleCode","skuListId","lineItem","buyNowMode","checkoutUrl","redirectToHostedCart","hostedCartUrl","quantity","lineItemOption","protocol"]),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=(0,react_1.useContext)(ExternalFunctionContext_1.default),{skuLists}=(0,react_1.useContext)(SkuListsContext_1.default),{sku}=(0,react_1.useContext)(SkuChildrenContext_1.default),sCode=(_a=sku?.code)!==null&&_a!==void 0?_a:skuCode,handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b,_c;const qty=quantity!=null?parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=(_a2=skuLists?.[skuListId])===null||_a2===void 0?void 0:_a2.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return yield callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),buyNowMode||(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=yield addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=(0,getDomain_1.getDomain)(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=yield(0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=(_c=(_b=config?.links)===null||_b===void 0?void 0:_b.cart)!==null&&_c!==void 0?_c:(0,getApplicationLink_1.getApplicationLink)({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return yield callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),buyNowMode||(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}),parentProps=Object.assign({handleClick,label},props);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({},p,{onClick:()=>{handleClick()},children:label}))}exports.default=AddToCartButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddToCartButton=AddToCartButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),SkuListsContext_1=tslib_1.__importDefault(require("../../context/SkuListsContext")),ExternalFunctionContext_1=tslib_1.__importDefault(require("../../context/ExternalFunctionContext")),SkuChildrenContext_1=tslib_1.__importDefault(require("../../context/SkuChildrenContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),getDomain_1=require("../../utils/getDomain"),events_1=require("../../utils/events"),organization_1=require("../../utils/organization");function AddToCartButton(props){var _a;const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https"}=props,p=tslib_1.__rest(props,["label","children","skuCode","bundleCode","skuListId","lineItem","buyNowMode","checkoutUrl","redirectToHostedCart","hostedCartUrl","quantity","lineItemOption","protocol"]),{accessToken,endpoint}=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=(0,useCustomContext_1.default)({context:OrderContext_1.default,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=(0,react_1.useContext)(ExternalFunctionContext_1.default),{skuLists}=(0,react_1.useContext)(SkuListsContext_1.default),{sku}=(0,react_1.useContext)(SkuChildrenContext_1.default),sCode=(_a=sku?.code)!==null&&_a!==void 0?_a:skuCode,handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b,_c;const qty=quantity!=null?Number.parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=(_a2=skuLists?.[skuListId])===null||_a2===void 0?void 0:_a2.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return yield callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),buyNowMode||(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=yield addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=(0,getDomain_1.getDomain)(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=yield(0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=(_c=(_b=config?.links)===null||_b===void 0?void 0:_b.cart)!==null&&_c!==void 0?_c:(0,getApplicationLink_1.getApplicationLink)({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return yield callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(res=>tslib_1.__awaiter(this,void 0,void 0,function*(){return getOrder&&orderId&&(yield getOrder(orderId)),buyNowMode||(0,events_1.publish)("open-cart"),res})).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}),parentProps=Object.assign({handleClick,label},props);return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({},p,{onClick:()=>{handleClick()},children:label}))}exports.default=AddToCartButton;
@@ -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
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent");function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.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()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e=options?.adyen)===null||_e===void 0)&&_e.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.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"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e;e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e=checkPaymentSource?.payment_response)===null||_e===void 0?void 0:_e.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield 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:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlaceOrderButton=PlaceOrderButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent");function PlaceOrderButton(props){var _a,_b,_c,_d;const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick}=props,p=tslib_1.__rest(props,["children","label","loadingLabel","autoPlaceOrder","disabled","onClick"]),{isPermitted,setPlaceOrder,options,paymentType,setButtonRef,setPlaceOrderStatus,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),[notPermitted,setNotPermitted]=(0,react_1.useState)(!0),[forceDisable,setForceDisable]=(0,react_1.useState)(disabled),[isLoading,setIsLoading]=(0,react_1.useState)(!1),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{var _a2;if(loading)setNotPermitted(loading);else if(paymentType===currentPaymentMethodType&&paymentType){const card=(0,getCardDetails_1.default)({customerPayment:{payment_source:paymentSource},paymentType});currentCustomerPaymentSourceId!=null&&paymentSource?.id===currentCustomerPaymentSourceId&&card.brand===""&&(card.brand="credit-card"),(isFree&&isPermitted||!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType,(_a=currentPaymentMethodRef?.current)===null||_a===void 0?void 0:_a.onsubmit,loading,currentPaymentMethodType,order,paymentSource]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2;if(paymentType==="stripe_payments"&&(!((_a2=options?.stripe)===null||_a2===void 0)&&_a2.paymentIntentClientSecret)&&(!((_b2=order?.payment_source)===null||_b2===void 0)&&_b2.publishable_key)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const publicApiKey=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.publishable_key,paymentIntentClientSecret=(_d2=options?.stripe)===null||_d2===void 0?void 0:_d2.paymentIntentClientSecret,getPaymentIntent=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const paymentIntentResult=yield(0,retrievePaymentIntent_1.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()}},[((_b=options?.stripe)===null||_b===void 0?void 0:_b.paymentIntentClientSecret)!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h,_j,_k,_l,_m;if(order?.status!=null&&["draft","pending"].includes(order?.status)){const resultCode=((_b2=(_a2=order?.payment_source)===null||_a2===void 0?void 0:_a2.payment_response)===null||_b2===void 0?void 0:_b2.resultCode)==="Authorised",paymentDetails=((_d2=(_c2=order?.payment_source)===null||_c2===void 0?void 0:_c2.payment_request_details)===null||_d2===void 0?void 0:_d2.details)!=null;if(paymentType==="adyen_payments"&&(!((_e=options?.adyen)===null||_e===void 0)&&_e.redirectResult)&&!paymentDetails){const attributes={payment_request_details:{details:{redirectResult:(_f=options?.adyen)===null||_f===void 0?void 0:_f.redirectResult}},_details:1};setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}).then(res=>{var _a3,_b3,_c3;const resultCode2=(_a3=res?.payment_response)===null||_a3===void 0?void 0:_a3.resultCode,errorCode=(_b3=res?.payment_response)===null||_b3===void 0?void 0:_b3.errorCode,message=(_c3=res?.payment_response)===null||_c3===void 0?void 0:_c3.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"&&(!((_g=options?.adyen)===null||_g===void 0)&&_g.MD)&&(!((_h=options?.adyen)===null||_h===void 0)&&_h.PaRes)&&autoPlaceOrder||paymentType==="adyen_payments"&&resultCode&&((_j=ref?.current)===null||_j===void 0?void 0:_j.disabled)===!1&&currentCustomerPaymentSourceId==null&&autoPlaceOrder&&status==="standby"&&!((_m=(_l=(_k=order?.payment_source)===null||_k===void 0?void 0:_k.payment_response)===null||_l===void 0?void 0:_l.merchantReference)===null||_m===void 0)&&_m.includes(order?.number))&&handleClick()}},[options?.adyen,paymentType,(_d=(_c=order?.payment_source)===null||_c===void 0?void 0:_c.payment_response)===null||_d===void 0?void 0:_d.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order,order?.payment_status,order?.status,paymentType,onClick]),(0,react_1.useEffect)(()=>{var _a2;paymentType==="checkout_com_payments"&&(!((_a2=options?.checkoutCom)===null||_a2===void 0)&&_a2.session_id)&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.checkoutCom,paymentType]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref]);const handleClick=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2,_d2,_e;e?.preventDefault(),e?.stopPropagation(),setIsLoading(!0);let isValid=!0;setForceDisable(!0);const checkPaymentSource=paymentType!=="stripe_payments"?yield setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({paymentType,customerPayment:{payment_source:checkPaymentSource}});!((_a2=currentPaymentMethodRef?.current)===null||_a2===void 0)&&_a2.onsubmit&&[!options?.paypalPayerId,!(!((_b2=options?.adyen)===null||_b2===void 0)&&_b2.MD),!(!((_c2=options?.checkoutCom)===null||_c2===void 0)&&_c2.session_id)].every(Boolean)?(isValid=yield(_d2=currentPaymentMethodRef.current)===null||_d2===void 0?void 0:_d2.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}),!isValid&&((_e=checkPaymentSource?.payment_response)===null||_e===void 0?void 0:_e.resultCode)==="Authorised"&&(isValid=!0)):card?.brand&&(isValid=!0),isValid&&setPlaceOrderStatus!=null&&setPlaceOrderStatus({status:"placing"});const placed=isValid&&setPlaceOrder&&(checkPaymentSource||isFree)&&(yield 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:(0,isFunction_1.default)(label)?label():label,parentProps=Object.assign(Object.assign({},p),{label,disabled:disabledButton,handleClick,parentRef:ref,isLoading});return children?(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children})):(0,jsx_runtime_1.jsx)("button",Object.assign({ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)}},p,{children:labelButton}))}exports.default=PlaceOrderButton;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),auto_1=require("@adyen/adyen-web/auto"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getPublicIp_1=require("../../utils/getPublicIp"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}=Object.assign(Object.assign({},defaultConfig),config),[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{placeOrderButtonRef,setPlaceOrder}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const savePaymentSourceToCustomerWallet=(_b=(_a=e?.elements)===null||_a===void 0?void 0:_a.save_payment_source_to_customer_wallet)===null||_b===void 0?void 0:_b.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1}),handleChange=state=>tslib_1.__awaiter(this,void 0,void 0,function*(){state.isValid&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}),setPaymentRef({ref}))}),handleOnAdditionalDetails=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&(yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes})),resultCode=(_a=pSource?.payment_response)===null||_a===void 0?void 0:_a.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=(_b=pSource?.payment_response)===null||_b===void 0?void 0:_b.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=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h;const url=(0,browserInfo_1.cleanUrlBy)(),shopperIp=yield(0,getPublicIp_1.getPublicIP)(),control=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=(_a=control?.payment_response)===null||_a===void 0?void 0:_a.resultCode;if(controlCode==="Authorised")return{resultCode:controlCode};const attributes={payment_request_data:Object.assign(Object.assign({},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:Object.assign({},(0,browserInfo_1.default)())})};delete attributes.payment_request_data.paymentMethod;try{if(yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=(_b=res?.payment_response)===null||_b===void 0?void 0:_b.action,resultCode=(_c=res?.payment_response)===null||_c===void 0?void 0:_c.resultCode;if(action!=null)return{resultCode,action};const issuerType=(_d=res?.payment_instrument)===null||_d===void 0?void 0:_d.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(yield 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=(_e=res?.payment_response)===null||_e===void 0?void 0:_e.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}if((_f=res?.payment_response)===null||_f===void 0?void 0:_f.errorType)if(((_g=res?.payment_response)===null||_g===void 0?void 0:_g.errorCode)==="14_006")onSubmit(state,component);else{const message=(_h=res?.payment_response)===null||_h===void 0?void 0:_h.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(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;const paymentMethodsResponse={paymentMethods:!((_a=paymentSource?.payment_methods)===null||_a===void 0)&&_a.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:!((_b=paymentSource?.payment_methods)===null||_b===void 0)&&_b.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=(_d=((_c=paymentSource?.payment_methods)===null||_c===void 0?void 0:_c.storedPaymentMethods)!=null)!==null&&_d!==void 0?_d:!1,options={locale:(_e=order?.language_code)!==null&&_e!==void 0?_e: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)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const{resultCode}=yield handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})}))()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2;const{resultCode,action}=yield onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?(_a2=dropinRef.current)===null||_a2===void 0||_a2.handleAction(action):actions.resolve({resultCode})}))()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2;const checkout2=yield(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:Object.assign({showStoredPaymentMethods,paypal:Object.assign({showPayButton:!0,style:styles?.paypal},(_a2=config?.paymentMethodsConfiguration)===null||_a2===void 0?void 0:_a2.paypal),card:Object.assign({enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1},(_b2=config?.paymentMethodsConfiguration)===null||_b2===void 0?void 0:_b2.card)},config?.paymentMethodsConfiguration),onDisableStoredPaymentMethod:state=>{var _a3;const recurringDetailReference=state,shopperReference=(_a3=customers?.shopper_reference)!==null&&_a3!==void 0?_a3: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=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield 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:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),auto_1=require("@adyen/adyen-web/auto"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),getPublicIp_1=require("../../utils/getPublicIp"),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}=Object.assign(Object.assign({},defaultConfig),config),[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder}=(0,react_1.useContext)(OrderContext_1.default),{placeOrderButtonRef,setPlaceOrder}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const savePaymentSourceToCustomerWallet=(_b=(_a=e?.elements)===null||_a===void 0?void 0:_a.save_payment_source_to_customer_wallet)===null||_b===void 0?void 0:_b.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1}),handleChange=state=>tslib_1.__awaiter(this,void 0,void 0,function*(){state.isValid&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit(ref.current)}),setPaymentRef({ref}))}),handleOnAdditionalDetails=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b;const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&(yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes})),resultCode=(_a=pSource?.payment_response)===null||_a===void 0?void 0:_a.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=(_b=pSource?.payment_response)===null||_b===void 0?void 0:_b.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=(state,component)=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=yield(0,getPublicIp_1.getPublicIP)(),control=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=(_a=control?.payment_response)===null||_a===void 0?void 0:_a.resultCode,paymentMethodType=(_c=(_b=control?.payment_response)===null||_b===void 0?void 0:_b.paymentMethod)===null||_c===void 0?void 0:_c.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:Object.assign(Object.assign({},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:Object.assign({},(0,browserInfo_1.default)())})};delete attributes.payment_request_data.paymentMethod;try{if(yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(controlCode==="Authorised"&&paymentMethodType==="giftcard")return yield updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2};if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}});if(["Cancelled","Refused"].includes((_d=firstAuthorization?.payment_response)===null||_d===void 0?void 0:_d.resultCode)){const availableGiftCardAmount=(_f=(_e=firstAuthorization?.payment_response)===null||_e===void 0?void 0:_e.additionalData)===null||_f===void 0?void 0:_f.currentBalanceValue;return yield updateOrder({id:order.id,attributes:{_authorization_amount_cents:Number.parseInt(availableGiftCardAmount),_place:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=yield setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=(_g=res?.payment_response)===null||_g===void 0?void 0:_g.action,resultCode=(_h=res?.payment_response)===null||_h===void 0?void 0:_h.resultCode;if(action!=null)return{resultCode,action};const issuerType=(_j=res?.payment_instrument)===null||_j===void 0?void 0:_j.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(yield 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=(_k=res?.payment_response)===null||_k===void 0?void 0:_k.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if((_l=res?.payment_response)===null||_l===void 0?void 0:_l.errorType)if(((_m=res?.payment_response)===null||_m===void 0?void 0:_m.errorCode)==="14_006")onSubmit(state,component);else{const message=(_o=res?.payment_response)===null||_o===void 0?void 0:_o.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(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;const paymentMethodsResponse={paymentMethods:!((_a=paymentSource?.payment_methods)===null||_a===void 0)&&_a.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:!((_b=paymentSource?.payment_methods)===null||_b===void 0)&&_b.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=(_d=((_c=paymentSource?.payment_methods)===null||_c===void 0?void 0:_c.storedPaymentMethods)!=null)!==null&&_d!==void 0?_d:!1,options={locale:(_e=order?.language_code)!==null&&_e!==void 0?_e: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)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){const{resultCode}=yield handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})}))()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2;const{resultCode,action}=yield onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?(_a2=dropinRef.current)===null||_a2===void 0||_a2.handleAction(action):(actions.resolve({resultCode}),(_b2=dropinRef.current)===null||_b2===void 0||_b2.mount("#adyen-dropin"))}))()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b2,_c2;const checkout2=yield(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:Object.assign({showStoredPaymentMethods,paypal:Object.assign({showPayButton:!0,style:styles?.paypal},(_a2=config?.paymentMethodsConfiguration)===null||_a2===void 0?void 0:_a2.paypal),card:Object.assign({enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1},(_b2=config?.paymentMethodsConfiguration)===null||_b2===void 0?void 0:_b2.card),giftcard:Object.assign({showPayButton:!0},(_c2=config?.paymentMethodsConfiguration)===null||_c2===void 0?void 0:_c2.giftcard)},config?.paymentMethodsConfiguration),onDisableStoredPaymentMethod:state=>{var _a3;const recurringDetailReference=state,shopperReference=(_a3=customers?.shopper_reference)!==null&&_a3!==void 0?_a3: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=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield 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:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
@@ -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>;
@@ -1,9 +1,9 @@
1
- import type { Dispatch, RefObject } from 'react';
2
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
3
- import type { BaseError } from '../typings/errors';
4
- import type { Order } from '@commercelayer/sdk';
5
- import type { PaymentResource, PaymentSourceType } from './PaymentMethodReducer';
6
- export type PlaceOrderActionType = 'setErrors' | 'setPlaceOrderPermitted' | 'setButtonRef' | 'setStatus';
1
+ import type { Dispatch, RefObject } from "react";
2
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
3
+ import type { BaseError } from "../typings/errors";
4
+ import type { Order } from "@commercelayer/sdk";
5
+ import type { PaymentResource, PaymentSourceType } from "./PaymentMethodReducer";
6
+ export type PlaceOrderActionType = "setErrors" | "setPlaceOrderPermitted" | "setButtonRef" | "setStatus";
7
7
  export interface PlaceOrderOptions {
8
8
  paypalPayerId?: string;
9
9
  adyen?: {
@@ -32,7 +32,7 @@ export interface PlaceOrderActionPayload {
32
32
  paymentSource: PaymentSourceType;
33
33
  options?: PlaceOrderOptions;
34
34
  placeOrderButtonRef?: RefObject<HTMLButtonElement | null>;
35
- status: 'placing' | 'standby';
35
+ status: "placing" | "standby";
36
36
  }
37
37
  export declare function setButtonRef(ref: RefObject<HTMLButtonElement | null>, dispatch: Dispatch<PlaceOrderAction>): void;
38
38
  export type PlaceOrderState = Partial<PlaceOrderActionPayload>;
@@ -48,7 +48,7 @@ interface TPlaceOrderPermittedParams {
48
48
  order?: Order;
49
49
  options?: PlaceOrderOptions;
50
50
  }
51
- export declare function placeOrderPermitted({ config, order, dispatch, options }: TPlaceOrderPermittedParams): void;
51
+ export declare function placeOrderPermitted({ config, order, dispatch, options, }: TPlaceOrderPermittedParams): void;
52
52
  interface TSetPlaceOrderParams {
53
53
  config?: CommerceLayerConfig;
54
54
  order?: Order;
@@ -59,13 +59,13 @@ interface TSetPlaceOrderParams {
59
59
  setOrder?: (order: Order) => void;
60
60
  currentCustomerPaymentSourceId?: string | null;
61
61
  }
62
- export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId }: TSetPlaceOrderParams): Promise<{
62
+ export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId, }: TSetPlaceOrderParams): Promise<{
63
63
  placed: boolean;
64
64
  errors?: BaseError[];
65
65
  order?: Order;
66
66
  }>;
67
- export declare function setPlaceOrderStatus({ status, dispatch }: {
68
- status: 'placing' | 'standby';
67
+ export declare function setPlaceOrderStatus({ status, dispatch, }: {
68
+ status: "placing" | "standby";
69
69
  dispatch?: Dispatch<PlaceOrderAction>;
70
70
  }): void;
71
71
  declare const placeOrderReducer: (state: PlaceOrderState, reducer: PlaceOrderAction) => PlaceOrderState;
@@ -1,7 +1,7 @@
1
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
2
- import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from '@commercelayer/sdk';
3
- import type { PaymentRequestShippingOption } from '@stripe/stripe-js';
4
- import type { PaymentResource } from '../reducers/PaymentMethodReducer';
1
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
2
+ import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from "@commercelayer/sdk";
3
+ import type { PaymentRequestShippingOption } from "@stripe/stripe-js";
4
+ import type { PaymentResource } from "../reducers/PaymentMethodReducer";
5
5
  export declare function getAvailableExpressPayments(paymentMethods: PaymentMethod[]): PaymentMethod[];
6
6
  interface TFakeAddressParams {
7
7
  /**
@@ -21,7 +21,7 @@ interface TFakeAddressParams {
21
21
  */
22
22
  email?: string;
23
23
  }
24
- export declare function setExpressFakeAddress({ orderId, config, address, email }: TFakeAddressParams): Promise<Order>;
24
+ export declare function setExpressFakeAddress({ orderId, config, address, email, }: TFakeAddressParams): Promise<Order>;
25
25
  export declare function getExpressShippingMethods(order: Order): PaymentRequestShippingOption[] | null;
26
26
  type TSetExpressShippingMethodParams = {
27
27
  /**
@@ -49,7 +49,7 @@ type TSetExpressShippingMethodParams = {
49
49
  selectFirst?: true;
50
50
  selectedShippingMethodId?: never;
51
51
  });
52
- export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params }: TSetExpressShippingMethodParams): Promise<Order>;
52
+ export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params, }: TSetExpressShippingMethodParams): Promise<Order>;
53
53
  export type TSetExpressPlaceOrderParams = {
54
54
  /**
55
55
  * The Commerce Layer config
@@ -77,7 +77,7 @@ export type TSetExpressPlaceOrderParams = {
77
77
  paymentSourceId?: never;
78
78
  placeTheOrder?: true;
79
79
  });
80
- export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder }: TSetExpressPlaceOrderParams): Promise<Order>;
80
+ export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder, }: TSetExpressPlaceOrderParams): Promise<Order>;
81
81
  interface TExpressRedirectUrlParams {
82
82
  /**
83
83
  * Order resource
@@ -88,5 +88,5 @@ interface TExpressRedirectUrlParams {
88
88
  */
89
89
  config: CommerceLayerConfig;
90
90
  }
91
- export declare function expressRedirectUrl({ order, config: { accessToken, endpoint } }: TExpressRedirectUrlParams): void;
91
+ export declare function expressRedirectUrl({ order, config: { accessToken, endpoint }, }: TExpressRedirectUrlParams): void;
92
92
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});{if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{var _a2;if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push((_a2=firstMethod.price_amount_for_shipment_cents)!==null&&_a2!==void 0?_a2:0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}}function setExpressShippingMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _b,_c,_d;const sdk=(0,getSdk_1.default)(config),order=yield sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}else selectedShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)}));else for(const shipment of(_b=order?.shipments)!==null&&_b!==void 0?_b:[]){const[firstShippingMethodId]=(_d=(_c=shipment?.available_shipping_methods)===null||_c===void 0?void 0:_c.map(method=>method.id))!==null&&_d!==void 0?_d:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}function setExpressPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=(0,getSdk_1.default)(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return yield sdk.orders.retrieve(orderId,{include}),yield sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),yield sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),yield sdk[paymentResource].update({id:paymentSourceId,_update:!0}),yield sdk.orders.retrieve(orderId,{include})}return yield sdk.orders.update({id:orderId,_place:!0})})}function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;window.location.pathname.includes("/checkout")||window.location.pathname.includes(`/${order.id}`)?window.location.reload():window.location.href=href}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{var _a2;if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push((_a2=firstMethod.price_amount_for_shipment_cents)!==null&&_a2!==void 0?_a2:0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}function setExpressShippingMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _b,_c,_d;const sdk=(0,getSdk_1.default)(config),order=yield sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}else selectedShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)}));else for(const shipment of(_b=order?.shipments)!==null&&_b!==void 0?_b:[]){const[firstShippingMethodId]=(_d=(_c=shipment?.available_shipping_methods)===null||_c===void 0?void 0:_c.map(method=>method.id))!==null&&_d!==void 0?_d:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}function setExpressPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=(0,getSdk_1.default)(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return yield sdk.orders.retrieve(orderId,{include}),yield sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),yield sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),yield sdk[paymentResource].update({id:paymentSourceId,_update:!0}),yield sdk.orders.retrieve(orderId,{include})}return yield sdk.orders.update({id:orderId,_place:!0})})}function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;!window.location.pathname.includes("/cart")?window.location.reload():window.top!=null&&(window.top.location.href=href)}
@@ -1,7 +1,7 @@
1
- import { type PropsWithoutRef, type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- import type { AddToCartReturn, CustomLineItem, LineItemOption } from '../../reducers/OrderReducer';
4
- interface TAddToCartButton extends Omit<Props, 'children'> {
1
+ import { type PropsWithoutRef, type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ import type { AddToCartReturn, CustomLineItem, LineItemOption } from "../../reducers/OrderReducer";
4
+ interface TAddToCartButton extends Omit<Props, "children"> {
5
5
  handleClick: () => AddToCartReturn;
6
6
  }
7
7
  type BuyNowMode = {
@@ -29,13 +29,13 @@ type THostedCart = {
29
29
  /**
30
30
  * If you have a self-hosted cart, you can pass the protocol to redirect to it.
31
31
  */
32
- protocol?: 'http' | 'https';
32
+ protocol?: "http" | "https";
33
33
  } | {
34
34
  redirectToHostedCart?: false;
35
35
  hostedCartUrl?: never;
36
36
  protocol?: never;
37
37
  };
38
- type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements['button'], 'children'>>;
38
+ type TButton = PropsWithoutRef<Omit<JSX.IntrinsicElements["button"], "children">>;
39
39
  type Props = {
40
40
  /**
41
41
  * Code of a bundle
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import{getApplicationLink}from"../../utils/getApplicationLink";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";import{getOrganizationConfig}from"../../utils/organization";export function AddToCartButton(props){const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https",...p}=props,{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=useContext(ExternalFunctionContext),{skuLists}=useContext(SkuListsContext),{sku}=useContext(SkuChildrenContext),sCode=sku?.code??skuCode,handleClick=async()=>{const qty=quantity!=null?parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=skuLists?.[skuListId]?.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return await callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=await addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=getDomain(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=config?.links?.cart??getApplicationLink({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return await callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))},parentProps={handleClick,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{...p,onClick:()=>{handleClick()},children:label})}export default AddToCartButton;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import SkuListsContext from"../../context/SkuListsContext";import ExternalFunctionContext from"../../context/ExternalFunctionContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import{getApplicationLink}from"../../utils/getApplicationLink";import CommerceLayerContext from"../../context/CommerceLayerContext";import useCustomContext from"../../utils/hooks/useCustomContext";import{getDomain}from"../../utils/getDomain";import{publish}from"../../utils/events";import{getOrganizationConfig}from"../../utils/organization";export function AddToCartButton(props){const{label="Add to cart",children,skuCode,bundleCode,skuListId,lineItem,buyNowMode=!1,checkoutUrl,redirectToHostedCart,hostedCartUrl,quantity,lineItemOption,protocol="https",...p}=props,{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AddToCartButton",key:"accessToken"}),{addToCart,orderId,getOrder,setOrderErrors}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"AddToCartButton",key:"addToCart"}),{url,callExternalFunction}=useContext(ExternalFunctionContext),{skuLists}=useContext(SkuListsContext),{sku}=useContext(SkuChildrenContext),sCode=sku?.code??skuCode,handleClick=async()=>{const qty=quantity!=null?Number.parseInt(quantity):1;if(skuLists!=null&&skuListId&&url&&skuListId in skuLists){const lineItems=skuLists?.[skuListId]?.map(skuCode2=>({skuCode:skuCode2,quantity:qty,_update_quantity:1}));return await callExternalFunction({url,data:{resourceType:"orders",inputs:[{id:orderId,lineItems}]}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))}if(!url&&addToCart!=null){const res=await addToCart({bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl});if(redirectToHostedCart&&accessToken!=null&&endpoint!=null){const{slug,domain}=getDomain(endpoint),orderId2=res?.orderId;if(hostedCartUrl&&orderId2)location.href=`${protocol}://${hostedCartUrl}/${orderId2}?accessToken=${accessToken}`;else if(orderId2&&slug){const config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:orderId2,accessToken,slug}});location.href=config?.links?.cart??getApplicationLink({orderId:orderId2,slug,accessToken,domain,applicationType:"cart"})}}return res}else if(url)return await callExternalFunction({url,data:{bundleCode,skuCode:sCode,quantity:qty,lineItemOption,lineItem,buyNowMode,checkoutUrl}}).then(async res=>(getOrder&&orderId&&await getOrder(orderId),buyNowMode||publish("open-cart"),res)).catch(({response})=>(setOrderErrors&&setOrderErrors(response.data),response))},parentProps={handleClick,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{...p,onClick:()=>{handleClick()},children:label})}export default AddToCartButton;
@@ -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,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"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.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(controlCode==="Authorised"&&paymentMethodType==="giftcard")return 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}});if(["Cancelled","Refused"].includes(firstAuthorization?.payment_response?.resultCode)){const availableGiftCardAmount=firstAuthorization?.payment_response?.additionalData?.currentBalanceValue;return await updateOrder({id:order.id,attributes:{_authorization_amount_cents:Number.parseInt(availableGiftCardAmount),_place:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}return{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,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>;
@@ -1,9 +1,9 @@
1
- import type { Dispatch, RefObject } from 'react';
2
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
3
- import type { BaseError } from '../typings/errors';
4
- import type { Order } from '@commercelayer/sdk';
5
- import type { PaymentResource, PaymentSourceType } from './PaymentMethodReducer';
6
- export type PlaceOrderActionType = 'setErrors' | 'setPlaceOrderPermitted' | 'setButtonRef' | 'setStatus';
1
+ import type { Dispatch, RefObject } from "react";
2
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
3
+ import type { BaseError } from "../typings/errors";
4
+ import type { Order } from "@commercelayer/sdk";
5
+ import type { PaymentResource, PaymentSourceType } from "./PaymentMethodReducer";
6
+ export type PlaceOrderActionType = "setErrors" | "setPlaceOrderPermitted" | "setButtonRef" | "setStatus";
7
7
  export interface PlaceOrderOptions {
8
8
  paypalPayerId?: string;
9
9
  adyen?: {
@@ -32,7 +32,7 @@ export interface PlaceOrderActionPayload {
32
32
  paymentSource: PaymentSourceType;
33
33
  options?: PlaceOrderOptions;
34
34
  placeOrderButtonRef?: RefObject<HTMLButtonElement | null>;
35
- status: 'placing' | 'standby';
35
+ status: "placing" | "standby";
36
36
  }
37
37
  export declare function setButtonRef(ref: RefObject<HTMLButtonElement | null>, dispatch: Dispatch<PlaceOrderAction>): void;
38
38
  export type PlaceOrderState = Partial<PlaceOrderActionPayload>;
@@ -48,7 +48,7 @@ interface TPlaceOrderPermittedParams {
48
48
  order?: Order;
49
49
  options?: PlaceOrderOptions;
50
50
  }
51
- export declare function placeOrderPermitted({ config, order, dispatch, options }: TPlaceOrderPermittedParams): void;
51
+ export declare function placeOrderPermitted({ config, order, dispatch, options, }: TPlaceOrderPermittedParams): void;
52
52
  interface TSetPlaceOrderParams {
53
53
  config?: CommerceLayerConfig;
54
54
  order?: Order;
@@ -59,13 +59,13 @@ interface TSetPlaceOrderParams {
59
59
  setOrder?: (order: Order) => void;
60
60
  currentCustomerPaymentSourceId?: string | null;
61
61
  }
62
- export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId }: TSetPlaceOrderParams): Promise<{
62
+ export declare function setPlaceOrder({ state, order, config, setOrderErrors, paymentSource, setOrder, include, currentCustomerPaymentSourceId, }: TSetPlaceOrderParams): Promise<{
63
63
  placed: boolean;
64
64
  errors?: BaseError[];
65
65
  order?: Order;
66
66
  }>;
67
- export declare function setPlaceOrderStatus({ status, dispatch }: {
68
- status: 'placing' | 'standby';
67
+ export declare function setPlaceOrderStatus({ status, dispatch, }: {
68
+ status: "placing" | "standby";
69
69
  dispatch?: Dispatch<PlaceOrderAction>;
70
70
  }): void;
71
71
  declare const placeOrderReducer: (state: PlaceOrderState, reducer: PlaceOrderAction) => PlaceOrderState;
@@ -1,7 +1,7 @@
1
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
2
- import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from '@commercelayer/sdk';
3
- import type { PaymentRequestShippingOption } from '@stripe/stripe-js';
4
- import type { PaymentResource } from '../reducers/PaymentMethodReducer';
1
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
2
+ import type { Order, PaymentMethod, QueryParamsRetrieve, AddressCreate } from "@commercelayer/sdk";
3
+ import type { PaymentRequestShippingOption } from "@stripe/stripe-js";
4
+ import type { PaymentResource } from "../reducers/PaymentMethodReducer";
5
5
  export declare function getAvailableExpressPayments(paymentMethods: PaymentMethod[]): PaymentMethod[];
6
6
  interface TFakeAddressParams {
7
7
  /**
@@ -21,7 +21,7 @@ interface TFakeAddressParams {
21
21
  */
22
22
  email?: string;
23
23
  }
24
- export declare function setExpressFakeAddress({ orderId, config, address, email }: TFakeAddressParams): Promise<Order>;
24
+ export declare function setExpressFakeAddress({ orderId, config, address, email, }: TFakeAddressParams): Promise<Order>;
25
25
  export declare function getExpressShippingMethods(order: Order): PaymentRequestShippingOption[] | null;
26
26
  type TSetExpressShippingMethodParams = {
27
27
  /**
@@ -49,7 +49,7 @@ type TSetExpressShippingMethodParams = {
49
49
  selectFirst?: true;
50
50
  selectedShippingMethodId?: never;
51
51
  });
52
- export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params }: TSetExpressShippingMethodParams): Promise<Order>;
52
+ export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params, }: TSetExpressShippingMethodParams): Promise<Order>;
53
53
  export type TSetExpressPlaceOrderParams = {
54
54
  /**
55
55
  * The Commerce Layer config
@@ -77,7 +77,7 @@ export type TSetExpressPlaceOrderParams = {
77
77
  paymentSourceId?: never;
78
78
  placeTheOrder?: true;
79
79
  });
80
- export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder }: TSetExpressPlaceOrderParams): Promise<Order>;
80
+ export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder, }: TSetExpressPlaceOrderParams): Promise<Order>;
81
81
  interface TExpressRedirectUrlParams {
82
82
  /**
83
83
  * Order resource
@@ -88,5 +88,5 @@ interface TExpressRedirectUrlParams {
88
88
  */
89
89
  config: CommerceLayerConfig;
90
90
  }
91
- export declare function expressRedirectUrl({ order, config: { accessToken, endpoint } }: TExpressRedirectUrlParams): void;
91
+ export declare function expressRedirectUrl({ order, config: { accessToken, endpoint }, }: TExpressRedirectUrlParams): void;
92
92
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import getSdk from"./getSdk";import{getDomain}from"./getDomain";const availablePaymentMethods=["stripe_payments"];export function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}export async function setExpressFakeAddress({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=getSdk(config),fakeAddress=await sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),await sdk.orders.update(resource,params),await sdk.orders.retrieve(orderId,params)}export function getExpressShippingMethods(order){const isSingleShipment=order?.shipments?.length===1,shippingMethods=order?.shipments?.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>({id:method?.id??"",label:method?.name??"",amount:method?.price_amount_for_shipment_cents??0,detail:""}));{if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push(firstMethod.price_amount_for_shipment_cents??0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}}export async function setExpressShippingMethod({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){const sdk=getSdk(config),order=await sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}else selectedShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)});else for(const shipment of order?.shipments??[]){const[firstShippingMethodId]=shipment?.available_shipping_methods?.map(method=>method.id)??[];firstShippingMethodId!=null&&await sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}return await sdk.orders.retrieve(order.id,params)}export async function setExpressPlaceOrder({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=getSdk(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return await sdk.orders.retrieve(orderId,{include}),await sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),await sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),await sdk[paymentResource].update({id:paymentSourceId,_update:!0}),await sdk.orders.retrieve(orderId,{include})}return await sdk.orders.update({id:orderId,_place:!0})}export function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=getDomain(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;window.location.pathname.includes("/checkout")||window.location.pathname.includes(`/${order.id}`)?window.location.reload():window.location.href=href}
2
+ import getSdk from"./getSdk";import{getDomain}from"./getDomain";const availablePaymentMethods=["stripe_payments"];export function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}export async function setExpressFakeAddress({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=getSdk(config),fakeAddress=await sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),await sdk.orders.update(resource,params),await sdk.orders.retrieve(orderId,params)}export function getExpressShippingMethods(order){const isSingleShipment=order?.shipments?.length===1,shippingMethods=order?.shipments?.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>({id:method?.id??"",label:method?.name??"",amount:method?.price_amount_for_shipment_cents??0,detail:""}));if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push(firstMethod.price_amount_for_shipment_cents??0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}export async function setExpressShippingMethod({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){const sdk=getSdk(config),order=await sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}else selectedShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)});else for(const shipment of order?.shipments??[]){const[firstShippingMethodId]=shipment?.available_shipping_methods?.map(method=>method.id)??[];firstShippingMethodId!=null&&await sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}return await sdk.orders.retrieve(order.id,params)}export async function setExpressPlaceOrder({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=getSdk(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return await sdk.orders.retrieve(orderId,{include}),await sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),await sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),await sdk[paymentResource].update({id:paymentSourceId,_update:!0}),await sdk.orders.retrieve(orderId,{include})}return await sdk.orders.update({id:orderId,_place:!0})}export function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=getDomain(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;!window.location.pathname.includes("/cart")?window.location.reload():window.top!=null&&(window.top.location.href=href)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.19.0",
3
+ "version": "4.20.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",
@@ -187,13 +187,13 @@
187
187
  "homepage": "https://github.com/commercelayer/commercelayer-react-components#readme",
188
188
  "dependencies": {
189
189
  "@adyen/adyen-web": "^6.8.0",
190
- "@commercelayer/organization-config": "^2.0.0",
191
- "@commercelayer/sdk": "^6.29.1",
190
+ "@commercelayer/organization-config": "^2.1.0",
191
+ "@commercelayer/sdk": "^6.32.0",
192
192
  "@stripe/react-stripe-js": "^3.1.1",
193
- "@stripe/stripe-js": "^5.5.0",
194
- "@tanstack/react-table": "^8.20.6",
193
+ "@stripe/stripe-js": "^5.6.0",
194
+ "@tanstack/react-table": "^8.21.2",
195
195
  "@types/iframe-resizer": "^3.5.13",
196
- "braintree-web": "^3.115.0",
196
+ "braintree-web": "^3.115.2",
197
197
  "frames-react": "^1.2.2",
198
198
  "iframe-resizer": "^4.3.6",
199
199
  "jwt-decode": "^4.0.0",
@@ -201,20 +201,20 @@
201
201
  "rapid-form": "2.1.0"
202
202
  },
203
203
  "devDependencies": {
204
- "@commercelayer/js-auth": "^6.7.0",
205
- "@faker-js/faker": "^9.4.0",
206
- "@playwright/test": "^1.50.0",
204
+ "@commercelayer/js-auth": "^6.7.1",
205
+ "@faker-js/faker": "^9.5.0",
206
+ "@playwright/test": "^1.50.1",
207
207
  "@testing-library/dom": "^10.4.0",
208
208
  "@testing-library/react": "^16.2.0",
209
209
  "@types/braintree-web": "^3.96.16",
210
210
  "@types/lodash": "^4.17.15",
211
- "@types/node": "^22.12.0",
211
+ "@types/node": "^22.13.4",
212
212
  "@types/prop-types": "^15.7.14",
213
213
  "@types/react": "^18.3.1",
214
214
  "@types/react-test-renderer": "^18.3.1",
215
215
  "@types/react-window": "^1.8.8",
216
216
  "@vitejs/plugin-react": "^4.3.4",
217
- "@vitest/coverage-v8": "^3.0.4",
217
+ "@vitest/coverage-v8": "^3.0.6",
218
218
  "jsdom": "^26.0.0",
219
219
  "minimize-js": "^1.4.0",
220
220
  "msw": "^2.7.0",
@@ -224,9 +224,9 @@
224
224
  "tsc-alias": "^1.8.10",
225
225
  "tslib": "^2.8.1",
226
226
  "typescript": "^5.7.3",
227
- "vite": "^6.0.11",
227
+ "vite": "^6.1.0",
228
228
  "vite-tsconfig-paths": "^5.1.4",
229
- "vitest": "^3.0.4"
229
+ "vitest": "^3.0.6"
230
230
  },
231
231
  "peerDependencies": {
232
232
  "react": ">=18.0.0"