@commercelayer/react-components 4.22.0-beta.0 → 4.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
  2. package/lib/cjs/components/orders/PlaceOrderContainer.d.ts +2 -2
  3. package/lib/cjs/components/payment_gateways/PaymentGateway.d.ts +3 -3
  4. package/lib/cjs/components/payment_gateways/PaymentGateway.js +1 -1
  5. package/lib/cjs/components/payment_methods/PaymentMethod.d.ts +8 -8
  6. package/lib/cjs/components/payment_methods/PaymentMethod.js +1 -1
  7. package/lib/cjs/components/payment_source/CheckoutComPayment.d.ts +52 -10
  8. package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
  9. package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
  10. package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
  11. package/lib/cjs/utils/getCardDetails.js +1 -1
  12. package/lib/cjs/utils/getPaymentAttributes.d.ts +12 -10
  13. package/lib/cjs/utils/getPaymentAttributes.js +1 -1
  14. package/lib/cjs/utils/snakeToCamelCase.d.ts +9 -0
  15. package/lib/cjs/utils/snakeToCamelCase.js +1 -1
  16. package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
  17. package/lib/esm/components/orders/PlaceOrderContainer.d.ts +2 -2
  18. package/lib/esm/components/payment_gateways/PaymentGateway.d.ts +3 -3
  19. package/lib/esm/components/payment_gateways/PaymentGateway.js +1 -1
  20. package/lib/esm/components/payment_methods/PaymentMethod.d.ts +8 -8
  21. package/lib/esm/components/payment_methods/PaymentMethod.js +1 -1
  22. package/lib/esm/components/payment_source/CheckoutComPayment.d.ts +52 -10
  23. package/lib/esm/components/payment_source/CheckoutComPayment.js +1 -1
  24. package/lib/esm/reducers/PaymentMethodReducer.js +1 -1
  25. package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
  26. package/lib/esm/utils/getCardDetails.js +1 -1
  27. package/lib/esm/utils/getPaymentAttributes.d.ts +12 -10
  28. package/lib/esm/utils/getPaymentAttributes.js +1 -1
  29. package/lib/esm/utils/snakeToCamelCase.d.ts +9 -0
  30. package/lib/esm/utils/snakeToCamelCase.js +1 -1
  31. package/package.json +1 -1
@@ -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)(()=>{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;
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;if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}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,5 +1,5 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import { type PlaceOrderOptions } from '../../reducers/PlaceOrderReducer';
1
+ import { type ReactNode, type JSX } from "react";
2
+ import { type PlaceOrderOptions } from "../../reducers/PlaceOrderReducer";
3
3
  interface Props {
4
4
  children: ReactNode;
5
5
  options?: PlaceOrderOptions;
@@ -1,6 +1,6 @@
1
- import type { LoaderType } from '../../typings/index';
2
- import { type JSX } from 'react';
3
- import type { PaymentSourceProps } from '../payment_source/PaymentSource';
1
+ import type { LoaderType } from "../../typings/index";
2
+ import { type JSX } from "react";
3
+ import type { PaymentSourceProps } from "../payment_source/PaymentSource";
4
4
  export type GatewayBaseType = Props & {
5
5
  show: boolean;
6
6
  loading: boolean;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_1=require("react"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext"));function PaymentGateway(_a){var _b,{readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading..."}=_a,p=tslib_1.__rest(_a,["readonly","showCard","handleEditClick","children","templateCustomerCards","templateCustomerSaveToWallet","onClickCustomerCards","show","loader"]);const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{var _a2,_b2,_c;if(payment?.id===currentPaymentMethodId&&paymentResource&&((_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.payment_source_type)===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href));const setPaymentSources=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){order!=null&&(yield setPaymentSource({paymentResource,order,attributes})),getCustomerPaymentSources&&getCustomerPaymentSources()});(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),((_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.id)!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&((_c=order?.payment_source)===null||_c===void 0?void 0:_c.id)!=null&&setLoading(!1),()=>{setLoading(!0)}},[(_b=order?.payment_method)===null||_b===void 0?void 0:_b.id,show,paymentSource]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status]);const gatewayConfig=Object.assign({readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet},p);if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,Object.assign({},gatewayConfig,{children}));case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,Object.assign({},gatewayConfig,{children}));case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,Object.assign({},gatewayConfig,{children}));case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,Object.assign({},gatewayConfig,{children}));case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,Object.assign({},gatewayConfig,{children}));case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,Object.assign({},gatewayConfig,{children}));case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,Object.assign({},gatewayConfig,{children}));case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,Object.assign({},gatewayConfig,{children}));default:return null}}exports.default=PaymentGateway;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentGateway=PaymentGateway;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_1=require("react"),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),AdyenGateway_1=tslib_1.__importDefault(require("./AdyenGateway")),StripeGateway_1=tslib_1.__importDefault(require("./StripeGateway")),BraintreeGateway_1=tslib_1.__importDefault(require("./BraintreeGateway")),PaypalGateway_1=tslib_1.__importDefault(require("./PaypalGateway")),WireTransferGateway_1=tslib_1.__importDefault(require("./WireTransferGateway")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),CheckoutComGateway_1=tslib_1.__importDefault(require("./CheckoutComGateway")),KlarnaGateway_1=tslib_1.__importDefault(require("./KlarnaGateway")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),ExternalGateway_1=tslib_1.__importDefault(require("./ExternalGateway")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext"));function PaymentGateway(_a){var _b,{readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading..."}=_a,p=tslib_1.__rest(_a,["readonly","showCard","handleEditClick","children","templateCustomerCards","templateCustomerSaveToWallet","onClickCustomerCards","show","loader"]);const loaderComponent=(0,getLoaderComponent_1.default)(loader),[loading,setLoading]=(0,react_1.useState)(!0),{payment,expressPayments}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;(0,react_1.useEffect)(()=>{var _a2,_b2,_c;if(payment?.id===currentPaymentMethodId&&paymentResource&&((_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.payment_source_type)===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=(0,getPaymentAttributes_1.getStripeAttributes)(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=(0,getPaymentAttributes_1.getCkoAttributes)(paymentResource,config));const setPaymentSources=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){order!=null&&(yield setPaymentSource({paymentResource,order,attributes})),getCustomerPaymentSources&&getCustomerPaymentSources()});(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),((_b2=order?.payment_source)===null||_b2===void 0?void 0:_b2.id)!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&((_c=order?.payment_source)===null||_c===void 0?void 0:_c.id)!=null&&setLoading(!1),()=>{setLoading(!0)}},[(_b=order?.payment_method)===null||_b===void 0?void 0:_b.id,show,paymentSource]),(0,react_1.useEffect)(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status]);const gatewayConfig=Object.assign({readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet},p);if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return(0,jsx_runtime_1.jsx)(AdyenGateway_1.default,Object.assign({},gatewayConfig,{children}));case"braintree_payments":return(0,jsx_runtime_1.jsx)(BraintreeGateway_1.default,Object.assign({},gatewayConfig,{children}));case"checkout_com_payments":return(0,jsx_runtime_1.jsx)(CheckoutComGateway_1.default,Object.assign({},gatewayConfig,{children}));case"external_payments":return(0,jsx_runtime_1.jsx)(ExternalGateway_1.default,Object.assign({},gatewayConfig,{children}));case"klarna_payments":return(0,jsx_runtime_1.jsx)(KlarnaGateway_1.default,Object.assign({},gatewayConfig,{children}));case"stripe_payments":return(0,jsx_runtime_1.jsx)(StripeGateway_1.default,Object.assign({},gatewayConfig,{children}));case"wire_transfers":return(0,jsx_runtime_1.jsx)(WireTransferGateway_1.default,Object.assign({},gatewayConfig,{children}));case"paypal_payments":return(0,jsx_runtime_1.jsx)(PaypalGateway_1.default,Object.assign({},gatewayConfig,{children}));default:return null}}exports.default=PaymentGateway;
@@ -1,12 +1,12 @@
1
- import { type JSX } from 'react';
2
- import type { LoaderType } from '../../typings/index';
3
- import type { Order, PaymentMethod as PaymentMethodType } from '@commercelayer/sdk';
4
- import type { PaymentResource } from '../../reducers/PaymentMethodReducer';
5
- import type { DefaultChildrenType } from '../../typings/globals';
1
+ import { type JSX } from "react";
2
+ import type { LoaderType } from "../../typings/index";
3
+ import type { Order, PaymentMethod as PaymentMethodType } from "@commercelayer/sdk";
4
+ import type { PaymentResource } from "../../reducers/PaymentMethodReducer";
5
+ import type { DefaultChildrenType } from "../../typings/globals";
6
6
  export interface PaymentMethodOnClickParams {
7
7
  payment?: PaymentMethodType | Record<string, any>;
8
8
  order?: Order;
9
- paymentSource?: Order['payment_source'];
9
+ paymentSource?: Order["payment_source"];
10
10
  }
