@commercelayer/react-components 4.28.4-beta.1 → 4.28.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.d.ts +1 -1
- package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +3 -3
- package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
- package/lib/cjs/components/gift_cards/GiftCardOrCouponSubmit.d.ts +1 -1
- package/lib/cjs/components/orders/GiftCardAmount.d.ts +1 -1
- package/lib/cjs/components/orders/GiftCardAmount.js +1 -1
- package/lib/cjs/components/orders/OrderContainer.d.ts +0 -4
- package/lib/cjs/components/orders/OrderContainer.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderButton.js +1 -1
- package/lib/cjs/components/orders/TotalAmount.d.ts +1 -1
- package/lib/cjs/components/orders/TotalAmount.js +1 -1
- package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
- package/lib/cjs/reducers/AddressReducer.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +1 -1
- package/lib/cjs/utils/adyen/manageGiftCard.js +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponCode.d.ts +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponCode.js +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +3 -3
- package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
- package/lib/esm/components/gift_cards/GiftCardOrCouponSubmit.d.ts +1 -1
- package/lib/esm/components/orders/GiftCardAmount.d.ts +1 -1
- package/lib/esm/components/orders/GiftCardAmount.js +1 -1
- package/lib/esm/components/orders/OrderContainer.d.ts +0 -4
- package/lib/esm/components/orders/OrderContainer.js +1 -1
- package/lib/esm/components/orders/PlaceOrderButton.js +1 -1
- package/lib/esm/components/orders/TotalAmount.d.ts +1 -1
- package/lib/esm/components/orders/TotalAmount.js +1 -1
- package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
- package/lib/esm/reducers/AddressReducer.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +1 -1
- package/lib/esm/utils/adyen/manageGiftCard.js +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type JSX } from "react";
|
|
2
|
-
import type { ChildrenFunction } from "../../typings/index";
|
|
3
2
|
import type { CodeType } from "../../reducers/OrderReducer";
|
|
3
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
4
4
|
interface ChildrenProps extends Omit<Props, "children" | "type"> {
|
|
5
5
|
code?: string | null;
|
|
6
6
|
hide?: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardOrCouponCode=GiftCardOrCouponCode;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard");function GiftCardOrCouponCode({children,type,...props}){const{order,
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardOrCouponCode=GiftCardOrCouponCode;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard");function GiftCardOrCouponCode({children,type,...props}){const{order,managePaymentProviderGiftCards}=(0,react_1.useContext)(OrderContext_1.default);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);if(managePaymentProviderGiftCards&&type==="gift_card"){const giftCardData=(0,manageGiftCard_1.manageGiftCard)({order});if(!giftCardData)return null;hide=!1;const parentProps2={...props,code:`${giftCardData.cardBrand} ${giftCardData.cardSummary}`,hide};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps2,children}):hide?null:(0,jsx_runtime_1.jsx)("span",{...props,children:code})}const parentProps={...props,code,hide,discountAmountCents:order?.discount_amount_cents,discountAmountFloat:order?.discount_amount_float,formattedDiscountAmount:order?.formatted_discount_amount};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):hide?null:(0,jsx_runtime_1.jsx)("span",{...props,children:code})}exports.default=GiftCardOrCouponCode;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { type ReactNode, type JSX } from "react";
|
|
2
|
-
import type { ChildrenFunction } from "../../typings/index";
|
|
3
|
-
import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
|
|
4
1
|
import type { Order } from "@commercelayer/sdk";
|
|
2
|
+
import { type JSX, type ReactNode } from "react";
|
|
3
|
+
import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
|
|
4
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
5
5
|
interface ChildrenProps extends Omit<Props, "children" | "onClick"> {
|
|
6
6
|
codeType?: OrderCodeType;
|
|
7
7
|
hide?: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardOrCouponRemoveButton=GiftCardOrCouponRemoveButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard");function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode,
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardOrCouponRemoveButton=GiftCardOrCouponRemoveButton;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard");function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode,managePaymentProviderGiftCards,paymentSourceRequest}=(0,react_1.useContext)(OrderContext_1.default);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);const handleClick=async()=>{if(managePaymentProviderGiftCards&&codeType==="gift_card_code"&&order!=null){const id=order?.payment_source?.id;if(id!=null){const res=await paymentSourceRequest({resource:"adyen_payments",requestType:"update",attributes:{id,payment_request_data:{}},order});onClick!=null&&res!=null&&onClick(res)}}else if(codeType!=null&&removeGiftCardOrCouponCode!=null){const response=await removeGiftCardOrCouponCode({codeType});onClick!=null&&response!=null&&onClick(response)}};if(managePaymentProviderGiftCards&&type==="gift_card"){if(!(0,manageGiftCard_1.manageGiftCard)({order}))return null;hide=!1;const parentProps2={...p,label,handleClick,codeType};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps2,children}):hide?null:(0,jsx_runtime_1.jsx)("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}const parentProps={...p,label,handleClick,codeType};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):hide?null:(0,jsx_runtime_1.jsx)("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}exports.default=GiftCardOrCouponRemoveButton;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseAmountComponent } from "../../typings/index";
|
|
2
1
|
import { type JSX } from "react";
|
|
2
|
+
import type { BaseAmountComponent } from "../../typings/index";
|
|
3
3
|
export declare function GiftCardAmount(props: BaseAmountComponent): JSX.Element | null;
|
|
4
4
|
export default GiftCardAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardAmount=GiftCardAmount;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GiftCardAmount=GiftCardAmount;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard"),BaseOrderPrice_1=tslib_1.__importDefault(require("../utils/BaseOrderPrice"));function GiftCardAmount(props){const{managePaymentProviderGiftCards,order}=(0,react_1.useContext)(OrderContext_1.default);if(managePaymentProviderGiftCards){const giftCardData=(0,manageGiftCard_1.manageGiftCard)({order});if(!giftCardData)return null;const parentProps={priceCents:giftCardData.currentBalanceValue,price:`-${giftCardData?.formattedBalanceValue}`,...props};return props.children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children:props.children}):(0,jsx_runtime_1.jsx)("span",{...props,children:`-${giftCardData?.formattedBalanceValue}`})}return(0,jsx_runtime_1.jsx)(BaseOrderPrice_1.default,{base:"amount",type:"gift_card",...props})}exports.default=GiftCardAmount;
|
|
@@ -20,10 +20,6 @@ interface Props {
|
|
|
20
20
|
* Callback called when the order is updated
|
|
21
21
|
*/
|
|
22
22
|
fetchOrder?: (order: Order) => void;
|
|
23
|
-
/**
|
|
24
|
-
* Indicate if Adyen gift card management is enabled
|
|
25
|
-
*/
|
|
26
|
-
manageAdyenGiftCard?: boolean;
|
|
27
23
|
}
|
|
28
24
|
/**
|
|
29
25
|
* This component is responsible for fetching the order and store it in its context.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=OrderContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.OrderContainer=OrderContainer;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importStar(require("../../context/OrderContext")),OrderStorageContext_1=tslib_1.__importDefault(require("../../context/OrderStorageContext")),OrderReducer_1=tslib_1.__importStar(require("../../reducers/OrderReducer")),compareObjAttribute_1=tslib_1.__importDefault(require("../../utils/compareObjAttribute")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext"));function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=(0,react_1.useReducer)(OrderReducer_1.default,OrderReducer_1.orderInitialState),[lock,setLock]=(0,react_1.useState)(!1),[lockOrder,setLockOrder]=(0,react_1.useState)(!0),config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=(0,react_1.useContext)(OrderStorageContext_1.default),getOrder=async localOrder=>{const removeOrderPlaced=!!(persistKey&&clearWhenPlaced);localOrder&&await(0,OrderReducer_1.getApiOrder)({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:removeOrderPlaced,deleteLocalOrder,state})};(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),(0,react_1.useEffect)(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),(0,react_1.useEffect)(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});Object.keys(updateAttributes).length>0&&((0,OrderReducer_1.updateOrder)({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=(0,compareObjAttribute_1.default)({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),(0,react_1.useEffect)(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=(0,react_1.useMemo)(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,managePaymentProviderGiftCards:state.order?.payment_source?.payment_request_data?.payment_method?.type==="giftcard",paymentSourceRequest:async params=>await(0,OrderReducer_1.paymentSourceRequest)({...params,dispatch,state,config}),setOrder:order=>{(0,OrderReducer_1.setOrder)(order,dispatch)},getOrder:async id=>await(0,OrderReducer_1.getApiOrder)({id,dispatch,config,state}),setOrderErrors:errors=>(0,OrderReducer_1.setOrderErrors)({dispatch,errors}),createOrder:async()=>await(0,OrderReducer_1.createOrder)({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await(0,OrderReducer_1.addToCart)({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{OrderContext_1.defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await OrderContext_1.defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await OrderContext_1.defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{OrderContext_1.defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await OrderContext_1.defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state}),getOrderByFields:OrderReducer_1.getOrderByFields}),[state,config.accessToken,persistKey]);return(0,jsx_runtime_1.jsx)(OrderContext_1.default.Provider,{value:orderValue,children})}exports.default=OrderContainer;
|
|
@@ -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"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{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||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status;if(console.log("Adyen redirect flow check",{isAuthorized,paymentDetails,redirectResult:options?.adyen?.redirectResult,status,paymentStatus:order?.payment_status}),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 resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&autoPlaceOrder&&status==="standby"&&(console.log("Adyen order is authorized, placing order..."),handleClick())}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status"]});console.log("PlaceOrderButton order status check",{status:status2,paymentStatus});const isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({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)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0)),console.log("PlaceOrderButton isValid",{isValid,currentPaymentStatus});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"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{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"),isFunction_1=tslib_1.__importDefault(require("lodash/isFunction")),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),useCommerceLayer_1=tslib_1.__importDefault(require("../../hooks/useCommerceLayer")),getCardDetails_1=tslib_1.__importDefault(require("../../utils/getCardDetails")),retrievePaymentIntent_1=require("../../utils/stripe/retrievePaymentIntent"),Parent_1=tslib_1.__importDefault(require("../utils/Parent"));function PlaceOrderButton(props){const ref=(0,react_1.useRef)(null),{children,label="Place order",loadingLabel="Placing...",autoPlaceOrder=!0,disabled,onClick,...p}=props,{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),{sdkClient}=(0,useCommerceLayer_1.default)(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,setOrderErrors,errors}=(0,react_1.useContext)(OrderContext_1.default),isFree=order?.total_amount_with_taxes_cents===0;(0,react_1.useEffect)(()=>{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||currentPaymentMethodRef?.current?.onsubmit||card.brand)&&isPermitted&&setNotPermitted(!1)}else setNotPermitted(!(isFree&&isPermitted));return()=>{setNotPermitted(!0)}},[isPermitted,paymentType!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),(0,react_1.useEffect)(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),(0,react_1.useEffect)(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),(0,react_1.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(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()}},[options?.stripe?.paymentIntentClientSecret!=null,paymentType!=null,order?.payment_source!=null]),(0,react_1.useEffect)(()=>{if(order?.status!=null&&["draft","pending"].includes(order?.status)){const isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status;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 resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&autoPlaceOrder&&status==="standby"&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),(0,react_1.useEffect)(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),(0,react_1.useEffect)(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),(0,react_1.useEffect)(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),(0,react_1.useEffect)(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!0);const checkPaymentSource=paymentType!=="stripe_payments"?await setPaymentSource({paymentResource:paymentType,paymentSourceId:paymentSource?.id}):paymentSource,card=paymentType&&(0,getCardDetails_1.default)({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)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:(0,isFunction_1.default)(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}exports.default=PlaceOrderButton;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseAmountComponent } from "../../typings/index";
|
|
2
1
|
import { type JSX } from "react";
|
|
2
|
+
import type { BaseAmountComponent } from "../../typings/index";
|
|
3
3
|
export declare function TotalAmount(props: BaseAmountComponent): JSX.Element | null;
|
|
4
4
|
export default TotalAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TotalAmount=TotalAmount;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TotalAmount=TotalAmount;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),manageGiftCard_1=require("../../utils/adyen/manageGiftCard"),BaseOrderPrice_1=tslib_1.__importDefault(require("../utils/BaseOrderPrice"));function TotalAmount(props){const{managePaymentProviderGiftCards,order}=(0,react_1.useContext)(OrderContext_1.default);if(managePaymentProviderGiftCards){const giftCardData=(0,manageGiftCard_1.manageGiftCard)({order});if(!giftCardData)return(0,jsx_runtime_1.jsx)(BaseOrderPrice_1.default,{base:"total_amount",type:"with_taxes",...props});const parentProps={price:`${giftCardData?.formattedOrderTotal}`,...props};return props.children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children:props.children}):(0,jsx_runtime_1.jsx)("span",{...props,children:`${giftCardData?.formattedOrderTotal}`})}return(0,jsx_runtime_1.jsx)(BaseOrderPrice_1.default,{base:"total_amount",type:"with_taxes",...props})}exports.default=TotalAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),auto_1=require("@adyen/adyen-web/auto"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),getPublicIp_1=require("../../utils/getPublicIp"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),localStorage_1=require("../../utils/localStorage"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_1.default),{placeOrderButtonRef,setPlaceOrder,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.getPublicIP)(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(console.log("onSubmit controlCode:",{paymentStatus,controlCode,paymentMethodType,currentPaymentMethodType:currentPaymentMethodType2,control,order}),controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return console.log("return resultCode",{controlCode,paymentMethodType,paymentStatus}),{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...(0,browserInfo_1.default)()}}};delete attributes.payment_request_data.paymentMethod;try{const psUp=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes});if(console.log("Payment source updated:",psUp),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(console.log("Submitting payment with method:",currentPaymentMethodType2),currentPaymentMethodType2==="giftcard"){const giftCardBalanceCheck=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}),currentBalance=giftCardBalanceCheck?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0,attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0};console.log("Gift card balance check:",{giftCardBalanceCheck,attributes:attributes2});const{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2});console.log("First gift card authorization:",orderUpdated);const resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return console.log("Gift card authorized:",{resultCode:resultCode2,action:action2,orderUpdated,paymentStatus:paymentStatus2}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return(0,react_1.useEffect)(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);console.log("onSubmit resultCode:",{resultCode,action,message,paymentStatus}),["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdyenPayment=AdyenPayment;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),auto_1=require("@adyen/adyen-web/auto"),react_1=require("react"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),CustomerContext_1=tslib_1.__importDefault(require("../../context/CustomerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PlaceOrderContext_1=tslib_1.__importDefault(require("../../context/PlaceOrderContext")),browserInfo_1=tslib_1.__importStar(require("../../utils/browserInfo")),getPublicIp_1=require("../../utils/getPublicIp"),hasSubscriptions_1=require("../../utils/hasSubscriptions"),localStorage_1=require("../../utils/localStorage"),defaultConfig={};function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=(0,react_1.useState)(!1),[checkout,setCheckout]=(0,react_1.useState)(),[giftcardError,setGiftcardError]=(0,react_1.useState)(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=(0,react_1.useContext)(PaymentMethodContext_1.default),{order,updateOrder,getOrderByFields}=(0,react_1.useContext)(OrderContext_1.default),authConfig=(0,react_1.useContext)(CommerceLayerContext_1.default),{placeOrderButtonRef,setPlaceOrder,status}=(0,react_1.useContext)(PlaceOrderContext_1.default),{customers}=(0,react_1.useContext)(CustomerContext_1.default),ref=(0,react_1.useRef)(null),dropinRef=(0,react_1.useRef)(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=(0,browserInfo_1.cleanUrlBy)(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await(0,getPublicIp_1.getPublicIP)(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...(0,browserInfo_1.default)()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0,attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return(0,react_1.useEffect)(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&(0,hasSubscriptions_1.hasSubscriptions)(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&(0,localStorage_1.setCustomerOrderParam)("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await(0,auto_1.AdyenCheckout)(options),dropin=new auto_1.Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:(0,jsx_runtime_1.jsxs)("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[(0,jsx_runtime_1.jsx)("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&(0,jsx_runtime_1.jsx)(Parent_1.default,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}exports.default=AdyenPayment;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),formCleaner_1=require("../utils/formCleaner"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...(0,formCleaner_1.formCleaner)(values)}};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config),billingAddress=(0,formCleaner_1.formCleaner)(billingAddressForm),shippingAddress=(0,formCleaner_1.formCleaner)(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?(address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(!shipToDifferentAddress&&billingAddressCloneId&&(
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setCloneAddress=exports.setAddressErrors=exports.addressInitialState=exports.addressFields=void 0,exports.setAddress=setAddress,exports.saveAddresses=saveAddresses;const tslib_1=require("tslib"),camelCase_1=tslib_1.__importDefault(require("lodash/camelCase")),addressesManager_1=require("../utils/addressesManager"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),formCleaner_1=require("../utils/formCleaner"),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk"));exports.addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],exports.addressInitialState={errors:[]};const setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};exports.setAddressErrors=setAddressErrors;function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...(0,formCleaner_1.formCleaner)(values)}};dispatch&&dispatch({type:"setAddress",payload})}const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${(0,camelCase_1.default)(resource)}Id`]:id}})};exports.setCloneAddress=setCloneAddress;async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=(0,getSdk_1.default)(config),billingAddress=(0,formCleaner_1.formCleaner)(billingAddressForm),shippingAddress=(0,formCleaner_1.formCleaner)(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await(0,addressesManager_1.invertedAddressesHandler)({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?(address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(!shipToDifferentAddress&&billingAddressCloneId&&(orderAttributes._shipping_address_same_as_billing=!0,orderAttributes._shipping_address_clone_id=billingAddressCloneId),shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=(0,addressesManager_1.sanitizeMetadataFields)(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?(address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder)return{success:!0,order:(await updateOrder({id:order.id,attributes:orderAttributes}))?.order}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>(0,baseReducer_1.default)(state,reducer,type);exports.default=addressReducer;
|
|
@@ -37,7 +37,7 @@ export interface OrderPayload {
|
|
|
37
37
|
include?: ResourceIncluded[] | undefined;
|
|
38
38
|
includeLoaded?: ResourceIncludedLoaded;
|
|
39
39
|
withoutIncludes?: boolean;
|
|
40
|
-
|
|
40
|
+
managePaymentProviderGiftCards?: boolean;
|
|
41
41
|
}
|
|
42
42
|
export type AddToCartImportValues = Pick<AddToCartImportParams, "lineItems">;
|
|
43
43
|
export type getOrderContext = (id: string) => Promise<undefined | Order>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.manageGiftCard=manageGiftCard;function manageGiftCard({order}){if(!order||!order?.payment_source)return null;const getPaymentSource=order.payment_source?.type==="adyen_payments"?order.payment_source:null;if(!getPaymentSource||getPaymentSource?.payment_response?.errorCode
|
|
2
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.manageGiftCard=manageGiftCard;function manageGiftCard({order}){if(!order||!order?.payment_source)return null;const getPaymentSource=order.payment_source?.type==="adyen_payments"?order.payment_source:null;if(!getPaymentSource||getPaymentSource?.payment_response?.errorCode||!(getPaymentSource?.payment_request_data?.payment_method?.type==="giftcard"))return null;const additionalData=getPaymentSource?.payment_response?.additionalData,amount=getPaymentSource?.payment_response?.amount?.value,giftCardData={cardSummary:additionalData?.cardSummary,currentBalanceValue:amount??Number.parseInt(additionalData?.currentBalanceValue),currentBalanceCurrency:additionalData?.currentBalanceCurrency,cardBrand:additionalData?.originalSelectedBrand??additionalData?.paymentMethod,formattedBalanceValue:additionalData?.currentBalanceValue},formattedOrderTotal=((order?.total_amount_with_taxes_cents!=null?order?.total_amount_with_taxes_cents-giftCardData.currentBalanceValue:0)/100).toLocaleString(order.language_code??"en",{style:"currency",currency:order?.currency_code??"USD"}),formattedCurrentBalance=(giftCardData.currentBalanceValue/100).toLocaleString(order.language_code??"en",{style:"currency",currency:order?.currency_code??"USD"});return giftCardData.formattedBalanceValue=formattedCurrentBalance,{...giftCardData,formattedOrderTotal}}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type JSX } from "react";
|
|
2
|
-
import type { ChildrenFunction } from "../../typings/index";
|
|
3
2
|
import type { CodeType } from "../../reducers/OrderReducer";
|
|
3
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
4
4
|
interface ChildrenProps extends Omit<Props, "children" | "type"> {
|
|
5
5
|
code?: string | null;
|
|
6
6
|
hide?: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponCode({children,type,...props}){const{order,
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponCode({children,type,...props}){const{order,managePaymentProviderGiftCards}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);if(managePaymentProviderGiftCards&&type==="gift_card"){const giftCardData=manageGiftCard({order});if(!giftCardData)return null;hide=!1;const parentProps2={...props,code:`${giftCardData.cardBrand} ${giftCardData.cardSummary}`,hide};return children?_jsx(Parent,{...parentProps2,children}):hide?null:_jsx("span",{...props,children:code})}const parentProps={...props,code,hide,discountAmountCents:order?.discount_amount_cents,discountAmountFloat:order?.discount_amount_float,formattedDiscountAmount:order?.formatted_discount_amount};return children?_jsx(Parent,{...parentProps,children}):hide?null:_jsx("span",{...props,children:code})}export default GiftCardOrCouponCode;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { type ReactNode, type JSX } from "react";
|
|
2
|
-
import type { ChildrenFunction } from "../../typings/index";
|
|
3
|
-
import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
|
|
4
1
|
import type { Order } from "@commercelayer/sdk";
|
|
2
|
+
import { type JSX, type ReactNode } from "react";
|
|
3
|
+
import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
|
|
4
|
+
import type { ChildrenFunction } from "../../typings/index";
|
|
5
5
|
interface ChildrenProps extends Omit<Props, "children" | "onClick"> {
|
|
6
6
|
codeType?: OrderCodeType;
|
|
7
7
|
hide?: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode,
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode,managePaymentProviderGiftCards,paymentSourceRequest}=useContext(OrderContext);let codeType=type?`${type}_code`:void 0;!type&&order&&"coupon_code"in order&&order.coupon_code!==""?codeType="coupon_code":type||(codeType="gift_card_code");const code=order&&codeType?order[codeType]:"";let hide=!(order&&code);const handleClick=async()=>{if(managePaymentProviderGiftCards&&codeType==="gift_card_code"&&order!=null){const id=order?.payment_source?.id;if(id!=null){const res=await paymentSourceRequest({resource:"adyen_payments",requestType:"update",attributes:{id,payment_request_data:{}},order});onClick!=null&&res!=null&&onClick(res)}}else if(codeType!=null&&removeGiftCardOrCouponCode!=null){const response=await removeGiftCardOrCouponCode({codeType});onClick!=null&&response!=null&&onClick(response)}};if(managePaymentProviderGiftCards&&type==="gift_card"){if(!manageGiftCard({order}))return null;hide=!1;const parentProps2={...p,label,handleClick,codeType};return children?_jsx(Parent,{...parentProps2,children}):hide?null:_jsx("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}const parentProps={...p,label,handleClick,codeType};return children?_jsx(Parent,{...parentProps,children}):hide?null:_jsx("button",{type:"button",onClick:()=>{handleClick()},...p,children:label})}export default GiftCardOrCouponRemoveButton;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseAmountComponent } from "../../typings/index";
|
|
2
1
|
import { type JSX } from "react";
|
|
2
|
+
import type { BaseAmountComponent } from "../../typings/index";
|
|
3
3
|
export declare function GiftCardAmount(props: BaseAmountComponent): JSX.Element | null;
|
|
4
4
|
export default GiftCardAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";import BaseOrderPrice from"../utils/BaseOrderPrice";export function GiftCardAmount(props){const{managePaymentProviderGiftCards,order}=useContext(OrderContext);if(managePaymentProviderGiftCards){const giftCardData=manageGiftCard({order});if(!giftCardData)return null;const parentProps={priceCents:giftCardData.currentBalanceValue,price:`-${giftCardData?.formattedBalanceValue}`,...props};return props.children?_jsx(Parent,{...parentProps,children:props.children}):_jsx("span",{...props,children:`-${giftCardData?.formattedBalanceValue}`})}return _jsx(BaseOrderPrice,{base:"amount",type:"gift_card",...props})}export default GiftCardAmount;
|
|
@@ -20,10 +20,6 @@ interface Props {
|
|
|
20
20
|
* Callback called when the order is updated
|
|
21
21
|
*/
|
|
22
22
|
fetchOrder?: (order: Order) => void;
|
|
23
|
-
/**
|
|
24
|
-
* Indicate if Adyen gift card management is enabled
|
|
25
|
-
*/
|
|
26
|
-
manageAdyenGiftCard?: boolean;
|
|
27
23
|
}
|
|
28
24
|
/**
|
|
29
25
|
* This component is responsible for fetching the order and store it in its context.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useReducer,useState}from"react";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import orderReducer,{addToCart,createOrder,getApiOrder,getOrderByFields,orderInitialState,paymentSourceRequest,setOrder,setOrderErrors,updateOrder}from"../../reducers/OrderReducer";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useMemo,useReducer,useState}from"react";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import orderReducer,{addToCart,createOrder,getApiOrder,getOrderByFields,orderInitialState,paymentSourceRequest,setOrder,setOrderErrors,updateOrder}from"../../reducers/OrderReducer";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,managePaymentProviderGiftCards:state.order?.payment_source?.payment_request_data?.payment_method?.type==="giftcard",paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state}),getOrderByFields}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";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),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=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!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),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 isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status;if(
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef,useState}from"react";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import useCommerceLayer from"../../hooks/useCommerceLayer";import getCardDetails from"../../utils/getCardDetails";import{checkPaymentIntent}from"../../utils/stripe/retrievePaymentIntent";import Parent from"../utils/Parent";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),{sdkClient}=useCommerceLayer(),{currentPaymentMethodRef,loading,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,setOrderErrors,errors}=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!=null,currentPaymentMethodRef?.current?.onsubmit!=null,loading,currentPaymentMethodType,order?.id,paymentSource?.id]),useEffect(()=>{errors&&errors.length>0&&(setNotPermitted(!0),setIsLoading(!1),setForceDisable(!1))},[errors]),useEffect(()=>{paymentType==="paypal_payments"&&options?.paypalPayerId&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder&&handleClick()},[options?.paypalPayerId,paymentType!=null]),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 isAuthorized=order?.payment_source?.payment_response?.resultCode==="Authorised",paymentDetails=order?.payment_source?.payment_request_details?.details!=null,paymentStatus=order?.payment_status;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 resultCode=res?.payment_response?.resultCode,errorCode=res?.payment_response?.errorCode,message=res?.payment_response?.message;["Authorised","Pending","Received"].includes(resultCode)&&autoPlaceOrder?handleClick():errorCode!=null&&setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}])})}else paymentType==="adyen_payments"&&isAuthorized&&paymentDetails&&autoPlaceOrder&&status==="standby"&&!options?.adyen?.redirectResult?order?.payment_source?.payment_response?.merchantReference?.includes(order?.number)&&handleClick():paymentType==="adyen_payments"&&isAuthorized&&paymentStatus==="authorized"&&autoPlaceOrder&&status==="standby"&&handleClick()}},[options?.adyen?.redirectResult!=null,order?.payment_source?.payment_response?.resultCode]),useEffect(()=>{order?.status==="placed"&&order?.payment_status==="authorized"&&paymentType==="adyen_payments"&&onClick?.({placed:!0,order})},[order?.id,order?.payment_status,order?.status,paymentType!=null]),useEffect(()=>{if(paymentType==="checkout_com_payments"&&options?.checkoutCom?.session_id&&order?.status&&["draft","pending"].includes(order?.status)&&autoPlaceOrder){const paymentStatus=order?.payment_source?.payment_response?.status;if(paymentStatus&&paymentStatus.toLowerCase()==="pending"){async function placingOrder(){const paymentStatus2=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"checkout_com_payments",attributes:{_details:1}}))?.payment_response?.status,isValidStatus=["authorized","captured"].includes(paymentStatus2?.toLowerCase());paymentStatus2&&isValidStatus?handleClick():(options?.checkoutCom&&(options.checkoutCom.session_id=void 0),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:paymentStatus2}]))}placingOrder()}}else if(paymentType==="checkout_com_payments"&&order?.status&&status&&["pending"].includes(order?.status)&&["placing"].includes(status)&&autoPlaceOrder){const paymentSourceStatus=order?.payment_source?.payment_response?.status;paymentSourceStatus&&["captured","authorized"].includes(paymentSourceStatus.toLowerCase())&&setPlaceOrder?.({paymentSource}).then(placed=>{placed?.placed?(onClick?.(placed),setPlaceOrderStatus?.({status:"placing"})):setPlaceOrderStatus?.({status:"standby"})})}},[options?.checkoutCom?.session_id,order?.payment_source?.id,status]),useEffect(()=>{ref?.current!=null&&setButtonRef!=null&&setButtonRef(ref)},[ref?.current]),useEffect(()=>{switch(status){case"disabled":case"placing":setNotPermitted(!0);break;default:setNotPermitted(!1);break}},[status!=null]);const handleClick=async e=>{e?.preventDefault(),e?.stopPropagation();const sdk=sdkClient();if(sdk==null||order==null)return;let isValid=!0,currentPaymentStatus="unpaid";if(!(paymentType==="stripe_payments")){const{status:status2,payment_status:paymentStatus}=await sdk.orders.retrieve(order?.id,{fields:["status","payment_status"]}),isAlreadyPlaced=status2==="placed",isDraftOrder=status2==="draft";if(currentPaymentStatus=paymentStatus??"unpaid",isAlreadyPlaced){setPlaceOrderStatus?.({status:"placing"}),onClick?.({placed:!0,order});return}if(isDraftOrder){setPlaceOrderStatus?.({status:"standby"}),onClick?.({placed:!1,order,errors:[{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]}),setOrderErrors([{code:"VALIDATION_ERROR",resource:"orders",message:"Draft order cannot be placed"}]);return}}setIsLoading(!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)):currentPaymentMethodRef?.current?.onsubmit&&options?.checkoutCom?.session_id&&checkPaymentSource?.payment_response?.status&&checkPaymentSource?.payment_response?.status?.toLowerCase()==="declined"?isValid=await currentPaymentMethodRef.current?.onsubmit({paymentSource:checkPaymentSource,setPlaceOrder,onclickCallback:onClick}):card?.brand&&(isValid=!0),currentPaymentStatus==="partially_authorized"&&(isValid=!1),isValid&&setPlaceOrderStatus!=null&&(setPlaceOrderStatus({status:"placing"}),setForceDisable(!0));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"})))},disabledButton=disabled!==void 0?disabled:notPermitted,labelButton=isLoading?loadingLabel:isFunction(label)?label():label,parentProps={...p,label,disabled:disabledButton,handleClick,parentRef:ref,isLoading};return children?_jsx(Parent,{...parentProps,children}):_jsx("button",{ref,type:"button",disabled:disabledButton||forceDisable,onClick:e=>{handleClick(e)},...p,children:labelButton})}export default PlaceOrderButton;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseAmountComponent } from "../../typings/index";
|
|
2
1
|
import { type JSX } from "react";
|
|
2
|
+
import type { BaseAmountComponent } from "../../typings/index";
|
|
3
3
|
export declare function TotalAmount(props: BaseAmountComponent): JSX.Element | null;
|
|
4
4
|
export default TotalAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx}from"react/jsx-runtime";import
|
|
2
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";import BaseOrderPrice from"../utils/BaseOrderPrice";export function TotalAmount(props){const{managePaymentProviderGiftCards,order}=useContext(OrderContext);if(managePaymentProviderGiftCards){const giftCardData=manageGiftCard({order});if(!giftCardData)return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props});const parentProps={price:`${giftCardData?.formattedOrderTotal}`,...props};return props.children?_jsx(Parent,{...parentProps,children:props.children}):_jsx("span",{...props,children:`${giftCardData?.formattedOrderTotal}`})}return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props})}export default TotalAmount;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import{getPublicIP}from"../../utils/getPublicIp";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{setCustomerOrderParam}from"../../utils/localStorage";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{placeOrderButtonRef,setPlaceOrder,status}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(console.log("onSubmit controlCode:",{paymentStatus,controlCode,paymentMethodType,currentPaymentMethodType:currentPaymentMethodType2,control,order}),controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return console.log("return resultCode",{controlCode,paymentMethodType,paymentStatus}),{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{const psUp=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes});if(console.log("Payment source updated:",psUp),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(console.log("Submitting payment with method:",currentPaymentMethodType2),currentPaymentMethodType2==="giftcard"){const giftCardBalanceCheck=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}),currentBalance=giftCardBalanceCheck?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0,attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0};console.log("Gift card balance check:",{giftCardBalanceCheck,attributes:attributes2});const{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2});console.log("First gift card authorization:",orderUpdated);const resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return console.log("Gift card authorized:",{resultCode:resultCode2,action:action2,orderUpdated,paymentStatus:paymentStatus2}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&hasSubscriptions(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);console.log("onSubmit resultCode:",{resultCode,action,message,paymentStatus}),["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
|
|
2
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import{useContext,useEffect,useRef,useState}from"react";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import CustomerContext from"../../context/CustomerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PlaceOrderContext from"../../context/PlaceOrderContext";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import{getPublicIP}from"../../utils/getPublicIp";import{hasSubscriptions}from"../../utils/hasSubscriptions";import{setCustomerOrderParam}from"../../utils/localStorage";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod,giftcardErrorComponent,onReady,onSelect,subscriptionPaymentMethods}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),[giftcardError,setGiftcardError]=useState(null),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder,getOrderByFields}=useContext(OrderContext),authConfig=useContext(CommerceLayerContext),{placeOrderButtonRef,setPlaceOrder,status}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type,paymentStatus=(await getOrderByFields({orderId:order?.id??"",fields:["status","payment_status"],config:authConfig}))?.payment_status;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard"&&paymentStatus!=="partially_authorized")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(currentPaymentMethodType2==="giftcard"){const currentBalance=(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_balance:!0}}))?.balance??0,totalAmount=order?.total_amount_with_taxes_cents??0,attributes2=currentBalance>=totalAmount?{_authorize:!0}:{_authorization_amount_cents:currentBalance,_authorize:!0},{order:orderUpdated}=await updateOrder({id:order.id,attributes:attributes2}),resultCode2=orderUpdated?.payment_source?.payment_response?.resultCode,refusalReasonCode=orderUpdated?.payment_source?.payment_response?.refusalReasonCode,errorCode=orderUpdated?.payment_source?.payment_response?.errorCode,action2=orderUpdated?.payment_source?.payment_response?.action,paymentStatus2=orderUpdated?.payment_status;if(["Cancelled","Refused"].includes(resultCode2)&&refusalReasonCode!=="12"||errorCode){const message=orderUpdated?.payment_response?.refusalReason??orderUpdated?.payment_response?.message;return{resultCode:errorCode?"Refused":resultCode2,message}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2,action:action2,paymentStatus:paymentStatus2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");let showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null;order&&hasSubscriptions(order)&&(showStoredPaymentMethods=!1,paymentMethodsResponse.storedPaymentMethods=[],paymentMethodsResponse.paymentMethods=subscriptionPaymentMethods!=null&&subscriptionPaymentMethods.length>0?paymentMethodsResponse.paymentMethods.filter(pm=>subscriptionPaymentMethods.includes(pm.type)):paymentMethodsResponse.paymentMethods);const options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action,message,paymentStatus}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?(actions.reject(),message&&setGiftcardError(message)):action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),paymentStatus==="partially_authorized"&&dropinRef.current?.mount("#adyen-dropin"),setGiftcardError(null))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref})),onSelect&&onSelect(component)},onReady(){onReady&&onReady()}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))},html=document.getElementById("adyen-dropin");!dropinRef.current&&status==="standby"&&html&&initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null,status]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),giftcardError!=null&&giftcardErrorComponent?giftcardErrorComponent(giftcardError):null,templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?(address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(!shipToDifferentAddress&&billingAddressCloneId&&(
|
|
2
|
+
import camelCase from"lodash/camelCase";import{invertedAddressesHandler,sanitizeMetadataFields}from"../utils/addressesManager";import baseReducer from"../utils/baseReducer";import{formCleaner}from"../utils/formCleaner";import getSdk from"../utils/getSdk";export const addressFields=["city","company","country_code","first_name","last_name","line_1","line_2","phone","state_code","zip_code"],addressInitialState={errors:[]},setAddressErrors=({errors,dispatch,currentErrors=[],resource})=>{const billingErrors=resource==="billing_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="billing_address"),shippingErrors=resource==="shipping_address"?errors.filter(e=>e.resource===resource):currentErrors.filter(e=>e.resource==="shipping_address"),finalErrors=[...billingErrors,...shippingErrors];dispatch&&dispatch({type:"setErrors",payload:{errors:finalErrors}})};export function setAddress({values,resource,dispatch}){const payload={[`${resource}`]:{...formCleaner(values)}};dispatch&&dispatch({type:"setAddress",payload})}export const setCloneAddress=(id,resource,dispatch)=>{dispatch({type:"setCloneAddress",payload:{[`${camelCase(resource)}Id`]:id}})};export async function saveAddresses({config,updateOrder,order,state,customerEmail,customerAddress}){const{shipToDifferentAddress,invertAddresses,billing_address:billingAddressForm,shipping_address:shippingAddressForm,billingAddressId,shippingAddressId}=state;try{const sdk=getSdk(config),billingAddress=formCleaner(billingAddressForm),shippingAddress=formCleaner(shippingAddressForm);if(order){let orderAttributes=null;const billingAddressCloneId=customerAddress?.resource==="billing_address"?customerAddress?.id:billingAddressId,shippingAddressCloneId=customerAddress?.resource==="shipping_address"?customerAddress?.id:shippingAddressId;if(invertAddresses)orderAttributes=await invertedAddressesHandler({billingAddress,billingAddressId:billingAddressCloneId,customerEmail,order,shipToDifferentAddress,shippingAddress,shippingAddressId:shippingAddressCloneId,sdk});else{const doNotShipItems=order?.line_items?.every(lineItem=>lineItem?.item?.do_not_ship===!0),currentBillingAddressRef=order?.billing_address?.reference;if(orderAttributes={id:order?.id,_billing_address_clone_id:billingAddressCloneId,_shipping_address_clone_id:billingAddressCloneId,customer_email:customerEmail},currentBillingAddressRef===billingAddressCloneId&&(orderAttributes._billing_address_clone_id=order?.billing_address?.id,orderAttributes._shipping_address_clone_id=order?.shipping_address?.id),billingAddress!=null&&Object.keys(billingAddress).length>0&&!billingAddressCloneId){delete orderAttributes._billing_address_clone_id,delete orderAttributes._shipping_address_clone_id,doNotShipItems||(orderAttributes._shipping_address_same_as_billing=!0);const billingAddressWithMeta=sanitizeMetadataFields(billingAddress);let address;order?.billing_address?.id&&order?.billing_address?.reference==null?(address=await sdk.addresses.update({id:order.billing_address.id,...billingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(billingAddressWithMeta),orderAttributes.billing_address=sdk.addresses.relationship(address.id))}if(!shipToDifferentAddress&&billingAddressCloneId&&(orderAttributes._shipping_address_same_as_billing=!0,orderAttributes._shipping_address_clone_id=billingAddressCloneId),shipToDifferentAddress&&(delete orderAttributes._shipping_address_same_as_billing,shippingAddressCloneId&&(orderAttributes._shipping_address_clone_id=shippingAddressCloneId),shippingAddress!=null&&Object.keys(shippingAddress).length>0)){delete orderAttributes._shipping_address_clone_id;const shippingAddressWithMeta=sanitizeMetadataFields(shippingAddress);let address;order?.shipping_address?.id&&order?.shipping_address?.reference==null?(address=await sdk.addresses.update({id:order.shipping_address.id,...shippingAddressWithMeta}),orderAttributes._refresh=!0):(address=await sdk.addresses.create(shippingAddressWithMeta),orderAttributes.shipping_address=sdk.addresses.relationship(address.id))}}if(orderAttributes!=null&&updateOrder)return{success:!0,order:(await updateOrder({id:order.id,attributes:orderAttributes}))?.order}}return{success:!1}}catch(error){return console.error(error),{success:!1,error}}}const type=["setErrors","setAddress","setShipToDifferentAddress","setCloneAddress","cleanup"],addressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default addressReducer;
|
|
@@ -37,7 +37,7 @@ export interface OrderPayload {
|
|
|
37
37
|
include?: ResourceIncluded[] | undefined;
|
|
38
38
|
includeLoaded?: ResourceIncludedLoaded;
|
|
39
39
|
withoutIncludes?: boolean;
|
|
40
|
-
|
|
40
|
+
managePaymentProviderGiftCards?: boolean;
|
|
41
41
|
}
|
|
42
42
|
export type AddToCartImportValues = Pick<AddToCartImportParams, "lineItems">;
|
|
43
43
|
export type getOrderContext = (id: string) => Promise<undefined | Order>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
export function manageGiftCard({order}){if(!order||!order?.payment_source)return null;const getPaymentSource=order.payment_source?.type==="adyen_payments"?order.payment_source:null;if(!getPaymentSource||getPaymentSource?.payment_response?.errorCode
|
|
2
|
+
export function manageGiftCard({order}){if(!order||!order?.payment_source)return null;const getPaymentSource=order.payment_source?.type==="adyen_payments"?order.payment_source:null;if(!getPaymentSource||getPaymentSource?.payment_response?.errorCode||!(getPaymentSource?.payment_request_data?.payment_method?.type==="giftcard"))return null;const additionalData=getPaymentSource?.payment_response?.additionalData,amount=getPaymentSource?.payment_response?.amount?.value,giftCardData={cardSummary:additionalData?.cardSummary,currentBalanceValue:amount??Number.parseInt(additionalData?.currentBalanceValue),currentBalanceCurrency:additionalData?.currentBalanceCurrency,cardBrand:additionalData?.originalSelectedBrand??additionalData?.paymentMethod,formattedBalanceValue:additionalData?.currentBalanceValue},formattedOrderTotal=((order?.total_amount_with_taxes_cents!=null?order?.total_amount_with_taxes_cents-giftCardData.currentBalanceValue:0)/100).toLocaleString(order.language_code??"en",{style:"currency",currency:order?.currency_code??"USD"}),formattedCurrentBalance=(giftCardData.currentBalanceValue/100).toLocaleString(order.language_code??"en",{style:"currency",currency:order?.currency_code??"USD"});return giftCardData.formattedBalanceValue=formattedCurrentBalance,{...giftCardData,formattedOrderTotal}}
|