11
11
  type Props = {
12
12
  /**
@@ -33,8 +33,8 @@ type Props = {
33
33
  /**
34
34
  * Sort payment methods by an array of strings
35
35
  */
36
- sortBy?: Array<PaymentMethodType['payment_source_type']>;
37
- } & Omit<JSX.IntrinsicElements['div'], 'onClick' | 'children'> & ({
36
+ sortBy?: Array<PaymentMethodType["payment_source_type"]>;
37
+ } & Omit<JSX.IntrinsicElements["div"], "onClick" | "children"> & ({
38
38
  clickableContainer: true;
39
39
  onClick?: (params: PaymentMethodOnClickParams) => void;
40
40
  } | {
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),isEmpty_1=require("../../utils/isEmpty"),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod(_a){var{children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy}=_a,p=tslib_1.__rest(_a,["children","className","activeClass","loader","clickableContainer","autoSelectSinglePaymentMethod","expressPayments","hide","onClick","sortBy"]);const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&tslib_1.__awaiter(this,void 0,void 0,function*(){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});const ps=yield setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&tslib_1.__awaiter(this,void 0,void 0,function*(){if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config));const ps=yield setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)}))},[!(0,isEmpty_1.isEmpty)(paymentMethods),order?.payment_source!=null]),(0,react_1.useEffect)(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const sortedPaymentMethods=paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods,components=sortedPaymentMethods?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}else if(typeof hide=="function")return hide(payment);return!0}).map((payment,k)=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2;e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=(_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=yield setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}):void 0;return(0,jsx_runtime_1.jsx)("div",Object.assign({"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)}},p,{children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})}),k)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PaymentMethod=PaymentMethod;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),getLoaderComponent_1=tslib_1.__importDefault(require("../../utils/getLoaderComponent")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),getPaymentAttributes_1=require("../../utils/getPaymentAttributes"),isEmpty_1=require("../../utils/isEmpty"),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),sortPaymentMethods_1=require("../../utils/payment-methods/sortPaymentMethods");let loadingResource=!1;function PaymentMethod(_a){var{children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy}=_a,p=tslib_1.__rest(_a,["children","className","activeClass","loader","clickableContainer","autoSelectSinglePaymentMethod","expressPayments","hide","onClick","sortBy"]);const[loading,setLoading]=(0,react_1.useState)(!0),[paymentSelected,setPaymentSelected]=(0,react_1.useState)(""),[paymentSourceCreated,setPaymentSourceCreated]=(0,react_1.useState)(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=(0,useCustomContext_1.default)({context:PaymentMethodContext_1.default,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=(0,react_1.useContext)(OrderContext_1.default),{getCustomerPaymentSources}=(0,react_1.useContext)(CustomerContext_1.default),{status}=(0,react_1.useContext)(PlaceOrderContext_1.default);(0,react_1.useEffect)(()=>{if(paymentMethods!=null&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&expressPayments){const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);!paymentSource&&paymentMethod!=null&&tslib_1.__awaiter(this,void 0,void 0,function*(){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});const ps=yield setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})}},[!(0,isEmpty_1.isEmpty)(paymentMethods),expressPayments]),(0,react_1.useEffect)(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!(0,isEmpty_1.isEmpty)(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&tslib_1.__awaiter(this,void 0,void 0,function*(){if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;yield setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=(0,getPaymentAttributes_1.getPaypalAttributes)(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=(0,getPaymentAttributes_1.getExternalPaymentAttributes)(paymentResource,config));const ps=yield setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)}))},[!(0,isEmpty_1.isEmpty)(paymentMethods),order?.payment_source!=null]),(0,react_1.useEffect)(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const sortedPaymentMethods=paymentMethods!=null&&sortBy!=null?(0,sortPaymentMethods_1.sortPaymentMethods)(paymentMethods,sortBy):paymentMethods,components=sortedPaymentMethods?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?e=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2;e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=(_a2=order?.payment_method)===null||_a2===void 0?void 0:_a2.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=yield setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}):void 0;return(0,jsx_runtime_1.jsx)("div",Object.assign({"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)}},p,{children:(0,jsx_runtime_1.jsx)(PaymentMethodChildrenContext_1.default.Provider,{value:paymentMethodProps,children})}),paymentResource)});return loading?(0,getLoaderComponent_1.default)(loader):(0,jsx_runtime_1.jsx)(jsx_runtime_1.Fragment,{children:components})}exports.default=PaymentMethod;
@@ -1,23 +1,65 @@
1
- import { type JSX } from 'react';
2
- import type { PaymentMethodConfig } from '../../reducers/PaymentMethodReducer';
3
- import type { PaymentSourceProps } from './PaymentSource';
4
- import { type FramesStyle } from 'frames-react';
1
+ import { type JSX } from "react";
2
+ import type { PaymentMethodConfig } from "../../reducers/PaymentMethodReducer";
3
+ import type { PaymentSourceProps } from "./PaymentSource";
4
+ interface Appearance {
5
+ colorAction: string;
6
+ colorBackground: string;
7
+ colorBorder: string;
8
+ colorDisabled: string;
9
+ colorError: string;
10
+ colorFormBackground: string;
11
+ colorFormBorder: string;
12
+ colorInverse: string;
13
+ colorOutline: string;
14
+ colorPrimary: string;
15
+ colorSecondary: string;
16
+ colorSuccess: string;
17
+ button: {
18
+ fontFamily: string;
19
+ fontSize: string;
20
+ fontWeight: number;
21
+ letterSpacing: number;
22
+ lineHeight: string;
23
+ };
24
+ footnote: {
25
+ fontFamily: string;
26
+ fontSize: string;
27
+ fontWeight: number;
28
+ letterSpacing: number;
29
+ lineHeight: string;
30
+ };
31
+ label: {
32
+ fontFamily: string;
33
+ fontSize: string;
34
+ fontWeight: number;
35
+ letterSpacing: number;
36
+ lineHeight: string;
37
+ };
38
+ subheading: {
39
+ fontFamily: string;
40
+ fontSize: string;
41
+ fontWeight: number;
42
+ letterSpacing: number;
43
+ lineHeight: string;
44
+ };
45
+ borderRadius: [string, string];
46
+ }
5
47
  export interface CheckoutComConfig {
6
48
  containerClassName?: string;
7
49
  hintLabel?: string;
8
50
  name?: string;
9
- success_url?: string;
10
- failure_url?: string;
51
+ success_url: string;
52
+ failure_url: string;
11
53
  options?: {
12
- style: FramesStyle;
54
+ appearance: Partial<Appearance>;
13
55
  };
14
56
  [key: string]: unknown;
15
57
  }
16
- type Props = PaymentMethodConfig['checkoutComPayment'] & JSX.IntrinsicElements['div'] & {
58
+ type Props = Partial<PaymentMethodConfig["checkoutComPayment"]> & JSX.IntrinsicElements["div"] & {
17
59
  show?: boolean;
18
60
  publicKey: string;
19
61
  locale?: string;
20
- templateCustomerSaveToWallet?: PaymentSourceProps['templateCustomerSaveToWallet'];
62
+ templateCustomerSaveToWallet?: PaymentSourceProps["templateCustomerSaveToWallet"];
21
63
  };
22
- export declare function CheckoutComPayment({ publicKey, options, locale, ...p }: Props): JSX.Element | null;
64
+ export declare function CheckoutComPayment({ publicKey, options, ...p }: Props): JSX.Element | null;
23
65
  export default CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),frames_react_1=require("frames-react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://cdn.checkout.com/js/framesv2.min.js",systemLanguages=["DE-DE","EN-GB","ES-ES","FR-FR","IT-IT","KO-KR","NL-NL"],defaultOptions={style:{base:{color:"black",fontSize:"18px"},autofill:{backgroundColor:"yellow"},hover:{color:"blue"},focus:{color:"blue"},valid:{color:"green"},invalid:{color:"red"},placeholder:{base:{color:"gray"},focus:{border:"solid 1px blue"}}}};function CheckoutComPayment(_a){var{publicKey,options=defaultOptions,locale="EN-GB"}=_a,p=tslib_1.__rest(_a,["publicKey","options","locale"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]),handleSubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o;const savePaymentSourceToCustomerWallet=(_c=(_b=(_a2=ref?.current)===null||_a2===void 0?void 0:_a2.elements)===null||_b===void 0?void 0:_b.save_payment_source_to_customer_wallet)===null||_c===void 0?void 0:_c.checked;if(savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),window.Frames){window.Frames.cardholder={name:(_d=order?.billing_address)===null||_d===void 0?void 0:_d.full_name,billingAddress:{addressLine1:(_e=order?.billing_address)===null||_e===void 0?void 0:_e.line_1,addressLine2:(_g=(_f=order?.billing_address)===null||_f===void 0?void 0:_f.line_2)!==null&&_g!==void 0?_g:"",zip:(_j=(_h=order?.billing_address)===null||_h===void 0?void 0:_h.zip_code)!==null&&_j!==void 0?_j:"",city:(_k=order?.billing_address)===null||_k===void 0?void 0:_k.city,state:(_l=order?.billing_address)===null||_l===void 0?void 0:_l.state_code,country:(_m=order?.billing_address)===null||_m===void 0?void 0:_m.country_code},phone:(_o=order?.billing_address)===null||_o===void 0?void 0:_o.phone};try{const data=yield window.Frames.submitCard();if(data.token&&paymentSource&&currentPaymentMethodType){const ps=yield setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{token:data.token,payment_type:"token",success_url:successUrl,failure_url:failureUrl,_authorize:!0}});ps?.redirect_uri&&(window.location.href=ps.redirect_uri)}}catch(error){console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error?.message}])}}return!1}),lang=`${locale.toUpperCase()}-${locale.toUpperCase()}`,localization=systemLanguages.includes(lang)?lang:"EN-GB";return loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsxs)(frames_react_1.Frames,{config:Object.assign({debug:!0,publicKey,localization},options),cardValidationChanged:e=>{e.isValid&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield handleSubmit()}),setPaymentRef({ref}))},cardTokenized:data=>data,children:[(0,jsx_runtime_1.jsx)(frames_react_1.CardNumber,{}),(0,jsx_runtime_1.jsx)(frames_react_1.ExpiryDate,{}),(0,jsx_runtime_1.jsx)(frames_react_1.Cvv,{})]})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutComPayment=CheckoutComPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),useExternalScript_1=tslib_1.__importDefault(require("../../utils/hooks/useExternalScript")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),jwt_1=require("../../utils/jwt"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),localStorage_1=require("../../utils/localStorage"),scriptUrl="https://checkout-web-components.checkout.com/index.js";function CheckoutComPayment(_a){var _b,{publicKey,options}=_a,p=tslib_1.__rest(_a,["publicKey","options"]);const ref=(0,react_1.useRef)(null),loaded=(0,useExternalScript_1.default)(scriptUrl),{setPaymentRef,setPaymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show}=p,divProps=tslib_1.__rest(p,["containerClassName","templateCustomerSaveToWallet","successUrl","failureUrl","show"]);return(0,react_1.useEffect)(()=>{var _a2;const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=(0,jwt_1.jwt)(accessToken).test?"sandbox":"production",locale=(_a2=order?.language_code)!==null&&_a2!==void 0?_a2:"en";(()=>tslib_1.__awaiter(this,void 0,void 0,function*(){(yield window.CheckoutWebComponents({appearance:Object.assign({},options?.appearance),showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a3,_b2;const element=(_a3=ref.current)===null||_a3===void 0?void 0:_a3.elements,savePaymentSourceToCustomerWallet=(_b2=element?.save_payment_source_to_customer_wallet)===null||_b2===void 0?void 0:_b2.checked;savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=yield component.tokenize(),token=data?.token,paymentSource=yield setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1}),setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))}))()}}},[loaded,(_b=order?.payment_source)===null||_b===void 0?void 0:_b.id,accessToken]),loaded&&show?(0,jsx_runtime_1.jsxs)("form",{ref,children:[(0,jsx_runtime_1.jsx)("div",Object.assign({className:containerClassName},divProps,{children:(0,jsx_runtime_1.jsx)("div",{id:"flow-container"})})),templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}exports.default=CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}else{if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}const updatePaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setPaymentMethodConfig=exports.destroyPaymentSource=exports.updatePaymentSource=exports.getPaymentMethods=exports.setPaymentMethodErrors=exports.paymentMethodInitialState=exports.setPaymentRef=void 0,exports.setLoading=setLoading,exports.setPaymentMethod=setPaymentMethod,exports.setPaymentSource=setPaymentSource,exports.getPaymentConfig=getPaymentConfig;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getErrors_1=tslib_1.__importStar(require("../utils/getErrors")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),snakeToCamelCase_1=require("../utils/snakeToCamelCase"),replace_1=require("../utils/replace"),pick_1=require("../utils/pick");function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})};exports.setPaymentRef=setPaymentRef,exports.paymentMethodInitialState={errors:[],paymentMethods:void 0};const setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})};exports.setPaymentMethodErrors=setPaymentMethodErrors;const getPaymentMethods=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({order,dispatch}){const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})});exports.getPaymentMethods=getPaymentMethods;function setPaymentMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:(0,getSdk_1.default)(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=yield updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}})}function setPaymentSource(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){var _b;try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=(0,getSdk_1.default)(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs=Object.assign({id:paymentSourceId},attributes);paymentSource=attributes!=null?yield sdk[paymentResource].update(attrs):yield sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs=Object.assign(Object.assign({},attributes),{order:sdk.orders.relationship(order.id)});paymentSource=yield sdk[paymentResource].create(attrs)}return getOrder&&(yield getOrder(order.id)),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=yield updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:(_b=orderUpdated.payment_source)===null||_b===void 0?void 0:_b.id}})}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=yield getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch}))}}else(0,getErrors_1.setErrors)({currentErrors,newErrors:errors,dispatch})}})}const updatePaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({id,attributes,config,dispatch,paymentResource}){if(config)try{const paymentSource=yield(0,getSdk_1.default)(config)[paymentResource].update(Object.assign({id},attributes));dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}});exports.updatePaymentSource=updatePaymentSource;const destroyPaymentSource=_a=>tslib_1.__awaiter(void 0,[_a],void 0,function*({paymentSourceId,paymentResource,dispatch}){paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})});exports.destroyPaymentSource=destroyPaymentSource;const setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};exports.setPaymentMethodConfig=setPaymentMethodConfig;function getPaymentConfig(paymentResource,config){const resourceKeys=(0,replace_1.replace)((0,replace_1.replace)(paymentResource,"payments","payment"),"transfers","transfer"),resource=(0,snakeToCamelCase_1.snakeToCamelCase)(resourceKeys);return(0,pick_1.pick)(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=paymentMethodReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g,_h;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:(_c=options?.checkoutCom)===null||_c===void 0?void 0:_c.session_id});if(((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.status)!=="Authorized"){const[action]=((_e=payment?.payment_response)===null||_e===void 0?void 0:_e.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_f=ps?.options)===null||_f===void 0?void 0:_f.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_g=order?.total_amount_cents)!==null&&_g!==void 0?_g:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_h=orderUpdated?.total_amount_cents)!==null&&_h!==void 0?_h:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.placeOrderInitialState=void 0,exports.setButtonRef=setButtonRef,exports.setPlaceOrderErrors=setPlaceOrderErrors,exports.placeOrderPermitted=placeOrderPermitted,exports.setPlaceOrder=setPlaceOrder,exports.setPlaceOrderStatus=setPlaceOrderStatus;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),shipments_1=require("../utils/shipments"),customerOrderOptions_1=require("../utils/customerOrderOptions"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),isGuestToken_1=require("../utils/isGuestToken"),localStorage_1=require("../utils/localStorage"),hasSubscriptions_1=require("../utils/hasSubscriptions"),updateOrderSubscriptionCustomerPaymentSource_1=require("../utils/updateOrderSubscriptionCustomerPaymentSource");function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}exports.placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}function placeOrderPermitted({config,order,dispatch,options}){var _a;if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=(0,shipments_1.isDoNotShip)(order.line_items),shipments=order.shipments,shipment=shipments&&(0,shipments_1.shipmentsFilled)(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&(0,isEmpty_1.default)(paymentMethod?.id)&&(isPermitted=!1),(0,isEmpty_1.default)(billingAddress)&&(isPermitted=!1),(0,isEmpty_1.default)(shippingAddress)&&!doNotShip&&(isPermitted=!1),!(0,isEmpty_1.default)(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:(_a=paymentSource?.options)===null||_a===void 0?void 0:_a.id,paymentSource,options}})}}function setPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){var _b,_c,_d,_e,_f,_g;const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=(0,getSdk_1.default)(config),{options,paymentType}=state;try{const lastOrderStatus=yield sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;yield sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&(!((_b=options?.checkoutCom)===null||_b===void 0)&&_b.session_id)){const payment=yield sdk[paymentType].update({id:paymentSource.id,_details:!0});if(((_c=payment?.payment_response)===null||_c===void 0?void 0:_c.status)!=="Authorized"){const[action]=((_d=payment?.payment_response)===null||_d===void 0?void 0:_d.actions)||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if((0,customerOrderOptions_1.saveBillingAddress)()&&(yield sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0})),(0,customerOrderOptions_1.saveShippingAddress)()&&(yield sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0})),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=(_e=ps?.options)===null||_e===void 0?void 0:_e.return_url;currentUrl!==returnUrl&&(yield sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}}))}switch((0,hasSubscriptions_1.hasSubscriptions)(order)&&config?.accessToken!=null&&!(0,isGuestToken_1.isGuestToken)(config.accessToken)&&currentCustomerPaymentSourceId==null&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=(_f=order?.total_amount_cents)!==null&&_f!==void 0?_f:0;yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=yield sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=yield sdk.orders.update(updateAttributes,{include}),total=(_g=orderUpdated?.total_amount_cents)!==null&&_g!==void 0?_g:0;return setOrder&&setOrder(orderUpdated),yield Promise.all([(0,customerOrderOptions_1.saveToWallet)()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{(0,updateOrderSubscriptionCustomerPaymentSource_1.updateOrderSubscriptionCustomerPaymentSource)(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),Object.assign(Object.assign({},response),{errors})}}return response})}function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getCardDetails;function getCardDetails({paymentType,customerPayment}){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0,_1,_2,_3,_4,_5;switch(paymentType){case"checkout_com_payments":{const ps=customerPayment.payment_source,source=(_a=ps?.payment_response)===null||_a===void 0?void 0:_a.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=((_e=(_c=(_b=ps?.options)===null||_b===void 0?void 0:_b.card)!==null&&_c!==void 0?_c:(_d=ps?.payment_method)===null||_d===void 0?void 0:_d.card)!==null&&_e!==void 0?_e:ps?.payment_instrument)?{brand:(_f=ps?.payment_instrument)===null||_f===void 0?void 0:_f.card_type,exp_month:(_g=ps?.payment_instrument)===null||_g===void 0?void 0:_g.card_expiry_month,exp_year:(_h=ps?.payment_instrument)===null||_h===void 0?void 0:_h.card_expiry_year,last4:(_j=ps?.payment_instrument)===null||_j===void 0?void 0:_j.card_last_digits,issuer_type:(_k=ps?.payment_instrument)===null||_k===void 0?void 0:_k.issuer_type}:void 0;if(source?.brand!=null)return Object.assign({},source);break}case"klarna_payments":{const ps=customerPayment.payment_source,source=ps?.auth_token!=null&&ps?.payment_instrument!=null?{brand:"klarna",exp_month:"",exp_year:"",last4:"",issuer_type:(_l=ps?.payment_instrument)===null||_l===void 0?void 0:_l.issuer_type}:void 0;if(source)return Object.assign({},source);break}case"braintree_payments":{const ps=customerPayment.payment_source,source=(_m=ps?.options)===null||_m===void 0?void 0:_m.card;if(source)return Object.assign({},source);break}case"adyen_payments":{const ps=customerPayment.payment_source,source=(_o=ps?.payment_request_data)===null||_o===void 0?void 0:_o.payment_method,authorized=((_p=ps?.payment_response)===null||_p===void 0?void 0:_p.resultCode)==="Authorised",last4=(_u=(_s=(_r=(_q=ps?.payment_response)===null||_q===void 0?void 0:_q.additionalData)===null||_r===void 0?void 0:_r.cardSummary)!==null&&_s!==void 0?_s:(_t=ps?.payment_instrument)===null||_t===void 0?void 0:_t.card_last_digits)!==null&&_u!==void 0?_u:"****";if(source&&authorized){const brand=source.type==="scheme"?(_v=source.brand)!==null&&_v!==void 0?_v:"credit-card":source.type.replace("_account","");return Object.assign(Object.assign({},source),{last4,brand})}break}default:{const ps=customerPayment.payment_source;if(ps?.type!==paymentType)break;const source=(_x=(_w=ps?.metadata)===null||_w===void 0?void 0:_w.card)!==null&&_x!==void 0?_x:{brand:(_z=(_y=ps?.payment_instrument)===null||_y===void 0?void 0:_y.issuer_type.replace("_","-"))!==null&&_z!==void 0?_z:"",last4:(_1=(_0=ps?.metadata)===null||_0===void 0?void 0:_0.last4)!==null&&_1!==void 0?_1:"",exp_month:(_3=(_2=ps?.metadata)===null||_2===void 0?void 0:_2.exp_month)!==null&&_3!==void 0?_3:"",exp_year:(_5=(_4=ps?.metadata)===null||_4===void 0?void 0:_4.exp_year)!==null&&_5!==void 0?_5:""};if(source)return Object.assign({},source);break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****",issuer_type:""}}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=getCardDetails;function getCardDetails({paymentType,customerPayment}){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0,_1,_2,_3,_4,_5,_6;switch(paymentType){case"checkout_com_payments":{const ps=customerPayment.payment_source,source=(_a=ps?.payment_response)===null||_a===void 0?void 0:_a.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=((_e=(_c=(_b=ps?.options)===null||_b===void 0?void 0:_b.card)!==null&&_c!==void 0?_c:(_d=ps?.payment_method)===null||_d===void 0?void 0:_d.card)!==null&&_e!==void 0?_e:ps?.payment_instrument)?{brand:(_f=ps?.payment_instrument)===null||_f===void 0?void 0:_f.card_type,exp_month:(_g=ps?.payment_instrument)===null||_g===void 0?void 0:_g.card_expiry_month,exp_year:(_h=ps?.payment_instrument)===null||_h===void 0?void 0:_h.card_expiry_year,last4:(_j=ps?.payment_instrument)===null||_j===void 0?void 0:_j.card_last_digits,issuer_type:(_k=ps?.payment_instrument)===null||_k===void 0?void 0:_k.issuer_type}:void 0;if(source?.brand!=null)return Object.assign({},source);break}case"klarna_payments":{const ps=customerPayment.payment_source,source=ps?.auth_token!=null&&ps?.payment_instrument!=null?{brand:"klarna",exp_month:"",exp_year:"",last4:"",issuer_type:(_l=ps?.payment_instrument)===null||_l===void 0?void 0:_l.issuer_type}:void 0;if(source)return Object.assign({},source);break}case"braintree_payments":{const ps=customerPayment.payment_source,source=(_m=ps?.options)===null||_m===void 0?void 0:_m.card;if(source)return Object.assign({},source);break}case"adyen_payments":{const ps=customerPayment.payment_source,source=(_o=ps?.payment_request_data)===null||_o===void 0?void 0:_o.payment_method,authorized=((_p=ps?.payment_response)===null||_p===void 0?void 0:_p.resultCode)==="Authorised",last4=(_u=(_s=(_r=(_q=ps?.payment_response)===null||_q===void 0?void 0:_q.additionalData)===null||_r===void 0?void 0:_r.cardSummary)!==null&&_s!==void 0?_s:(_t=ps?.payment_instrument)===null||_t===void 0?void 0:_t.card_last_digits)!==null&&_u!==void 0?_u:"****";if(source&&authorized){const brand=source.type==="scheme"?(_v=source.brand)!==null&&_v!==void 0?_v:"credit-card":source.type.replace("_account","");return Object.assign(Object.assign({},source),{last4,brand})}break}default:{const ps=customerPayment.payment_source;if(ps?.type!==paymentType)break;const source=(_x=(_w=ps?.metadata)===null||_w===void 0?void 0:_w.card)!==null&&_x!==void 0?_x:{brand:(_0=(_z=(_y=ps?.payment_instrument)===null||_y===void 0?void 0:_y.issuer_type)===null||_z===void 0?void 0:_z.replace("_","-"))!==null&&_0!==void 0?_0:"",last4:(_2=(_1=ps?.metadata)===null||_1===void 0?void 0:_1.last4)!==null&&_2!==void 0?_2:"",exp_month:(_4=(_3=ps?.metadata)===null||_3===void 0?void 0:_3.exp_month)!==null&&_4!==void 0?_4:"",exp_year:(_6=(_5=ps?.metadata)===null||_5===void 0?void 0:_5.exp_year)!==null&&_6!==void 0?_6:""};if(source)return Object.assign({},source);break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****",issuer_type:""}}
@@ -1,17 +1,19 @@
1
- import type { PaypalConfig } from '../components/payment_source/PaypalPayment';
2
- import { type PaymentMethodConfig, type PaymentResource } from '../reducers/PaymentMethodReducer';
3
- import type { ExternalPayment } from '@commercelayer/sdk';
4
- import { type StringReplace } from './replace';
5
- import { type SnakeToCamelCase } from './snakeToCamelCase';
6
- import type { StripeConfig } from '../components/payment_source/StripePayment';
1
+ import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
2
+ import { type PaymentMethodConfig, type PaymentResource } from "../reducers/PaymentMethodReducer";
3
+ import type { ExternalPayment } from "@commercelayer/sdk";
4
+ import { type StringReplace } from "./replace";
5
+ import { type SnakeToCamelCase } from "./snakeToCamelCase";
6
+ import type { StripeConfig } from "../components/payment_source/StripePayment";
7
+ import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
7
8
  interface Params<R extends PaymentResource, C extends PaymentMethodConfig> {
8
9
  resource: R;
9
10
  config: C;
10
11
  keys: R[];
11
12
  }
12
- export type ResourceKeys<K extends PaymentResource> = SnakeToCamelCase<StringReplace<StringReplace<K, 'payments', 'payment'>, 'transfers', 'transfer'>>;
13
+ export type ResourceKeys<K extends PaymentResource> = SnakeToCamelCase<StringReplace<StringReplace<K, "payments", "payment">, "transfers", "transfer">>;
13
14
  export declare function getPaymentAttributes<R extends PaymentResource = PaymentResource, C extends PaymentMethodConfig = PaymentMethodConfig>(params: Params<R, C>): Pick<C, ResourceKeys<R>> | undefined;
14
- export declare function getPaypalAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<PaypalConfig, 'return_url' | 'cancel_url'> | undefined;
15
- export declare function getExternalPaymentAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<ExternalPayment, 'payment_source_token'> | undefined;
16
- export declare function getStripeAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<StripeConfig, 'return_url'> | undefined;
15
+ export declare function getPaypalAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<PaypalConfig, "return_url" | "cancel_url"> | undefined;
16
+ export declare function getExternalPaymentAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<ExternalPayment, "payment_source_token"> | undefined;
17
+ export declare function getStripeAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<StripeConfig, "return_url"> | undefined;
18
+ export declare function getCkoAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<CheckoutComConfig, "success_url" | "failure_url"> | undefined;
17
19
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPaymentAttributes=getPaymentAttributes,exports.getPaypalAttributes=getPaypalAttributes,exports.getExternalPaymentAttributes=getExternalPaymentAttributes,exports.getStripeAttributes=getStripeAttributes;const PaymentMethodReducer_1=require("../reducers/PaymentMethodReducer"),pick_1=require("./pick"),replace_1=require("./replace"),snakeToCamelCase_1=require("./snakeToCamelCase");function getPaymentAttributes(params){const{resource,config,keys}=params,attributes=(0,PaymentMethodReducer_1.getPaymentConfig)(resource,config),keysCamelCase=keys.map(key=>{const k=(0,replace_1.replace)((0,replace_1.replace)(key,"payments","payment"),"transfers","transfer");return(0,snakeToCamelCase_1.snakeToCamelCase)(k)}),currentResource=(0,snakeToCamelCase_1.snakeToCamelCase)((0,replace_1.replace)((0,replace_1.replace)(resource,"payments","payment"),"transfers","transfer"));return attributes!=null&&currentResource in attributes?(0,pick_1.pick)(attributes,keysCamelCase):void 0}function getPaypalAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["paypal_payments"]});return attributes?.paypalPayment!=null&&"paypalPayment"in attributes?(0,pick_1.pick)(attributes?.paypalPayment,["return_url","cancel_url"]):void 0}function getExternalPaymentAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["external_payments"]});return attributes?.externalPayment!=null&&"externalPayment"in attributes?(0,pick_1.pick)(attributes?.externalPayment,["payment_source_token"]):void 0}function getStripeAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["stripe_payments"]});return attributes?.stripePayment!=null&&"stripePayment"in attributes?(0,pick_1.pick)(attributes?.stripePayment,["return_url"]):void 0}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPaymentAttributes=getPaymentAttributes,exports.getPaypalAttributes=getPaypalAttributes,exports.getExternalPaymentAttributes=getExternalPaymentAttributes,exports.getStripeAttributes=getStripeAttributes,exports.getCkoAttributes=getCkoAttributes;const PaymentMethodReducer_1=require("../reducers/PaymentMethodReducer"),pick_1=require("./pick"),replace_1=require("./replace"),snakeToCamelCase_1=require("./snakeToCamelCase");function getPaymentAttributes(params){const{resource,config,keys}=params,attributes=(0,PaymentMethodReducer_1.getPaymentConfig)(resource,config),keysCamelCase=keys.map(key=>{const k=(0,replace_1.replace)((0,replace_1.replace)(key,"payments","payment"),"transfers","transfer");return(0,snakeToCamelCase_1.snakeToCamelCase)(k)}),currentResource=(0,snakeToCamelCase_1.snakeToCamelCase)((0,replace_1.replace)((0,replace_1.replace)(resource,"payments","payment"),"transfers","transfer"));return attributes!=null&&currentResource in attributes?(0,pick_1.pick)(attributes,keysCamelCase):void 0}function getPaypalAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["paypal_payments"]});return attributes?.paypalPayment!=null&&"paypalPayment"in attributes?(0,pick_1.pick)(attributes?.paypalPayment,["return_url","cancel_url"]):void 0}function getExternalPaymentAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["external_payments"]});return attributes?.externalPayment!=null&&"externalPayment"in attributes?(0,pick_1.pick)(attributes?.externalPayment,["payment_source_token"]):void 0}function getStripeAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["stripe_payments"]});return attributes?.stripePayment!=null&&"stripePayment"in attributes?(0,pick_1.pick)(attributes?.stripePayment,["return_url"]):void 0}function getCkoAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["checkout_com_payments"]});return attributes?.checkoutComPayment!=null&&"checkoutComPayment"in attributes?(0,pick_1.pick)(attributes?.checkoutComPayment,["success_url","failure_url"]):void 0}
@@ -2,4 +2,13 @@ export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U
2
2
  export type SnakeToCamelCaseNested<T> = T extends object ? {
3
3
  [K in keyof T as SnakeToCamelCase<K & string>]: SnakeToCamelCaseNested<T[K]>;
4
4
  } : T;
5
+ /**
6
+ *
7
+ * @param value - The string to convert from snake_case to camelCase
8
+ * @example
9
+ * snakeToCamelCase("hello_world") // "helloWorld"
10
+ * snakeToCamelCase("hello_world_test") // "helloWorldTest"
11
+ * @returns string
12
+ * @description Converts a string from snake_case to camelCase
13
+ */
5
14
  export declare function snakeToCamelCase<S extends string>(value: S): SnakeToCamelCase<S>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.snakeToCamelCase=snakeToCamelCase;function snakeToCamelCase(value){var _a,_b,_c,_d,_e,_f;const words=value.toLowerCase().split("_"),first=(_a=words[0])!==null&&_a!==void 0?_a:"",firstLetter=(_d=(_c=(_b=words[1])===null||_b===void 0?void 0:_b[0])===null||_c===void 0?void 0:_c.toUpperCase())!==null&&_d!==void 0?_d:"",second=(_f=(_e=words[1])===null||_e===void 0?void 0:_e.substring(1))!==null&&_f!==void 0?_f:"";return`${first}${firstLetter}${second}`}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.snakeToCamelCase=snakeToCamelCase;function snakeToCamelCase(value){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l;const words=value.toLowerCase().split("_"),first=(_a=words[0])!==null&&_a!==void 0?_a:"",secondLetter=(_d=(_c=(_b=words[1])===null||_b===void 0?void 0:_b[0])===null||_c===void 0?void 0:_c.toUpperCase())!==null&&_d!==void 0?_d:"",second=(_f=(_e=words[1])===null||_e===void 0?void 0:_e.substring(1))!==null&&_f!==void 0?_f:"",thirdLetter=(_j=(_h=(_g=words[2])===null||_g===void 0?void 0:_g[0])===null||_h===void 0?void 0:_h.toUpperCase())!==null&&_j!==void 0?_j:"",third=(_l=(_k=words[2])===null||_k===void 0?void 0:_k.substring(1))!==null&&_l!==void 0?_l:"";return`${first}${secondLetter}${second}${thirdLetter}${third}`}
@@ -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(()=>{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;
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=>{if(e?.preventDefault(),e?.stopPropagation(),order?.status==="placed"){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}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,5 +1,5 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import { type PlaceOrderOptions } from '../../reducers/PlaceOrderReducer';
1
+ import { type ReactNode, type JSX } from "react";
2
+ import { type PlaceOrderOptions } from "../../reducers/PlaceOrderReducer";
3
3
  interface Props {
4
4
  children: ReactNode;
5
5
  options?: PlaceOrderOptions;
@@ -1,6 +1,6 @@
1
- import type { LoaderType } from '../../typings/index';
2
- import { type JSX } from 'react';
3
- import type { PaymentSourceProps } from '../payment_source/PaymentSource';
1
+ import type { LoaderType } from "../../typings/index";
2
+ import { type JSX } from "react";
3
+ import type { PaymentSourceProps } from "../payment_source/PaymentSource";
4
4
  export type GatewayBaseType = Props & {
5
5
  show: boolean;
6
6
  loading: boolean;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{useContext,useEffect,useState}from"react";import getLoaderComponent from"../../utils/getLoaderComponent";import AdyenGateway from"./AdyenGateway";import StripeGateway from"./StripeGateway";import BraintreeGateway from"./BraintreeGateway";import PaypalGateway from"./PaypalGateway";import WireTransferGateway from"./WireTransferGateway";import CustomerContext from"../../context/CustomerContext";import CheckoutComGateway from"./CheckoutComGateway";import KlarnaGateway from"./KlarnaGateway";import{getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import ExternalGateway from"./ExternalGateway";import PlaceOrderContext from"../../context/PlaceOrderContext";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import OrderContext from"../../context/OrderContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{useContext,useEffect,useState}from"react";import getLoaderComponent from"../../utils/getLoaderComponent";import AdyenGateway from"./AdyenGateway";import StripeGateway from"./StripeGateway";import BraintreeGateway from"./BraintreeGateway";import PaypalGateway from"./PaypalGateway";import WireTransferGateway from"./WireTransferGateway";import CustomerContext from"../../context/CustomerContext";import CheckoutComGateway from"./CheckoutComGateway";import KlarnaGateway from"./KlarnaGateway";import{getCkoAttributes,getExternalPaymentAttributes,getPaypalAttributes,getStripeAttributes}from"../../utils/getPaymentAttributes";import ExternalGateway from"./ExternalGateway";import PlaceOrderContext from"../../context/PlaceOrderContext";export function PaymentGateway({readonly,showCard,handleEditClick,children,templateCustomerCards,templateCustomerSaveToWallet,onClickCustomerCards,show,loader="Loading...",...p}){const loaderComponent=getLoaderComponent(loader),[loading,setLoading]=useState(!0),{payment,expressPayments}=useContext(PaymentMethodChildrenContext),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext),{currentPaymentMethodId,config,currentPaymentMethodType,setPaymentSource,paymentSource}=useContext(PaymentMethodContext),paymentResource=readonly?currentPaymentMethodType:payment?.payment_source_type;useEffect(()=>{if(payment?.id===currentPaymentMethodId&&paymentResource&&order?.payment_method?.payment_source_type===paymentResource&&!expressPayments){let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config)),config!=null&&paymentResource==="stripe_payments"&&(attributes=getStripeAttributes(paymentResource,config),attributes!=null&&attributes.return_url==null&&(attributes.return_url=window.location.href)),config!=null&&paymentResource==="checkout_com_payments"&&(attributes=getCkoAttributes(paymentResource,config));const setPaymentSources=async()=>{order!=null&&await setPaymentSource({paymentResource,order,attributes}),getCustomerPaymentSources&&getCustomerPaymentSources()};(!paymentSource&&order?.payment_method.id&&show&&!expressPayments||(!paymentSource&&!expressPayments||paymentSource?.type!==paymentResource)&&show)&&setPaymentSources(),paymentSource?.mismatched_amounts&&show&&setPaymentSources(),order?.payment_source?.id!=null&&setLoading(!1)}return expressPayments&&show&&setLoading(!1),order?.status!=null&&!["draft","pending"].includes(order?.status)&&show&&order?.payment_source?.id!=null&&setLoading(!1),()=>{setLoading(!0)}},[order?.payment_method?.id,show,paymentSource]),useEffect(()=>(status==="placing"&&setLoading(!0),status==="standby"&&loading&&setLoading(!1),()=>{setLoading(!0)}),[status]);const gatewayConfig={readonly,showCard,handleEditClick,children,templateCustomerCards,show,loading,onClickCustomerCards,loaderComponent,templateCustomerSaveToWallet,...p};if(currentPaymentMethodType!==paymentResource)return null;if(loading)return loaderComponent;switch(paymentResource){case"adyen_payments":return _jsx(AdyenGateway,{...gatewayConfig,children});case"braintree_payments":return _jsx(BraintreeGateway,{...gatewayConfig,children});case"checkout_com_payments":return _jsx(CheckoutComGateway,{...gatewayConfig,children});case"external_payments":return _jsx(ExternalGateway,{...gatewayConfig,children});case"klarna_payments":return _jsx(KlarnaGateway,{...gatewayConfig,children});case"stripe_payments":return _jsx(StripeGateway,{...gatewayConfig,children});case"wire_transfers":return _jsx(WireTransferGateway,{...gatewayConfig,children});case"paypal_payments":return _jsx(PaypalGateway,{...gatewayConfig,children});default:return null}}export default PaymentGateway;
@@ -1,12 +1,12 @@
1
- import { type JSX } from 'react';
2
- import type { LoaderType } from '../../typings/index';
3
- import type { Order, PaymentMethod as PaymentMethodType } from '@commercelayer/sdk';
4
- import type { PaymentResource } from '../../reducers/PaymentMethodReducer';
5
- import type { DefaultChildrenType } from '../../typings/globals';
1
+ import { type JSX } from "react";
2
+ import type { LoaderType } from "../../typings/index";
3
+ import type { Order, PaymentMethod as PaymentMethodType } from "@commercelayer/sdk";
4
+ import type { PaymentResource } from "../../reducers/PaymentMethodReducer";
5
+ import type { DefaultChildrenType } from "../../typings/globals";
6
6
  export interface PaymentMethodOnClickParams {
7
7
  payment?: PaymentMethodType | Record<string, any>;
8
8
  order?: Order;
9
- paymentSource?: Order['payment_source'];
9
+ paymentSource?: Order["payment_source"];
10
10
  }
11
11
  type Props = {
12
12
  /**
@@ -33,8 +33,8 @@ type Props = {
33
33
  /**
34
34
  * Sort payment methods by an array of strings
35
35
  */
36
- sortBy?: Array<PaymentMethodType['payment_source_type']>;
37
- } & Omit<JSX.IntrinsicElements['div'], 'onClick' | 'children'> & ({
36
+ sortBy?: Array<PaymentMethodType["payment_source_type"]>;
37
+ } & Omit<JSX.IntrinsicElements["div"], "onClick" | "children"> & ({
38
38
  clickableContainer: true;
39
39
  onClick?: (params: PaymentMethodOnClickParams) => void;
40
40
  } | {
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useState,useEffect,useContext}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import useCustomContext from"../../utils/hooks/useCustomContext";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import{getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import{isEmpty}from"../../utils/isEmpty";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import PlaceOrderContext from"../../context/PlaceOrderContext";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)})())},[!isEmpty(paymentMethods),order?.payment_source!=null]),useEffect(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}else if(typeof hide=="function")return hide(payment);return!0}).map((payment,k)=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},k)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useState,useEffect,useContext}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import useCustomContext from"../../utils/hooks/useCustomContext";import OrderContext from"../../context/OrderContext";import CustomerContext from"../../context/CustomerContext";import{getExternalPaymentAttributes,getPaypalAttributes}from"../../utils/getPaymentAttributes";import{isEmpty}from"../../utils/isEmpty";import{getAvailableExpressPayments}from"../../utils/expressPaymentHelper";import PlaceOrderContext from"../../context/PlaceOrderContext";import{sortPaymentMethods}from"../../utils/payment-methods/sortPaymentMethods";let loadingResource=!1;export function PaymentMethod({children,className,activeClass,loader="Loading...",clickableContainer,autoSelectSinglePaymentMethod,expressPayments,hide,onClick,sortBy,...p}){const[loading,setLoading]=useState(!0),[paymentSelected,setPaymentSelected]=useState(""),[paymentSourceCreated,setPaymentSourceCreated]=useState(!1),{paymentMethods,currentPaymentMethodId,setPaymentMethod,setLoading:setLoadingPlaceOrder,paymentSource,setPaymentSource,config}=useCustomContext({context:PaymentMethodContext,contextComponentName:"PaymentMethodsContainer",currentComponentName:"PaymentMethod",key:"paymentMethods"}),{order}=useContext(OrderContext),{getCustomerPaymentSources}=useContext(CustomerContext),{status}=useContext(PlaceOrderContext);useEffect(()=>{if(paymentMethods!=null&&!isEmpty(paymentMethods)&&expressPayments){const[paymentMethod]=getAvailableExpressPayments(paymentMethods);!paymentSource&&paymentMethod!=null&&(async()=>{setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});const ps=await setPaymentSource({paymentResource,order});ps&&paymentMethod&&onClick!=null&&(onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),setLoadingPlaceOrder({loading:!1})})()}},[!isEmpty(paymentMethods),expressPayments]),useEffect(()=>{paymentMethods!=null&&!paymentSourceCreated&&!loadingResource&&!isEmpty(paymentMethods)&&(loadingResource=!0,autoSelectSinglePaymentMethod!=null&&!expressPayments&&(async()=>{if(paymentMethods.length===1){const[paymentMethod]=paymentMethods??[];if(paymentMethod&&!paymentSource){setLoadingPlaceOrder({loading:!0}),setPaymentSelected(paymentMethod.id);const paymentMethodId=paymentMethod?.id,paymentResource=paymentMethod?.payment_source_type;await setPaymentMethod({paymentResource,paymentMethodId});let attributes={};config!=null&&paymentResource==="paypal_payments"&&(attributes=getPaypalAttributes(paymentResource,config)),config!=null&&paymentResource==="external_payments"&&(attributes=getExternalPaymentAttributes(paymentResource,config));const ps=await setPaymentSource({paymentResource,order,attributes});ps&&paymentMethod&&onClick!=null&&(setPaymentSourceCreated(!0),onClick({payment:paymentMethod,order,paymentSource:ps}),setTimeout(()=>{setLoading(!1)},200)),getCustomerPaymentSources&&getCustomerPaymentSources(),setLoadingPlaceOrder({loading:!1})}typeof autoSelectSinglePaymentMethod=="function"&&autoSelectSinglePaymentMethod()}else setTimeout(()=>{setLoading(!1)},200)})())},[!isEmpty(paymentMethods),order?.payment_source!=null]),useEffect(()=>(paymentMethods&&(paymentMethods.length===1&&autoSelectSinglePaymentMethod?paymentSource&&setTimeout(()=>{setLoading(!1)},200):setLoading(!1)),currentPaymentMethodId&&setPaymentSelected(currentPaymentMethodId),()=>{setLoading(!0),setPaymentSelected("")}),[paymentMethods,currentPaymentMethodId]);const components=(paymentMethods!=null&&sortBy!=null?sortPaymentMethods(paymentMethods,sortBy):paymentMethods)?.filter(payment=>{if(Array.isArray(hide)){const source=payment?.payment_source_type;return!hide?.includes(source)}return typeof hide=="function"?hide(payment):!0}).map(payment=>{const isActive=currentPaymentMethodId===payment?.id,paymentMethodProps={payment,clickableContainer,paymentSelected,setPaymentSelected,expressPayments},paymentResource=payment?.payment_source_type,onClickable=clickableContainer?async e=>{e.stopPropagation();const paymentMethodId=payment?.id,currentPaymentMethodId2=order?.payment_method?.id;if(paymentMethodId===currentPaymentMethodId2||status==="placing")return;setLoadingPlaceOrder({loading:!0}),setPaymentSelected(payment.id);const{order:updatedOrder}=await setPaymentMethod({paymentResource,paymentMethodId});onClick&&onClick({payment,order:updatedOrder}),setLoadingPlaceOrder({loading:!1})}:void 0;return _jsx("div",{"data-testid":paymentResource,className:`${className??""} ${isActive&&activeClass!=null?activeClass:""}`,onClick:e=>{onClickable?.(e)},...p,children:_jsx(PaymentMethodChildrenContext.Provider,{value:paymentMethodProps,children})},paymentResource)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default PaymentMethod;
@@ -1,23 +1,65 @@
1
- import { type JSX } from 'react';
2
- import type { PaymentMethodConfig } from '../../reducers/PaymentMethodReducer';
3
- import type { PaymentSourceProps } from './PaymentSource';
4
- import { type FramesStyle } from 'frames-react';
1
+ import { type JSX } from "react";
2
+ import type { PaymentMethodConfig } from "../../reducers/PaymentMethodReducer";
3
+ import type { PaymentSourceProps } from "./PaymentSource";
4
+ interface Appearance {
5
+ colorAction: string;
6
+ colorBackground: string;
7
+ colorBorder: string;
8
+ colorDisabled: string;
9
+ colorError: string;
10
+ colorFormBackground: string;
11
+ colorFormBorder: string;
12
+ colorInverse: string;
13
+ colorOutline: string;
14
+ colorPrimary: string;
15
+ colorSecondary: string;
16
+ colorSuccess: string;
17
+ button: {
18
+ fontFamily: string;
19
+ fontSize: string;
20
+ fontWeight: number;
21
+ letterSpacing: number;
22
+ lineHeight: string;
23
+ };
24
+ footnote: {
25
+ fontFamily: string;
26
+ fontSize: string;
27
+ fontWeight: number;
28
+ letterSpacing: number;
29
+ lineHeight: string;
30
+ };
31
+ label: {
32
+ fontFamily: string;
33
+ fontSize: string;
34
+ fontWeight: number;
35
+ letterSpacing: number;
36
+ lineHeight: string;
37
+ };
38
+ subheading: {
39
+ fontFamily: string;
40
+ fontSize: string;
41
+ fontWeight: number;
42
+ letterSpacing: number;
43
+ lineHeight: string;
44
+ };
45
+ borderRadius: [string, string];
46
+ }
5
47
  export interface CheckoutComConfig {
6
48
  containerClassName?: string;
7
49
  hintLabel?: string;
8
50
  name?: string;
9
- success_url?: string;
10
- failure_url?: string;
51
+ success_url: string;
52
+ failure_url: string;
11
53
  options?: {
12
- style: FramesStyle;
54
+ appearance: Partial<Appearance>;
13
55
  };
14
56
  [key: string]: unknown;
15
57
  }
16
- type Props = PaymentMethodConfig['checkoutComPayment'] & JSX.IntrinsicElements['div'] & {
58
+ type Props = Partial<PaymentMethodConfig["checkoutComPayment"]> & JSX.IntrinsicElements["div"] & {
17
59
  show?: boolean;
18
60
  publicKey: string;
19
61
  locale?: string;
20
- templateCustomerSaveToWallet?: PaymentSourceProps['templateCustomerSaveToWallet'];
62
+ templateCustomerSaveToWallet?: PaymentSourceProps["templateCustomerSaveToWallet"];
21
63
  };
22
- export declare function CheckoutComPayment({ publicKey, options, locale, ...p }: Props): JSX.Element | null;
64
+ export declare function CheckoutComPayment({ publicKey, options, ...p }: Props): JSX.Element | null;
23
65
  export default CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Frames,CardNumber,ExpiryDate,Cvv}from"frames-react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://cdn.checkout.com/js/framesv2.min.js",systemLanguages=["DE-DE","EN-GB","ES-ES","FR-FR","IT-IT","KO-KR","NL-NL"],defaultOptions={style:{base:{color:"black",fontSize:"18px"},autofill:{backgroundColor:"yellow"},hover:{color:"blue"},focus:{color:"blue"},valid:{color:"green"},invalid:{color:"red"},placeholder:{base:{color:"gray"},focus:{border:"solid 1px blue"}}}};export function CheckoutComPayment({publicKey,options=defaultOptions,locale="EN-GB",...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p,handleSubmit=async()=>{const savePaymentSourceToCustomerWallet=ref?.current?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),window.Frames){window.Frames.cardholder={name:order?.billing_address?.full_name,billingAddress:{addressLine1:order?.billing_address?.line_1,addressLine2:order?.billing_address?.line_2??"",zip:order?.billing_address?.zip_code??"",city:order?.billing_address?.city,state:order?.billing_address?.state_code,country:order?.billing_address?.country_code},phone:order?.billing_address?.phone};try{const data=await window.Frames.submitCard();if(data.token&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{token:data.token,payment_type:"token",success_url:successUrl,failure_url:failureUrl,_authorize:!0}});ps?.redirect_uri&&(window.location.href=ps.redirect_uri)}}catch(error){console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error?.message}])}}return!1},lang=`${locale.toUpperCase()}-${locale.toUpperCase()}`,localization=systemLanguages.includes(lang)?lang:"EN-GB";return loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsxs(Frames,{config:{debug:!0,publicKey,localization,...options},cardValidationChanged:e=>{e.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(),setPaymentRef({ref}))},cardTokenized:data=>data,children:[_jsx(CardNumber,{}),_jsx(ExpiryDate,{}),_jsx(Cvv,{})]})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{jwt}from"../../utils/jwt";import CommerceLayerContext from"../../context/CommerceLayerContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://checkout-web-components.checkout.com/index.js";export function CheckoutComPayment({publicKey,options,...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{accessToken}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p;return useEffect(()=>{const ps=order?.payment_source;if(loaded&&window&&ps&&accessToken){const publicKey2=ps.public_key,paymentSession=ps.payment_session;if(window?.CheckoutWebComponents){const environment=jwt(accessToken).test?"sandbox":"production",locale=order?.language_code??"en";(async()=>{(await window.CheckoutWebComponents({appearance:{...options?.appearance},showPayButton:!1,publicKey:publicKey2,environment,locale,paymentSession,componentOptions:{card:{displayCardholderName:"hidden"}},onChange:component=>{component.isValid()&&ref.current&&(ref.current.onsubmit=async()=>{const savePaymentSourceToCustomerWallet=ref.current?.elements?.save_payment_source_to_customer_wallet?.checked;savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet);const{data}=await component.tokenize(),token=data?.token,paymentSource=await setPaymentSource({paymentSourceId:ps.id,paymentResource:"checkout_com_payments",attributes:{token,_authorize:!0}});if(paymentSource){const response=paymentSource.payment_response,securityRedirect=paymentSource?.redirect_uri;return response?.status.toLowerCase()==="pending"&&securityRedirect?(window.location.href=securityRedirect,!1):!0}return!1},setPaymentRef?.({ref}))},onError:(component,error)=>{console.error("onError",error,"Component",component.type)}})).create("flow").mount(document.getElementById("flow-container"))})()}}},[loaded,order?.payment_source?.id,accessToken]),loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"flow-container"})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(customerPaymentSourceId){if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}else{if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
2
+ import baseReducer from"../utils/baseReducer";import getErrors,{setErrors}from"../utils/getErrors";import getSdk from"../utils/getSdk";import{snakeToCamelCase}from"../utils/snakeToCamelCase";import{replace}from"../utils/replace";import{pick}from"../utils/pick";export function setLoading({loading,dispatch}){dispatch&&dispatch({type:"setLoading",payload:{loading}})}export const setPaymentRef=({ref,dispatch})=>{ref&&dispatch&&dispatch({type:"setPaymentRef",payload:{currentPaymentMethodRef:ref}})},paymentMethodInitialState={errors:[],paymentMethods:void 0},setPaymentMethodErrors=(errors,dispatch)=>{dispatch&&dispatch({type:"setErrors",payload:{errors}})},getPaymentMethods=async({order,dispatch})=>{const paymentMethods=order.available_payment_methods,paymentMethod=order.payment_method,paymentSource=order.payment_source;dispatch({type:"setPaymentMethods",payload:{paymentMethods,currentPaymentMethodId:paymentMethod?.id,currentPaymentMethodType:paymentMethod?.payment_source_type,paymentSource}})};export async function setPaymentMethod({config,dispatch,order,paymentMethodId,updateOrder,setOrderErrors,paymentResource}){let response={success:!1};try{if(config&&order&&dispatch&&paymentResource){localStorage.removeItem("_save_payment_source_to_customer_wallet");const attributes={payment_method:getSdk(config).payment_methods.relationship(paymentMethodId)};updateOrder!=null&&(response=await updateOrder({id:order.id,attributes})),dispatch({type:"setPaymentMethods",payload:{currentPaymentMethodId:paymentMethodId,currentPaymentMethodType:paymentResource,errors:[]}}),setOrderErrors&&setOrderErrors([])}return response}catch(error){const errors=getErrors({error,resource:"orders",field:paymentResource});return console.error("Set payment method",errors),response}}export async function setPaymentSource({config,dispatch,getOrder,attributes,order,paymentResource,customerPaymentSourceId,paymentSourceId,updateOrder,errors:currentErrors}){try{const isAlreadyPlaced=order?.status==="placed";if(config&&order&&!isAlreadyPlaced){let paymentSource;const sdk=getSdk(config);if(!customerPaymentSourceId){if(paymentSourceId){const attrs={id:paymentSourceId,...attributes};paymentSource=attributes!=null?await sdk[paymentResource].update(attrs):await sdk[paymentResource].retrieve(paymentSourceId)}else{const attrs={...attributes,order:sdk.orders.relationship(order.id)};paymentSource=await sdk[paymentResource].create(attrs)}return getOrder&&await getOrder(order.id),dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource,errors:[],currentCustomerPaymentSourceId:null}}),paymentSource}if(updateOrder!=null){const{order:orderUpdated}=await updateOrder({id:order.id,attributes:{_customer_payment_source_id:customerPaymentSourceId}});dispatch!=null&&orderUpdated!=null&&dispatch({type:"setPaymentSource",payload:{paymentSource:orderUpdated.payment_source,currentCustomerPaymentSourceId:orderUpdated.payment_source?.id}})}}}catch(error){const errors=getErrors({error,resource:"payment_methods",field:paymentResource});if(errors!=null&&errors?.length>0){const[error2]=errors;if(error2?.status==="401"&&getOrder!=null&&order!=null){const currentOrder=await getOrder(order?.id);currentOrder?.status!=null&&!["placed","approved"].includes(currentOrder.status)&&(console.error("Set payment source:",errors),setErrors({currentErrors,newErrors:errors,dispatch}))}}else setErrors({currentErrors,newErrors:errors,dispatch})}}export const updatePaymentSource=async({id,attributes,config,dispatch,paymentResource})=>{if(config)try{const paymentSource=await getSdk(config)[paymentResource].update({id,...attributes});dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource}})}catch(err){console.error("Update payment source:",err)}},destroyPaymentSource=async({paymentSourceId,paymentResource,dispatch})=>{paymentSourceId&&paymentResource&&dispatch&&dispatch({type:"setPaymentSource",payload:{paymentSource:void 0}})},setPaymentMethodConfig=(config,dispatch)=>{dispatch({type:"setPaymentMethodConfig",payload:{config}})};export function getPaymentConfig(paymentResource,config){const resourceKeys=replace(replace(paymentResource,"payments","payment"),"transfers","transfer"),resource=snakeToCamelCase(resourceKeys);return pick(config,[resource])}const type=["setErrors","setPaymentMethodConfig","setPaymentMethods","setPaymentSource","setPaymentRef","setLoading"],paymentMethodReducer=(state,reducer)=>baseReducer(state,reducer,type);export default paymentMethodReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0,session_id:options?.checkoutCom?.session_id});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
2
+ import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import{isDoNotShip,shipmentsFilled}from"../utils/shipments";import{saveBillingAddress,saveShippingAddress,saveToWallet}from"../utils/customerOrderOptions";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import{isGuestToken}from"../utils/isGuestToken";import{setCustomerOrderParam}from"../utils/localStorage";import{hasSubscriptions}from"../utils/hasSubscriptions";import{updateOrderSubscriptionCustomerPaymentSource}from"../utils/updateOrderSubscriptionCustomerPaymentSource";export function setButtonRef(ref,dispatch){ref?.current!=null&&dispatch({type:"setButtonRef",payload:{placeOrderButtonRef:ref}})}export const placeOrderInitialState={errors:[],isPermitted:!1,status:"standby"};export function setPlaceOrderErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function placeOrderPermitted({config,order,dispatch,options}){if(order&&config){let isPermitted=!0;order.privacy_url&&order.terms_url&&(isPermitted=localStorage.getItem("privacy-terms")==="true");const billingAddress=order.billing_address,shippingAddress=order.shipping_address,doNotShip=isDoNotShip(order.line_items),shipments=order.shipments,shipment=shipments&&shipmentsFilled(shipments),paymentMethod=order.payment_method,paymentSource=order.payment_source;order.total_amount_with_taxes_cents!==0&&isEmpty(paymentMethod?.id)&&(isPermitted=!1),isEmpty(billingAddress)&&(isPermitted=!1),isEmpty(shippingAddress)&&!doNotShip&&(isPermitted=!1),!isEmpty(shipments)&&!shipment&&(isPermitted=!1),paymentSource?.mismatched_amounts&&(isPermitted=!1),dispatch({type:"setPlaceOrderPermitted",payload:{isPermitted,paymentType:paymentMethod?.payment_source_type,paymentSecret:paymentSource?.client_secret,paymentId:paymentSource?.options?.id,paymentSource,options}})}}export async function setPlaceOrder({state,order,config,setOrderErrors,paymentSource,setOrder,include,currentCustomerPaymentSourceId}){const response={placed:!1};if(state&&config&&order){if(order?.status==="placed")return{placed:!0,order};const sdk=getSdk(config),{options,paymentType}=state;try{const lastOrderStatus=await sdk.orders.retrieve(order.id);if(lastOrderStatus.status==="placed")return{placed:!0,order:lastOrderStatus};if(paymentType==="paypal_payments"&&paymentSource?.type==="paypal_payments"){if(!options?.paypalPayerId&&paymentSource?.approval_url)return window.location.href=paymentSource?.approval_url,response;await sdk[paymentType].update({id:paymentSource.id,paypal_payer_id:options?.paypalPayerId})}if(paymentType==="checkout_com_payments"&&paymentSource&&options?.checkoutCom?.session_id){const payment=await sdk[paymentType].update({id:paymentSource.id,_details:!0});if(payment?.payment_response?.status!=="Authorized"){const[action]=payment?.payment_response?.actions||[""];throw{errors:[{code:"PAYMENT_NOT_APPROVED_FOR_EXECUTION",message:action?.response_summary,resource:"orders",field:"checkout_com_payments"}]}}}const updateAttributes={id:order.id,_place:!0};if(saveBillingAddress()&&await sdk.orders.update({id:order.id,_save_billing_address_to_customer_address_book:!0}),saveShippingAddress()&&await sdk.orders.update({id:order.id,_save_shipping_address_to_customer_address_book:!0}),paymentType==="stripe_payments"&&paymentSource!=null){const ps=paymentSource,currentUrl=window.location.href,returnUrl=ps?.options?.return_url;currentUrl!==returnUrl&&await sdk[paymentType].update({id:paymentSource.id,options:{return_url:currentUrl}})}switch(hasSubscriptions(order)&&config?.accessToken!=null&&!isGuestToken(config.accessToken)&&currentCustomerPaymentSourceId==null&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","true"),paymentType){case"braintree_payments":{const total=order?.total_amount_cents??0;await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0})]);const orderUpdated=await sdk.orders.update(updateAttributes,{include});return setOrder&&setOrder(orderUpdated),setOrderErrors&&setOrderErrors([]),updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk),{placed:!0,order:orderUpdated}}default:{const orderUpdated=await sdk.orders.update(updateAttributes,{include}),total=orderUpdated?.total_amount_cents??0;return setOrder&&setOrder(orderUpdated),await Promise.all([saveToWallet()&&total>0&&sdk.orders.update({id:order.id,_save_payment_source_to_customer_wallet:!0}).catch(error=>{const errors=getErrors({error,resource:"orders",field:paymentType});setOrderErrors&&setOrderErrors(errors)})]).then(()=>{updateOrderSubscriptionCustomerPaymentSource(orderUpdated,paymentType,sdk)}),{placed:!0,order:orderUpdated}}}}catch(error){const errors=getErrors({error,resource:"orders",field:paymentType});return setOrderErrors&&setOrderErrors(errors),{...response,errors}}}return response}export function setPlaceOrderStatus({status,dispatch}){dispatch?.({type:"setStatus",payload:{status}})}const type=["setErrors","setPlaceOrderPermitted","setButtonRef","setStatus"],placeOrderReducer=(state,reducer)=>baseReducer(state,reducer,type);export default placeOrderReducer;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export default function getCardDetails({paymentType,customerPayment}){switch(paymentType){case"checkout_com_payments":{const source=customerPayment.payment_source?.payment_response?.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=ps?.options?.card??ps?.payment_method?.card??ps?.payment_instrument?{brand:ps?.payment_instrument?.card_type,exp_month:ps?.payment_instrument?.card_expiry_month,exp_year:ps?.payment_instrument?.card_expiry_year,last4:ps?.payment_instrument?.card_last_digits,issuer_type:ps?.payment_instrument?.issuer_type}:void 0;if(source?.brand!=null)return{...source};break}case"klarna_payments":{const ps=customerPayment.payment_source,source=ps?.auth_token!=null&&ps?.payment_instrument!=null?{brand:"klarna",exp_month:"",exp_year:"",last4:"",issuer_type:ps?.payment_instrument?.issuer_type}:void 0;if(source)return{...source};break}case"braintree_payments":{const source=customerPayment.payment_source?.options?.card;if(source)return{...source};break}case"adyen_payments":{const ps=customerPayment.payment_source,source=ps?.payment_request_data?.payment_method,authorized=ps?.payment_response?.resultCode==="Authorised",last4=ps?.payment_response?.additionalData?.cardSummary??ps?.payment_instrument?.card_last_digits??"****";if(source&&authorized){const brand=source.type==="scheme"?source.brand??"credit-card":source.type.replace("_account","");return{...source,last4,brand}}break}default:{const ps=customerPayment.payment_source;if(ps?.type!==paymentType)break;const source=ps?.metadata?.card??{brand:ps?.payment_instrument?.issuer_type.replace("_","-")??"",last4:ps?.metadata?.last4??"",exp_month:ps?.metadata?.exp_month??"",exp_year:ps?.metadata?.exp_year??""};if(source)return{...source};break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****",issuer_type:""}}
2
+ export default function getCardDetails({paymentType,customerPayment}){switch(paymentType){case"checkout_com_payments":{const source=customerPayment.payment_source?.payment_response?.source;if(source)return{brand:source.scheme.toLowerCase(),exp_month:source.expiry_month,exp_year:source.expiry_year,last4:source.last4};break}case"stripe_payments":{const ps=customerPayment.payment_source,source=ps?.options?.card??ps?.payment_method?.card??ps?.payment_instrument?{brand:ps?.payment_instrument?.card_type,exp_month:ps?.payment_instrument?.card_expiry_month,exp_year:ps?.payment_instrument?.card_expiry_year,last4:ps?.payment_instrument?.card_last_digits,issuer_type:ps?.payment_instrument?.issuer_type}:void 0;if(source?.brand!=null)return{...source};break}case"klarna_payments":{const ps=customerPayment.payment_source,source=ps?.auth_token!=null&&ps?.payment_instrument!=null?{brand:"klarna",exp_month:"",exp_year:"",last4:"",issuer_type:ps?.payment_instrument?.issuer_type}:void 0;if(source)return{...source};break}case"braintree_payments":{const source=customerPayment.payment_source?.options?.card;if(source)return{...source};break}case"adyen_payments":{const ps=customerPayment.payment_source,source=ps?.payment_request_data?.payment_method,authorized=ps?.payment_response?.resultCode==="Authorised",last4=ps?.payment_response?.additionalData?.cardSummary??ps?.payment_instrument?.card_last_digits??"****";if(source&&authorized){const brand=source.type==="scheme"?source.brand??"credit-card":source.type.replace("_account","");return{...source,last4,brand}}break}default:{const ps=customerPayment.payment_source;if(ps?.type!==paymentType)break;const source=ps?.metadata?.card??{brand:ps?.payment_instrument?.issuer_type?.replace("_","-")??"",last4:ps?.metadata?.last4??"",exp_month:ps?.metadata?.exp_month??"",exp_year:ps?.metadata?.exp_year??""};if(source)return{...source};break}}return{brand:"",exp_month:"**",exp_year:"**",last4:"****",issuer_type:""}}
@@ -1,17 +1,19 @@
1
- import type { PaypalConfig } from '../components/payment_source/PaypalPayment';
2
- import { type PaymentMethodConfig, type PaymentResource } from '../reducers/PaymentMethodReducer';
3
- import type { ExternalPayment } from '@commercelayer/sdk';
4
- import { type StringReplace } from './replace';
5
- import { type SnakeToCamelCase } from './snakeToCamelCase';
6
- import type { StripeConfig } from '../components/payment_source/StripePayment';
1
+ import type { PaypalConfig } from "../components/payment_source/PaypalPayment";
2
+ import { type PaymentMethodConfig, type PaymentResource } from "../reducers/PaymentMethodReducer";
3
+ import type { ExternalPayment } from "@commercelayer/sdk";
4
+ import { type StringReplace } from "./replace";
5
+ import { type SnakeToCamelCase } from "./snakeToCamelCase";
6
+ import type { StripeConfig } from "../components/payment_source/StripePayment";
7
+ import type { CheckoutComConfig } from "../components/payment_source/CheckoutComPayment";
7
8
  interface Params<R extends PaymentResource, C extends PaymentMethodConfig> {
8
9
  resource: R;
9
10
  config: C;
10
11
  keys: R[];
11
12
  }
12
- export type ResourceKeys<K extends PaymentResource> = SnakeToCamelCase<StringReplace<StringReplace<K, 'payments', 'payment'>, 'transfers', 'transfer'>>;
13
+ export type ResourceKeys<K extends PaymentResource> = SnakeToCamelCase<StringReplace<StringReplace<K, "payments", "payment">, "transfers", "transfer">>;
13
14
  export declare function getPaymentAttributes<R extends PaymentResource = PaymentResource, C extends PaymentMethodConfig = PaymentMethodConfig>(params: Params<R, C>): Pick<C, ResourceKeys<R>> | undefined;
14
- export declare function getPaypalAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<PaypalConfig, 'return_url' | 'cancel_url'> | undefined;
15
- export declare function getExternalPaymentAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<ExternalPayment, 'payment_source_token'> | undefined;
16
- export declare function getStripeAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<StripeConfig, 'return_url'> | undefined;
15
+ export declare function getPaypalAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<PaypalConfig, "return_url" | "cancel_url"> | undefined;
16
+ export declare function getExternalPaymentAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<ExternalPayment, "payment_source_token"> | undefined;
17
+ export declare function getStripeAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<StripeConfig, "return_url"> | undefined;
18
+ export declare function getCkoAttributes(paymentResource: PaymentResource, config: PaymentMethodConfig): Pick<CheckoutComConfig, "success_url" | "failure_url"> | undefined;
17
19
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{getPaymentConfig}from"../reducers/PaymentMethodReducer";import{pick}from"./pick";import{replace}from"./replace";import{snakeToCamelCase}from"./snakeToCamelCase";export function getPaymentAttributes(params){const{resource,config,keys}=params,attributes=getPaymentConfig(resource,config),keysCamelCase=keys.map(key=>{const k=replace(replace(key,"payments","payment"),"transfers","transfer");return snakeToCamelCase(k)}),currentResource=snakeToCamelCase(replace(replace(resource,"payments","payment"),"transfers","transfer"));return attributes!=null&&currentResource in attributes?pick(attributes,keysCamelCase):void 0}export function getPaypalAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["paypal_payments"]});return attributes?.paypalPayment!=null&&"paypalPayment"in attributes?pick(attributes?.paypalPayment,["return_url","cancel_url"]):void 0}export function getExternalPaymentAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["external_payments"]});return attributes?.externalPayment!=null&&"externalPayment"in attributes?pick(attributes?.externalPayment,["payment_source_token"]):void 0}export function getStripeAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["stripe_payments"]});return attributes?.stripePayment!=null&&"stripePayment"in attributes?pick(attributes?.stripePayment,["return_url"]):void 0}
2
+ import{getPaymentConfig}from"../reducers/PaymentMethodReducer";import{pick}from"./pick";import{replace}from"./replace";import{snakeToCamelCase}from"./snakeToCamelCase";export function getPaymentAttributes(params){const{resource,config,keys}=params,attributes=getPaymentConfig(resource,config),keysCamelCase=keys.map(key=>{const k=replace(replace(key,"payments","payment"),"transfers","transfer");return snakeToCamelCase(k)}),currentResource=snakeToCamelCase(replace(replace(resource,"payments","payment"),"transfers","transfer"));return attributes!=null&&currentResource in attributes?pick(attributes,keysCamelCase):void 0}export function getPaypalAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["paypal_payments"]});return attributes?.paypalPayment!=null&&"paypalPayment"in attributes?pick(attributes?.paypalPayment,["return_url","cancel_url"]):void 0}export function getExternalPaymentAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["external_payments"]});return attributes?.externalPayment!=null&&"externalPayment"in attributes?pick(attributes?.externalPayment,["payment_source_token"]):void 0}export function getStripeAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["stripe_payments"]});return attributes?.stripePayment!=null&&"stripePayment"in attributes?pick(attributes?.stripePayment,["return_url"]):void 0}export function getCkoAttributes(paymentResource,config){const attributes=getPaymentAttributes({resource:paymentResource,config,keys:["checkout_com_payments"]});return attributes?.checkoutComPayment!=null&&"checkoutComPayment"in attributes?pick(attributes?.checkoutComPayment,["success_url","failure_url"]):void 0}
@@ -2,4 +2,13 @@ export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U
2
2
  export type SnakeToCamelCaseNested<T> = T extends object ? {
3
3
  [K in keyof T as SnakeToCamelCase<K & string>]: SnakeToCamelCaseNested<T[K]>;
4
4
  } : T;
5
+ /**
6
+ *
7
+ * @param value - The string to convert from snake_case to camelCase
8
+ * @example
9
+ * snakeToCamelCase("hello_world") // "helloWorld"
10
+ * snakeToCamelCase("hello_world_test") // "helloWorldTest"
11
+ * @returns string
12
+ * @description Converts a string from snake_case to camelCase
13
+ */
5
14
  export declare function snakeToCamelCase<S extends string>(value: S): SnakeToCamelCase<S>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export function snakeToCamelCase(value){const words=value.toLowerCase().split("_"),first=words[0]??"",firstLetter=words[1]?.[0]?.toUpperCase()??"",second=words[1]?.substring(1)??"";return`${first}${firstLetter}${second}`}
2
+ export function snakeToCamelCase(value){const words=value.toLowerCase().split("_"),first=words[0]??"",secondLetter=words[1]?.[0]?.toUpperCase()??"",second=words[1]?.substring(1)??"",thirdLetter=words[2]?.[0]?.toUpperCase()??"",third=words[2]?.substring(1)??"";return`${first}${secondLetter}${second}${thirdLetter}${third}`}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/react-components",
3
- "version": "4.22.0-beta.0",
3
+ "version": "4.23.0",
4
4
  "description": "The Official Commerce Layer React Components",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",