@commercelayer/react-components 4.20.0 → 4.20.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
  2. package/lib/cjs/components/gift_cards/GiftCardOrCouponCode.js +1 -1
  3. package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
  4. package/lib/cjs/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
  5. package/lib/cjs/components/orders/CheckoutLink.d.ts +4 -4
  6. package/lib/cjs/components/orders/GiftCardAmount.d.ts +3 -3
  7. package/lib/cjs/components/orders/GiftCardAmount.js +1 -1
  8. package/lib/cjs/components/orders/OrderContainer.d.ts +8 -4
  9. package/lib/cjs/components/orders/OrderContainer.js +1 -1
  10. package/lib/cjs/components/orders/TotalAmount.d.ts +3 -3
  11. package/lib/cjs/components/orders/TotalAmount.js +1 -1
  12. package/lib/cjs/components/payment_source/AdyenPayment.js +1 -1
  13. package/lib/cjs/components/payment_source/KlarnaPayment.d.ts +4 -4
  14. package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
  15. package/lib/cjs/components/payment_source/StripeExpressPayment.d.ts +2 -2
  16. package/lib/cjs/components/payment_source/StripeExpressPayment.js +1 -1
  17. package/lib/cjs/context/OrderContext.d.ts +5 -3
  18. package/lib/cjs/context/OrderContext.js +1 -1
  19. package/lib/cjs/reducers/OrderReducer.d.ts +34 -20
  20. package/lib/cjs/reducers/OrderReducer.js +1 -1
  21. package/lib/cjs/utils/adyen/manageGiftCard.d.ts +16 -0
  22. package/lib/cjs/utils/adyen/manageGiftCard.js +2 -0
  23. package/lib/cjs/utils/expressPaymentHelper.d.ts +1 -1
  24. package/lib/cjs/utils/expressPaymentHelper.js +1 -1
  25. package/lib/esm/components/gift_cards/GiftCardOrCouponCode.d.ts +5 -5
  26. package/lib/esm/components/gift_cards/GiftCardOrCouponCode.js +1 -1
  27. package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.d.ts +6 -6
  28. package/lib/esm/components/gift_cards/GiftCardOrCouponRemoveButton.js +1 -1
  29. package/lib/esm/components/orders/CheckoutLink.d.ts +4 -4
  30. package/lib/esm/components/orders/GiftCardAmount.d.ts +3 -3
  31. package/lib/esm/components/orders/GiftCardAmount.js +1 -1
  32. package/lib/esm/components/orders/OrderContainer.d.ts +8 -4
  33. package/lib/esm/components/orders/OrderContainer.js +1 -1
  34. package/lib/esm/components/orders/TotalAmount.d.ts +3 -3
  35. package/lib/esm/components/orders/TotalAmount.js +1 -1
  36. package/lib/esm/components/payment_source/AdyenPayment.js +1 -1
  37. package/lib/esm/components/payment_source/KlarnaPayment.d.ts +4 -4
  38. package/lib/esm/components/payment_source/KlarnaPayment.js +1 -1
  39. package/lib/esm/components/payment_source/StripeExpressPayment.d.ts +2 -2
  40. package/lib/esm/components/payment_source/StripeExpressPayment.js +1 -1
  41. package/lib/esm/context/OrderContext.d.ts +5 -3
  42. package/lib/esm/context/OrderContext.js +1 -1
  43. package/lib/esm/reducers/OrderReducer.d.ts +34 -20
  44. package/lib/esm/reducers/OrderReducer.js +1 -1
  45. package/lib/esm/utils/adyen/manageGiftCard.d.ts +16 -0
  46. package/lib/esm/utils/adyen/manageGiftCard.js +2 -0
  47. package/lib/esm/utils/expressPaymentHelper.d.ts +1 -1
  48. package/lib/esm/utils/expressPaymentHelper.js +1 -1
  49. package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
  50. package/lib/tsconfig.prod.tsbuildinfo +1 -1
  51. package/package.json +15 -15
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{var _a2;if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push((_a2=firstMethod.price_amount_for_shipment_cents)!==null&&_a2!==void 0?_a2:0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}function setExpressShippingMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _b,_c,_d;const sdk=(0,getSdk_1.default)(config),order=yield sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}else selectedShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)}));else for(const shipment of(_b=order?.shipments)!==null&&_b!==void 0?_b:[]){const[firstShippingMethodId]=(_d=(_c=shipment?.available_shipping_methods)===null||_c===void 0?void 0:_c.map(method=>method.id))!==null&&_d!==void 0?_d:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}function setExpressPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=(0,getSdk_1.default)(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return yield sdk.orders.retrieve(orderId,{include}),yield sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),yield sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),yield sdk[paymentResource].update({id:paymentSourceId,_update:!0}),yield sdk.orders.retrieve(orderId,{include})}return yield sdk.orders.update({id:orderId,_place:!0})})}function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;!window.location.pathname.includes("/cart")?window.location.reload():window.top!=null&&(window.top.location.href=href)}
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=getAvailableExpressPayments,exports.setExpressFakeAddress=setExpressFakeAddress,exports.getExpressShippingMethods=getExpressShippingMethods,exports.setExpressShippingMethod=setExpressShippingMethod,exports.setExpressPlaceOrder=setExpressPlaceOrder,exports.expressRedirectUrl=expressRedirectUrl;const tslib_1=require("tslib"),getSdk_1=tslib_1.__importDefault(require("./getSdk")),getDomain_1=require("./getDomain"),organization_1=require("./organization"),getApplicationLink_1=require("./getApplicationLink"),availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}function setExpressFakeAddress(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=(0,getSdk_1.default)(config),fakeAddress=yield sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),yield sdk.orders.update(resource,params),yield sdk.orders.retrieve(orderId,params)})}function getExpressShippingMethods(order){var _a,_b;const isSingleShipment=((_a=order?.shipments)===null||_a===void 0?void 0:_a.length)===1,shippingMethods=(_b=order?.shipments)===null||_b===void 0?void 0:_b.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>{var _a2,_b2,_c;return{id:(_a2=method?.id)!==null&&_a2!==void 0?_a2:"",label:(_b2=method?.name)!==null&&_b2!==void 0?_b2:"",amount:(_c=method?.price_amount_for_shipment_cents)!==null&&_c!==void 0?_c:0,detail:""}});if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{var _a2;if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push((_a2=firstMethod.price_amount_for_shipment_cents)!==null&&_a2!==void 0?_a2:0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}function setExpressShippingMethod(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _b,_c,_d;const sdk=(0,getSdk_1.default)(config),order=yield sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}else selectedShippingMethodId!=null&&(yield sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)}));else for(const shipment of(_b=order?.shipments)!==null&&_b!==void 0?_b:[]){const[firstShippingMethodId]=(_d=(_c=shipment?.available_shipping_methods)===null||_c===void 0?void 0:_c.map(method=>method.id))!==null&&_d!==void 0?_d:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}function setExpressPlaceOrder(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=(0,getSdk_1.default)(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return yield sdk.orders.retrieve(orderId,{include}),yield sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),yield sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),yield sdk[paymentResource].update({id:paymentSourceId,_update:!0}),yield sdk.orders.retrieve(orderId,{include})}return yield sdk.orders.update({id:orderId,_place:!0})})}function expressRedirectUrl(_a){return tslib_1.__awaiter(this,arguments,void 0,function*({order,config:{accessToken,endpoint}}){var _b,_c;if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug,domain}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const config=yield(0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{accessToken,slug,orderId:order?.id}}),href=((_b=config?.links)===null||_b===void 0?void 0:_b.checkout)!=null?(_c=config?.links)===null||_c===void 0?void 0:_c.checkout:(0,getApplicationLink_1.getApplicationLink)({slug,orderId:order?.id,accessToken,applicationType:"checkout",domain});!window.location.pathname.includes("/cart")?window.location.reload():window.open(href,"_top")})}
@@ -1,14 +1,14 @@
1
- import { type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- import type { CodeType } from '../../reducers/OrderReducer';
4
- interface ChildrenProps extends Omit<Props, 'children' | 'type'> {
1
+ import { type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ import type { CodeType } from "../../reducers/OrderReducer";
4
+ interface ChildrenProps extends Omit<Props, "children" | "type"> {
5
5
  code?: string | null;
6
6
  hide?: boolean;
7
7
  discountAmountCents?: number | null;
8
8
  discountAmountFloat?: number | null;
9
9
  formattedDiscountAmount?: string | null;
10
10
  }
11
- interface Props extends Omit<JSX.IntrinsicElements['span'], 'children'> {
11
+ interface Props extends Omit<JSX.IntrinsicElements["span"], "children"> {
12
12
  type?: CodeType;
13
13
  children?: ChildrenFunction<ChildrenProps>;
14
14
  }
@@ -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";export function GiftCardOrCouponCode({children,type,...props}){const{order}=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]:"",hide=!(order&&code),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;
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,manageAdyenGiftCard}=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(manageAdyenGiftCard&&type==="gift_card"){const giftCardData=manageGiftCard({order});if(console.log("order",order),console.log("giftCardData",giftCardData),!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,8 +1,8 @@
1
- import { type ReactNode, type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- import type { CodeType, OrderCodeType } from '../../reducers/OrderReducer';
4
- import type { Order } from '@commercelayer/sdk';
5
- interface ChildrenProps extends Omit<Props, 'children' | 'onClick'> {
1
+ import { type ReactNode, type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ import type { CodeType, OrderCodeType } from "../../reducers/OrderReducer";
4
+ import type { Order } from "@commercelayer/sdk";
5
+ interface ChildrenProps extends Omit<Props, "children" | "onClick"> {
6
6
  codeType?: OrderCodeType;
7
7
  hide?: boolean;
8
8
  handleClick?: () => void;
@@ -15,6 +15,6 @@ type Props = {
15
15
  success: boolean;
16
16
  order?: Order;
17
17
  }) => void;
18
- } & Omit<JSX.IntrinsicElements['button'], 'type' | 'onClick'>;
18
+ } & Omit<JSX.IntrinsicElements["button"], "type" | "onClick">;
19
19
  export declare function GiftCardOrCouponRemoveButton(props: Props): JSX.Element | null;
20
20
  export default GiftCardOrCouponRemoveButton;
@@ -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";export function GiftCardOrCouponRemoveButton(props){const{children,label="Remove",onClick,type,...p}=props,{order,removeGiftCardOrCouponCode}=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]:"",hide=!(order&&code),handleClick=async()=>{if(codeType!=null&&removeGiftCardOrCouponCode!=null){const response=await removeGiftCardOrCouponCode({codeType});onClick!=null&&response!=null&&onClick(response)}},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;
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,manageAdyenGiftCard,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(manageAdyenGiftCard&&codeType==="gift_card_code"&&order!=null){console.log("handle click gift card");const id=order?.payment_source?.id;if(console.log("id",id),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(manageAdyenGiftCard&&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,10 +1,10 @@
1
- import { type JSX } from 'react';
2
- import type { ChildrenFunction } from '../../typings/index';
3
- interface ChildrenProps extends Omit<Props, 'children'> {
1
+ import { type JSX } from "react";
2
+ import type { ChildrenFunction } from "../../typings/index";
3
+ interface ChildrenProps extends Omit<Props, "children"> {
4
4
  checkoutUrl: string;
5
5
  href: string;
6
6
  }
7
- interface Props extends Omit<JSX.IntrinsicElements['a'], 'children'> {
7
+ interface Props extends Omit<JSX.IntrinsicElements["a"], "children"> {
8
8
  children?: ChildrenFunction<ChildrenProps>;
9
9
  /**
10
10
  * Label for the checkout link
@@ -1,4 +1,4 @@
1
- import type { BaseAmountComponent } from '../../typings/index';
2
- import type { JSX } from "react";
3
- export declare function GiftCardAmount(props: BaseAmountComponent): JSX.Element;
1
+ import type { BaseAmountComponent } from "../../typings/index";
2
+ import { type JSX } from "react";
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 BaseOrderPrice from"../utils/BaseOrderPrice";export function GiftCardAmount(props){return _jsx(BaseOrderPrice,{base:"amount",type:"gift_card",...props})}export default GiftCardAmount;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";import Parent from"../utils/Parent";export function GiftCardAmount(props){const{manageAdyenGiftCard,order}=useContext(OrderContext);if(manageAdyenGiftCard){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;
@@ -1,7 +1,7 @@
1
- import { type JSX } from 'react';
2
- import type { BaseMetadataObject } from '../../typings/index';
3
- import type { OrderCreate, Order } from '@commercelayer/sdk';
4
- import type { DefaultChildrenType } from '../../typings/globals';
1
+ import { type JSX } from "react";
2
+ import type { BaseMetadataObject } from "../../typings/index";
3
+ import type { OrderCreate, Order } from "@commercelayer/sdk";
4
+ import type { DefaultChildrenType } from "../../typings/globals";
5
5
  interface Props {
6
6
  children: DefaultChildrenType;
7
7
  /**
@@ -20,6 +20,10 @@ interface Props {
20
20
  * Callback called when the order is updated
21
21
  */
22
22
  fetchOrder?: (order: Order) => void;
23
+ /**
24
+ * Indicate if Adyen gift card management is enabled
25
+ */
26
+ manageAdyenGiftCard?: boolean;
23
27
  }
24
28
  /**
25
29
  * This component is responsible for fetching the order and store it in its context.
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useEffect,useReducer,useContext,useMemo,useState}from"react";import orderReducer,{createOrder,getApiOrder,setOrderErrors,setOrder,orderInitialState,updateOrder,addToCart,paymentSourceRequest}from"../../reducers/OrderReducer";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext,{defaultOrderContext}from"../../context/OrderContext";import OrderStorageContext from"../../context/OrderStorageContext";import compareObjAttribute from"../../utils/compareObjAttribute";import useCustomContext from"../../utils/hooks/useCustomContext";export function OrderContainer(props){const{orderId,children,metadata,attributes,fetchOrder,manageAdyenGiftCard}=props,[state,dispatch]=useReducer(orderReducer,orderInitialState),[lock,setLock]=useState(!1),[lockOrder,setLockOrder]=useState(!0),config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"OrderContainer",key:"accessToken"}),{persistKey,clearWhenPlaced,getLocalOrder,setLocalOrder,deleteLocalOrder}=useContext(OrderStorageContext),getOrder=async localOrder=>{localOrder&&await getApiOrder({id:localOrder,dispatch,config,persistKey,clearWhenPlaced:!!(persistKey&&clearWhenPlaced),deleteLocalOrder,state})};useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId;state?.orderId&&(localOrder!=null&&state.orderId!==localOrder?getOrder(localOrder):dispatch({type:"setOrderId",payload:{orderId:void 0,order:void 0}}))},[persistKey]),useEffect(()=>{state.withoutIncludes||dispatch({type:"setLoading",payload:{loading:!0}})},[state.withoutIncludes]),useEffect(()=>{if(attributes&&state?.order&&!lock){const updateAttributes=compareObjAttribute({attributes,object:state.order});Object.keys(updateAttributes).length>0&&(updateOrder({id:state.order.id,attributes:updateAttributes,dispatch,config,include:state.include,state}),setLock(!0))}return()=>{if(attributes&&state?.order){const updateAttributes=compareObjAttribute({attributes,object:state.order});state.order&&Object.keys(updateAttributes).length===0&&setLock(!1)}}},[attributes,state?.order,lock]),useEffect(()=>{const localOrder=persistKey?getLocalOrder(persistKey):orderId,startRequest=Object.keys(state?.includeLoaded||{}).filter(key=>state?.includeLoaded?.[key]===!0);return config.accessToken&&state.loading===!1&&state?.order==null?(localOrder&&!state.order&&state.include?.length===startRequest.length&&!state.withoutIncludes&&!lockOrder||state.withoutIncludes&&!state.include?.length&&startRequest.length===0)&&getOrder(localOrder):[config.accessToken,state.order==null,state.loading,state.withoutIncludes].every(Boolean)?dispatch({type:"setLoading",payload:{loading:!1}}):[config.accessToken,state.order==null,state.loading,state.withoutIncludes===!1].every(Boolean)&&dispatch({type:"setLoading",payload:{loading:!1}}),()=>{state.order==null&&state.loading&&state.withoutIncludes===!1&&(state.include?.length===0&&startRequest.length>0?dispatch({type:"setLoading",payload:{loading:!1}}):state.include&&state.include?.length>0&&(dispatch({type:"setIncludesResource",payload:{include:[]}}),setLockOrder(!1)))}},[config.accessToken,Object.keys(state.includeLoaded??{}).length,state.include?.length,orderId,Object.keys(state?.order??{}).length,state.loading,state.withoutIncludes,lockOrder]);const orderValue=useMemo(()=>(fetchOrder!=null&&state?.order!=null&&fetchOrder(state.order),{...state,manageAdyenGiftCard,paymentSourceRequest:async params=>await paymentSourceRequest({...params,dispatch,state,config}),setOrder:order=>{setOrder(order,dispatch)},getOrder:async id=>await getApiOrder({id,dispatch,config,state}),setOrderErrors:errors=>setOrderErrors({dispatch,errors}),createOrder:async()=>await createOrder({persistKey,dispatch,config,state,orderMetadata:metadata,orderAttributes:attributes,setLocalOrder}),addToCart:async params=>await addToCart({...params,persistKey,dispatch,state,config,errors:state.errors,orderMetadata:metadata||{},orderAttributes:attributes,setLocalOrder}),saveAddressToCustomerAddressBook:args=>{defaultOrderContext.saveAddressToCustomerAddressBook({...args,dispatch})},setGiftCardOrCouponCode:async({code,codeType})=>await defaultOrderContext.setGiftCardOrCouponCode({code,codeType,dispatch,order:state.order,config,include:state.include,state}),removeGiftCardOrCouponCode:async({codeType})=>await defaultOrderContext.removeGiftCardOrCouponCode({codeType,dispatch,order:state.order,config,include:state.include,state}),addResourceToInclude:args=>{defaultOrderContext.addResourceToInclude({...args,dispatch,resourcesIncluded:state.include,resourceIncludedLoaded:state.includeLoaded})},updateOrder:async args=>await defaultOrderContext.updateOrder({...args,dispatch,config,include:state.include,state})}),[state,config.accessToken,persistKey]);return _jsx(OrderContext.Provider,{value:orderValue,children})}export default OrderContainer;
@@ -1,4 +1,4 @@
1
- import type { BaseAmountComponent } from '../../typings/index';
2
- import type { JSX } from "react";
3
- export declare function TotalAmount(props: BaseAmountComponent): JSX.Element;
1
+ import type { BaseAmountComponent } from "../../typings/index";
2
+ import { type JSX } from "react";
3
+ export declare function TotalAmount(props: BaseAmountComponent): JSX.Element | null;
4
4
  export default TotalAmount;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";export function TotalAmount(props){return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props})}export default TotalAmount;
2
+ import{jsx as _jsx}from"react/jsx-runtime";import BaseOrderPrice from"../utils/BaseOrderPrice";import{useContext}from"react";import Parent from"../utils/Parent";import OrderContext from"../../context/OrderContext";import{manageGiftCard}from"../../utils/adyen/manageGiftCard";export function TotalAmount(props){const{manageAdyenGiftCard,order}=useContext(OrderContext);if(manageAdyenGiftCard){const giftCardData=manageGiftCard({order});if(!giftCardData)return null;const parentProps={price:`${giftCardData?.formattedOrderTotal}`,...props};return props.children?_jsx(Parent,{...parentProps,children:props.children}):_jsx("span",{...props,children:`${giftCardData?.formattedOrderTotal}`})}return _jsx(BaseOrderPrice,{base:"total_amount",type:"with_taxes",...props})}export default TotalAmount;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import Parent from"../utils/Parent";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import{getPublicIP}from"../../utils/getPublicIp";import CustomerContext from"../../context/CustomerContext";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"}),controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",recurringProcessingModel:"CardOnFile",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(controlCode==="Authorised"&&paymentMethodType==="giftcard")return await updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2};if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}});if(["Cancelled","Refused"].includes(firstAuthorization?.payment_response?.resultCode)){const availableGiftCardAmount=firstAuthorization?.payment_response?.additionalData?.currentBalanceValue;return await updateOrder({id:order.id,attributes:{_authorization_amount_cents:Number.parseInt(availableGiftCardAmount),_place:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}return{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null,options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),dropinRef.current?.mount("#adyen-dropin"))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref}))}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))};dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
2
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import{setCustomerOrderParam}from"../../utils/localStorage";import{AdyenCheckout,Dropin}from"@adyen/adyen-web/auto";import Parent from"../utils/Parent";import browserInfo,{cleanUrlBy}from"../../utils/browserInfo";import PlaceOrderContext from"../../context/PlaceOrderContext";import OrderContext from"../../context/OrderContext";import{getPublicIP}from"../../utils/getPublicIp";import CustomerContext from"../../context/CustomerContext";const defaultConfig={};export function AdyenPayment({clientKey,config,templateCustomerSaveToWallet,environment="test",locale="en_US"}){const{cardContainerClassName,styles,onDisableStoredPaymentMethod}={...defaultConfig,...config},[loadAdyen,setLoadAdyen]=useState(!1),[checkout,setCheckout]=useState(),{setPaymentSource,paymentSource,setPaymentMethodErrors,currentPaymentMethodType,setPaymentRef,currentCustomerPaymentSourceId}=useContext(PaymentMethodContext),{order,updateOrder}=useContext(OrderContext),{placeOrderButtonRef,setPlaceOrder}=useContext(PlaceOrderContext),{customers}=useContext(CustomerContext),ref=useRef(null),dropinRef=useRef(null),handleSubmit=async e=>{const savePaymentSourceToCustomerWallet=e?.elements?.save_payment_source_to_customer_wallet?.checked;return savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),dropinRef.current&&dropinRef.current.submit(),!1},handleChange=async state=>{state.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(ref.current),setPaymentRef({ref}))},handleOnAdditionalDetails=async(state,component)=>{const attributes={payment_request_details:state.data,_details:1};try{const pSource=paymentSource&&await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:"adyen_payments",attributes}),resultCode=pSource?.payment_response?.resultCode;if(["Authorised","Pending","Received"].includes(resultCode))return placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode};if(["Cancelled","Refused"].includes(resultCode)){const message=pSource?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message}]),component&&component.mount("#adyen-dropin")}return{resultCode}}catch(error){return console.error("Adyen additional details error:",error),{resultCode:"Error"}}},onSubmit=async(state,component)=>{const url=cleanUrlBy(),{type:currentPaymentMethodType2}=state.data.paymentMethod,shopperIp=await getPublicIP(),control=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments"});console.log("Control",control);const controlCode=control?.payment_response?.resultCode,paymentMethodType=control?.payment_response?.paymentMethod?.type??control?.payment_request_data?.payment_method?.type;if(controlCode==="Authorised"&&paymentMethodType!=="giftcard")return{resultCode:controlCode};const attributes={payment_request_data:{...state.data,payment_method:state.data.paymentMethod,return_url:url,origin:window.location.origin,redirect_from_issuer_method:"GET",shopper_ip:shopperIp,shopperInteraction:"Ecommerce",recurringProcessingModel:"CardOnFile",browser_info:{...browserInfo()}}};delete attributes.payment_request_data.paymentMethod;try{if(await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes}),order?.id==null)return console.error("Order id is missing"),{resultCode:"Error"};if(console.log("Control code",controlCode),console.log("Payment method type",paymentMethodType),["Cancelled","Refused"].includes(controlCode)&&paymentMethodType==="giftcard"&&currentPaymentMethodType2!=="giftcard"){const availableGiftCardAmount=Number.parseInt(control?.payment_response?.additionalData?.currentBalanceValue),totalPartialAmount=order?.total_amount_with_taxes_cents!=null&&availableGiftCardAmount!=null?order?.total_amount_with_taxes_cents-availableGiftCardAmount:0;return console.log("totalPartialAmount",totalPartialAmount),await updateOrder({id:order.id,attributes:{_authorization_amount_cents:totalPartialAmount,_place:!0}}),console.log("Authorize first credit card amount"),await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{payment_request_data:control?.payment_request_data}}),await updateOrder({id:order.id,attributes:{_authorize:!0}}),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}if(currentPaymentMethodType2==="giftcard"){const firstAuthorization=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}});return console.log("First gift card authorization",firstAuthorization),{resultCode:"Authorised",paymentMethodType:currentPaymentMethodType2}}const res=await setPaymentSource({paymentSourceId:paymentSource?.id,paymentResource:"adyen_payments",attributes:{_authorize:1}}),action=res?.payment_response?.action,resultCode=res?.payment_response?.resultCode;if(action!=null)return{resultCode,action};const issuerType=res?.payment_instrument?.issuer_type;if(["Authorised","Pending","Received"].includes(resultCode))return["apple pay","google pay"].includes(issuerType)&&setPlaceOrder!=null?(await setPlaceOrder({paymentSource:res,currentCustomerPaymentSourceId}),{resultCode}):(placeOrderButtonRef?.current!=null&&(placeOrderButtonRef.current.disabled&&(placeOrderButtonRef.current.disabled=!1),placeOrderButtonRef.current.click()),{resultCode});if(["Cancelled","Refused"].includes(resultCode)){const message=res?.payment_response?.refusalReason;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}]),component&&component.mount("#adyen-dropin")}if(res?.payment_response?.errorType)if(res?.payment_response?.errorCode==="14_006")onSubmit(state,component);else{const message=res?.payment_response?.message;setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message}])}return{resultCode,paymentMethodType:currentPaymentMethodType2}}catch(error){const{message}=error;return setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType2,message:message??"An error occurred"}]),{resultCode:"Error"}}};return useEffect(()=>{const paymentMethodsResponse={paymentMethods:paymentSource?.payment_methods?.paymentMethods?paymentSource?.payment_methods.paymentMethods:[],storedPaymentMethods:paymentSource?.payment_methods?.storedPaymentMethods?paymentSource?.payment_methods.storedPaymentMethods:[]};paymentMethodsResponse.paymentMethods.length===0&&console.error("Payment methods are not available. Please, check your Adyen configuration.");const showStoredPaymentMethods=paymentSource?.payment_methods?.storedPaymentMethods!=null,options={locale:order?.language_code??locale,environment,clientKey,amount:{currency:order?.currency_code||"",value:order?.total_amount_with_taxes_cents||0},countryCode:order?.country_code||"",paymentMethodsResponse,showPayButton:!1,onAdditionalDetails:(state,element,actions)=>{(async()=>{const{resultCode}=await handleOnAdditionalDetails(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():actions.resolve({resultCode})})()},onChange:state=>{handleChange(state)},onSubmit:(state,element,actions)=>{(async()=>{const{resultCode,action}=await onSubmit(state,element);["Cancelled","Refused"].includes(resultCode)?actions.reject():action!=null?dropinRef.current?.handleAction(action):(actions.resolve({resultCode}),dropinRef.current?.mount("#adyen-dropin"))})()}};if(!ref&&clientKey&&setCustomerOrderParam("_save_payment_source_to_customer_wallet","false"),clientKey&&!loadAdyen&&window&&!checkout){const initializeAdyen=async()=>{const checkout2=await AdyenCheckout(options),dropin=new Dropin(checkout2,{disableFinalAnimation:!0,showRemovePaymentMethodButton:showStoredPaymentMethods,instantPaymentTypes:["applepay","googlepay"],paymentMethodsConfiguration:{showStoredPaymentMethods,paypal:{showPayButton:!0,style:styles?.paypal,...config?.paymentMethodsConfiguration?.paypal},card:{enableStoreDetails:showStoredPaymentMethods,styles:styles?.card,holderNameRequired:!1,...config?.paymentMethodsConfiguration?.card},giftcard:{showPayButton:!0,...config?.paymentMethodsConfiguration?.giftcard},...config?.paymentMethodsConfiguration},onDisableStoredPaymentMethod:state=>{const recurringDetailReference=state,shopperReference=customers?.shopper_reference??void 0;onDisableStoredPaymentMethod?.({recurringDetailReference,shopperReference}).then(response=>{response?setPaymentSource({paymentResource:"adyen_payments",order,attributes:{}}):console.error("onDisableStoredPaymentMethod error")}).catch(error=>{console.error("onDisableStoredPaymentMethod error",error)})},onSelect:component=>{const id=component._id;id.search("scheme")===-1&&ref.current&&(id.search("paypal")===-1?ref.current.onsubmit=async()=>await handleSubmit(ref.current):ref.current.onsubmit=null,setPaymentRef({ref}))}}).mount("#adyen-dropin");dropin&&checkout2&&(dropinRef.current=dropin,setCheckout(dropin),setLoadAdyen(!0))};dropinRef.current||initializeAdyen()}return()=>{setPaymentRef({ref:{current:null}}),setLoadAdyen(!1)}},[clientKey,ref!=null]),!clientKey&&!loadAdyen&&!checkout?null:_jsxs("form",{ref,onSubmit:e=>{handleSubmit(e)},children:[_jsx("div",{className:cardContainerClassName,id:"adyen-dropin"}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]})}export default AdyenPayment;
@@ -1,7 +1,7 @@
1
- import { type JSX } from 'react';
2
- import type { PaymentMethodConfig } from '../../reducers/PaymentMethodReducer';
3
- import type { PaymentSourceProps } from './PaymentSource';
4
- type KlarnaPaymentProps = PaymentMethodConfig['klarnaPayment'] & JSX.IntrinsicElements['div'] & Partial<PaymentSourceProps['templateCustomerSaveToWallet']> & {
1
+ import { type JSX } from "react";
2
+ import type { PaymentMethodConfig } from "../../reducers/PaymentMethodReducer";
3
+ import type { PaymentSourceProps } from "./PaymentSource";
4
+ type KlarnaPaymentProps = PaymentMethodConfig["klarnaPayment"] & JSX.IntrinsicElements["div"] & Partial<PaymentSourceProps["templateCustomerSaveToWallet"]> & {
5
5
  show?: boolean;
6
6
  clientToken: string;
7
7
  locale?: string | null;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async function(res){if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
2
+ import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useEffect,useRef,useState}from"react";import PaymentMethodContext from"../../context/PaymentMethodContext";import OrderContext from"../../context/OrderContext";import useExternalScript from"../../utils/hooks/useExternalScript";function typeOfLine(lineItemType){switch(lineItemType){case"percentage_discount_promotions":return"discount";case"shipments":return"shipping_fee";case"skus":return"physical";case"payment_methods":default:return null}}function klarnaOrderLines(lineItems){return lineItems?lineItems?.map(item=>{const type=item.item_type?typeOfLine(item.item_type):null;return{quantity:item.quantity,total_amount:item.total_amount_cents,unit_price:item.unit_amount_cents,type}}):[]}export default function KlarnaPayment({clientToken,placeOrderCallback,locale="EN",...p}){const ref=useRef(null),{paymentSource,currentPaymentMethodType,setPaymentRef,setPaymentSource}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),loaded=useExternalScript("https://x.klarnacdn.net/kp/lib/v1/api.js"),[klarna,setKlarna]=useState(),{containerClassName,...divProps}=p;useEffect(()=>{loaded&&window?.Klarna!==void 0&&setKlarna(window.Klarna)},[loaded,window.Klarna]),useEffect(()=>(ref.current&&paymentSource&&currentPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async props=>{handleClick(klarna,props)},setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=(kl,props)=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategories=first?.identifier,billingAddress={given_name:order?.billing_address?.first_name,family_name:order?.billing_address?.last_name,email:order?.customer_email,street_address:order?.billing_address?.line_1,street_address2:null,organization_name:null,postal_code:order?.billing_address?.zip_code,city:order?.billing_address?.city,region:order?.billing_address?.state_code,phone:order?.billing_address?.phone,country:order?.billing_address?.country_code},shippingAddress={given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,email:order?.customer_email,street_address:order?.shipping_address?.line_1,street_address2:null,postal_code:order?.shipping_address?.zip_code,organization_name:null,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code},klarnaData={merchant_data:order?.id,purchase_country:order?.country_code,purchase_currency:order?.currency_code,locale,shipping_address:shippingAddress,billing_address:billingAddress,order_amount:order?.total_amount_cents,order_lines:klarnaOrderLines(order?.line_items),order_tax_amount:order?.total_tax_amount_cents};kl.Payments.authorize({payment_method_category:paymentMethodCategories,...klarnaData},async res=>{if(res.approved&&paymentSource&&currentPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}});if(props.setPlaceOrder!=null){const placed=await props.setPlaceOrder({paymentSource:ps});placed&&props.onclickCallback!=null&&props.onclickCallback(placed)}}})};if(klarna&&clientToken){const[first]=paymentSource?.payment_methods||void 0;klarna.Payments.init({client_token:clientToken}),klarna.Payments.load({container:"#klarna-payments-container",payment_method_category:first?.identifier})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
@@ -1,6 +1,6 @@
1
- import { type JSX } from 'react';
1
+ import { type JSX } from "react";
2
2
  interface Props {
3
3
  clientSecret: string;
4
4
  }
5
- export declare function StripeExpressPayment({ clientSecret }: Props): JSX.Element | null;
5
+ export declare function StripeExpressPayment({ clientSecret, }: Props): JSX.Element | null;
6
6
  export {};
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{getAvailableExpressPayments,getExpressShippingMethods,setExpressFakeAddress,setExpressPlaceOrder,setExpressShippingMethod,expressRedirectUrl}from"../../utils/expressPaymentHelper";import{isEmpty}from"../../utils/isEmpty";import{PaymentRequestButtonElement,useStripe}from"@stripe/react-stripe-js";import{useContext,useEffect,useState}from"react";export function StripeExpressPayment({clientSecret}){const stripe=useStripe(),[paymentRequest,setPaymentRequest]=useState(null),{accessToken,endpoint}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{paymentMethods,paymentSource}=useContext(PaymentMethodContext);return useEffect(()=>{if(stripe==null||order==null)return;const pr=stripe.paymentRequest({country:order?.country_code??"US",currency:order?.currency_code?.toLowerCase()??"",total:{label:`#${order?.number??""}`,amount:order?.total_amount_with_taxes_cents??0},requestPayerName:!0,requestPayerEmail:!0,requestPayerPhone:!0,requestShipping:!0});pr.canMakePayment().then(result=>{result&&setPaymentRequest(pr)}).catch(err=>{console.error("Can make payment:",err)})},[isEmpty(stripe),isEmpty(order)]),paymentRequest!=null&&stripe!=null?(paymentRequest.on("shippingaddresschange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const requiresBillingInfo=order?.requires_billing_info??!1,orderWithShipments=await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:"Fake name",last_name:"Fake lastname",country_code:ev.shippingAddress.country??"",line_1:"Fake street 123",city:ev.shippingAddress.city??"Fake city",zip_code:ev.shippingAddress.postalCode??"12345",state_code:ev.shippingAddress.region??"Fake state",phone:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0}}),shippingOptions=getExpressShippingMethods(orderWithShipments);shippingOptions!=null&&!isEmpty(shippingOptions)?ev.updateWith({status:"success",shippingOptions,total:{label:`#${orderWithShipments?.number??""}`,amount:orderWithShipments?.total_amount_with_taxes_cents??0}}):ev.updateWith({status:"invalid_shipping_address"})}else ev.updateWith({status:"fail"})}),paymentRequest.on("shippingoptionchange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const updatedOrder=await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev.shippingOption.id,params:{include:["shipments.available_shipping_methods"]}});ev.updateWith({status:"success",total:{label:`#${updatedOrder?.number??""}`,amount:updatedOrder?.total_amount_with_taxes_cents??0}})}else ev.updateWith({status:"fail"})}),paymentRequest.on("paymentmethod",async ev=>{if(order?.id==null)throw new Error("Order is null");if(paymentMethods==null)throw new Error("Payment methods are null");const[paymentMethod]=getAvailableExpressPayments(paymentMethods);if(paymentMethod==null)throw new Error("Payment method is null");if(paymentSource==null)throw new Error("Payment source is null");const requiresBillingInfo=order?.requires_billing_info??!1,paymentResource=paymentMethod?.payment_source_type;if(accessToken!=null&&endpoint!=null){const[firstName,lastName]=ev.payerName?.split(" ")??[],[line]=ev.shippingAddress?.addressLine??"",email=ev.payerEmail??"";await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:firstName??"Fake name",last_name:lastName??"Fake lastname",country_code:ev?.shippingAddress?.country??"",line_1:line??"Fake street 123",city:ev?.shippingAddress?.city??"Fake city",zip_code:ev?.shippingAddress?.postalCode??"12345",state_code:ev?.shippingAddress?.region??"Fake state",phone:ev?.payerPhone??"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0},email}),await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev?.shippingOption?.id,params:{include:["shipments.available_shipping_methods"]}});const placeOrderParams={config:{accessToken,endpoint},orderId:order?.id,paymentResource,paymentSourceId:paymentSource?.id};await setExpressPlaceOrder(placeOrderParams);const{paymentIntent,error:confirmError}=await stripe.confirmCardPayment(clientSecret,{payment_method:ev.paymentMethod.id},{handleActions:!1});if(confirmError)ev.complete("fail"),console.error("Confirm card payment:",confirmError);else if(ev.complete("success"),paymentIntent.status==="requires_action"){const{error}=await stripe.confirmCardPayment(clientSecret);if(error)console.error("Confirm card payment:",error);else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}}),_jsx(_Fragment,{children:_jsx(PaymentRequestButtonElement,{className:"",options:{paymentRequest}})})):null}
2
+ import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import OrderContext from"../../context/OrderContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import{getAvailableExpressPayments,getExpressShippingMethods,setExpressFakeAddress,setExpressPlaceOrder,setExpressShippingMethod,expressRedirectUrl}from"../../utils/expressPaymentHelper";import{isEmpty}from"../../utils/isEmpty";import{PaymentRequestButtonElement,useStripe}from"@stripe/react-stripe-js";import{useContext,useEffect,useState}from"react";export function StripeExpressPayment({clientSecret}){const stripe=useStripe(),[paymentRequest,setPaymentRequest]=useState(null),{accessToken,endpoint}=useContext(CommerceLayerContext),{order}=useContext(OrderContext),{paymentMethods,paymentSource}=useContext(PaymentMethodContext);return useEffect(()=>{if(stripe==null||order==null)return;const pr=stripe.paymentRequest({country:order?.country_code??"US",currency:order?.currency_code?.toLowerCase()??"",total:{label:`#${order?.number??""}`,amount:order?.total_amount_with_taxes_cents??0},requestPayerName:!0,requestPayerEmail:!0,requestPayerPhone:!0,requestShipping:!0});pr.canMakePayment().then(result=>{result&&setPaymentRequest(pr)}).catch(err=>{console.error("Can make payment:",err)})},[isEmpty(stripe),isEmpty(order)]),paymentRequest!=null&&stripe!=null?(paymentRequest.on("shippingaddresschange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const requiresBillingInfo=order?.requires_billing_info??!1,orderWithShipments=await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:"Fake name",last_name:"Fake lastname",country_code:ev.shippingAddress.country??"",line_1:"Fake street 123",city:ev.shippingAddress.city??"Fake city",zip_code:ev.shippingAddress.postalCode??"12345",state_code:ev.shippingAddress.region??"Fake state",phone:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0}}),shippingOptions=getExpressShippingMethods(orderWithShipments);shippingOptions!=null&&!isEmpty(shippingOptions)?ev.updateWith({status:"success",shippingOptions,total:{label:`#${orderWithShipments?.number??""}`,amount:orderWithShipments?.total_amount_with_taxes_cents??0}}):ev.updateWith({status:"invalid_shipping_address"})}else ev.updateWith({status:"fail"})}),paymentRequest.on("shippingoptionchange",async ev=>{if(order!=null&&accessToken!=null&&endpoint!=null){const updatedOrder=await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev.shippingOption.id,params:{include:["shipments.available_shipping_methods"]}});ev.updateWith({status:"success",total:{label:`#${updatedOrder?.number??""}`,amount:updatedOrder?.total_amount_with_taxes_cents??0}})}else ev.updateWith({status:"fail"})}),paymentRequest.on("paymentmethod",async ev=>{if(order?.id==null)throw new Error("Order is null");if(paymentMethods==null)throw new Error("Payment methods are null");const[paymentMethod]=getAvailableExpressPayments(paymentMethods);if(paymentMethod==null)throw new Error("Payment method is null");if(paymentSource==null)throw new Error("Payment source is null");const requiresBillingInfo=order?.requires_billing_info??!1,paymentResource=paymentMethod?.payment_source_type;if(accessToken!=null&&endpoint!=null){const[firstName,lastName]=ev.payerName?.split(" ")??[],[line]=ev.shippingAddress?.addressLine??"",email=ev.payerEmail??"";await setExpressFakeAddress({orderId:order.id,config:{accessToken,endpoint},address:{first_name:firstName??"Fake name",last_name:lastName??"Fake lastname",country_code:ev?.shippingAddress?.country??"",line_1:line??"Fake street 123",city:ev?.shippingAddress?.city??"Fake city",zip_code:ev?.shippingAddress?.postalCode??"12345",state_code:ev?.shippingAddress?.region??"Fake state",phone:ev?.payerPhone??"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0},email}),await setExpressShippingMethod({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:ev?.shippingOption?.id,params:{include:["shipments.available_shipping_methods"]}});const placeOrderParams={config:{accessToken,endpoint},orderId:order?.id,paymentResource,paymentSourceId:paymentSource?.id};await setExpressPlaceOrder(placeOrderParams);const{paymentIntent,error:confirmError}=await stripe.confirmCardPayment(clientSecret,{payment_method:ev.paymentMethod.id},{handleActions:!1});if(confirmError)ev.complete("fail"),console.error("Confirm card payment:",confirmError);else if(ev.complete("success"),paymentIntent.status==="requires_action"){const{error}=await stripe.confirmCardPayment(clientSecret);if(error)console.error("Confirm card payment:",error);else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),await expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}else{const placeOrderParams2={config:{accessToken,endpoint},orderId:order?.id,placeTheOrder:!0};try{const order2=await setExpressPlaceOrder(placeOrderParams2);ev.complete("success"),await expressRedirectUrl({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}}),_jsx(_Fragment,{children:_jsx(PaymentRequestButtonElement,{className:"",options:{paymentRequest}})})):null}
@@ -1,6 +1,6 @@
1
- import type { Order } from '@commercelayer/sdk';
2
- import { type OrderState, type SaveAddressToCustomerAddressBook, createOrder, setGiftCardOrCouponCode, removeGiftCardOrCouponCode, addResourceToInclude, updateOrder, type getOrderContext, type addToCart } from '../reducers/OrderReducer';
3
- import type { BaseError } from '../typings/errors';
1
+ import type { Order } from "@commercelayer/sdk";
2
+ import { type OrderState, type SaveAddressToCustomerAddressBook, createOrder, paymentSourceRequest, setGiftCardOrCouponCode, removeGiftCardOrCouponCode, addResourceToInclude, updateOrder, type getOrderContext, type addToCart } from "../reducers/OrderReducer";
3
+ import type { BaseError } from "../typings/errors";
4
4
  interface DefaultContext extends OrderState {
5
5
  createOrder: typeof createOrder;
6
6
  addToCart?: typeof addToCart;
@@ -12,6 +12,7 @@ interface DefaultContext extends OrderState {
12
12
  getOrder: getOrderContext;
13
13
  updateOrder: typeof updateOrder;
14
14
  setOrder: (order: Order) => void;
15
+ paymentSourceRequest: typeof paymentSourceRequest;
15
16
  }
16
17
  export declare const defaultOrderContext: {
17
18
  createOrder: typeof createOrder;
@@ -23,6 +24,7 @@ export declare const defaultOrderContext: {
23
24
  addResourceToInclude: typeof addResourceToInclude;
24
25
  getOrder: () => Promise<undefined>;
25
26
  updateOrder: typeof updateOrder;
27
+ paymentSourceRequest: typeof paymentSourceRequest;
26
28
  };
27
29
  declare const OrderContext: import("react").Context<DefaultContext>;
28
30
  export default OrderContext;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{createContext}from"react";import{createOrder,setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,updateOrder}from"../reducers/OrderReducer";export const defaultOrderContext={createOrder,setOrderErrors:()=>{},setOrder:()=>{},setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,getOrder:async()=>{},updateOrder};const OrderContext=createContext(defaultOrderContext);export default OrderContext;
2
+ import{createContext}from"react";import{createOrder,paymentSourceRequest,setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,updateOrder}from"../reducers/OrderReducer";export const defaultOrderContext={createOrder,setOrderErrors:()=>{},setOrder:()=>{},setGiftCardOrCouponCode,removeGiftCardOrCouponCode,saveAddressToCustomerAddressBook,addResourceToInclude,getOrder:async()=>{},updateOrder,paymentSourceRequest};const OrderContext=createContext(defaultOrderContext);export default OrderContext;
@@ -1,11 +1,11 @@
1
- import type { Dispatch } from 'react';
2
- import { type SetLocalOrder, type DeleteLocalOrder } from '../utils/localStorage';
3
- import type { CommerceLayerConfig } from '../context/CommerceLayerContext';
4
- import type { BaseMetadataObject } from '../typings/index';
5
- import type { BaseError } from '../typings/errors';
6
- import type { AddressResource } from './AddressReducer';
7
- import type { Order, OrderUpdate } from '@commercelayer/sdk';
8
- import type { LooseAutocomplete } from '../typings/globals';
1
+ import type { Dispatch } from "react";
2
+ import { type SetLocalOrder, type DeleteLocalOrder } from "../utils/localStorage";
3
+ import type { CommerceLayerConfig } from "../context/CommerceLayerContext";
4
+ import type { BaseMetadataObject } from "../typings/index";
5
+ import type { BaseError } from "../typings/errors";
6
+ import type { AddressResource } from "./AddressReducer";
7
+ import type { Order, OrderUpdate, CommerceLayerClient, ResourceUpdate, AdyenPaymentUpdate } from "@commercelayer/sdk";
8
+ import type { LooseAutocomplete } from "../typings/globals";
9
9
  export type GetOrderParams = Partial<{
10
10
  clearWhenPlaced: boolean;
11
11
  config: CommerceLayerConfig;
@@ -16,8 +16,8 @@ export type GetOrderParams = Partial<{
16
16
  state: OrderState;
17
17
  }>;
18
18
  export type GetOrder = (params: GetOrderParams) => Promise<undefined | Order>;
19
- type CreateOrderParams = Pick<AddToCartParams, 'config' | 'dispatch' | 'persistKey' | 'state' | 'orderMetadata' | 'orderAttributes' | 'setLocalOrder'>;
20
- export interface AddToCartImportParams extends Omit<AddToCartParams, 'skuCode' | 'skuId' | 'quantity' | 'option' | 'lineItem'> {
19
+ type CreateOrderParams = Pick<AddToCartParams, "config" | "dispatch" | "persistKey" | "state" | "orderMetadata" | "orderAttributes" | "setLocalOrder">;
20
+ export interface AddToCartImportParams extends Omit<AddToCartParams, "skuCode" | "skuId" | "quantity" | "option" | "lineItem"> {
21
21
  lineItems: CustomLineItem[];
22
22
  }
23
23
  export type AddToCartReturn = Promise<{
@@ -26,7 +26,7 @@ export type AddToCartReturn = Promise<{
26
26
  }>;
27
27
  export type AddToCartImport = (params: AddToCartImportParams) => AddToCartReturn;
28
28
  export type UnsetOrderState = (dispatch: Dispatch<OrderActions>) => void;
29
- export type ResourceIncluded = 'billing_address' | 'shipping_address' | 'line_items.line_item_options.sku_option' | 'line_items.item' | 'available_customer_payment_sources.payment_source' | 'available_customer_payment_sources.payment_method' | 'shipments.available_shipping_methods' | 'shipments.stock_transfers' | 'shipments.stock_transfers.line_item' | 'shipments.stock_line_items.line_item' | 'shipments.shipping_method' | 'shipments.stock_location' | 'shipments.parcels' | 'shipments.parcels.parcel_line_items' | 'payment_source' | 'available_payment_methods' | 'payment_method';
29
+ export type ResourceIncluded = "billing_address" | "shipping_address" | "line_items.line_item_options.sku_option" | "line_items.item" | "available_customer_payment_sources.payment_source" | "available_customer_payment_sources.payment_method" | "shipments.available_shipping_methods" | "shipments.stock_transfers" | "shipments.stock_transfers.line_item" | "shipments.stock_line_items.line_item" | "shipments.shipping_method" | "shipments.stock_location" | "shipments.parcels" | "shipments.parcels.parcel_line_items" | "payment_source" | "available_payment_methods" | "payment_method";
30
30
  type ResourceIncludedLoaded = Partial<Record<ResourceIncluded, boolean>>;
31
31
  export interface OrderPayload {
32
32
  loading?: boolean;
@@ -36,30 +36,44 @@ export interface OrderPayload {
36
36
  include?: ResourceIncluded[] | undefined;
37
37
  includeLoaded?: ResourceIncludedLoaded;
38
38
  withoutIncludes?: boolean;
39
+ manageAdyenGiftCard?: boolean;
39
40
  }
40
- export type AddToCartImportValues = Pick<AddToCartImportParams, 'lineItems'>;
41
+ export type AddToCartImportValues = Pick<AddToCartImportParams, "lineItems">;
41
42
  export type getOrderContext = (id: string) => Promise<undefined | Order>;
42
43
  export type OrderState = Partial<OrderPayload>;
43
44
  export interface OrderActions {
44
45
  type: OrderActionType;
45
46
  payload: OrderPayload;
46
47
  }
47
- export type OrderActionType = 'setLoading' | 'setOrderId' | 'setOrder' | 'setSingleQuantity' | 'setCurrentSkuCodes' | 'setCurrentSkuPrices' | 'setCurrentItem' | 'setErrors' | 'setSaveAddressToCustomerAddressBook' | 'setGiftCardOrCouponCode' | 'setIncludesResource';
48
+ export type OrderActionType = "setLoading" | "setOrderId" | "setOrder" | "setSingleQuantity" | "setCurrentSkuCodes" | "setCurrentSkuPrices" | "setCurrentItem" | "setErrors" | "setSaveAddressToCustomerAddressBook" | "setGiftCardOrCouponCode" | "setIncludesResource";
48
49
  export declare function createOrder(params: CreateOrderParams): Promise<string>;
49
50
  export declare const getApiOrder: GetOrder;
50
51
  export interface UpdateOrderArgs {
51
52
  id: string;
52
- attributes: Omit<OrderUpdate, 'id'>;
53
+ attributes: Omit<OrderUpdate, "id">;
53
54
  dispatch?: Dispatch<OrderActions>;
54
55
  include?: string[];
55
56
  config?: CommerceLayerConfig;
56
57
  state?: OrderState;
57
58
  }
58
- export declare function updateOrder({ id, attributes, dispatch, config, include, state }: UpdateOrderArgs): Promise<{
59
+ export declare function updateOrder({ id, attributes, dispatch, config, include, state, }: UpdateOrderArgs): Promise<{
59
60
  success: boolean;
60
61
  error?: unknown;
61
62
  order?: Order;
62
63
  }>;
64
+ interface TResourceRequest {
65
+ resource: Extract<keyof CommerceLayerClient, "adyen_payments">;
66
+ requestType: "update";
67
+ attributes: TResourceRequest["resource"] extends "adyen_payments" ? AdyenPaymentUpdate : ResourceUpdate;
68
+ order: Order;
69
+ dispatch?: Dispatch<OrderActions>;
70
+ config?: CommerceLayerConfig;
71
+ state?: OrderState;
72
+ }
73
+ export declare function paymentSourceRequest({ resource, requestType, dispatch, attributes, config, order, state, }: TResourceRequest): Promise<{
74
+ success: boolean;
75
+ order?: Order;
76
+ }>;
63
77
  export declare const setOrder: (order: Order, dispatch?: Dispatch<OrderActions>) => void;
64
78
  export interface AddResourceToInclude {
65
79
  resourcesIncluded?: ResourceIncluded[];
@@ -68,7 +82,7 @@ export interface AddResourceToInclude {
68
82
  resourceIncludedLoaded?: ResourceIncludedLoaded;
69
83
  newResourceLoaded?: ResourceIncludedLoaded;
70
84
  }
71
- export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded }: AddResourceToInclude): void;
85
+ export declare function addResourceToInclude({ resourcesIncluded, dispatch, newResource, newResourceLoaded, resourceIncludedLoaded, }: AddResourceToInclude): void;
72
86
  export interface LineItemOption {
73
87
  /**
74
88
  * SKU Option ID. Ex: mNJEgsJwBn
@@ -80,7 +94,7 @@ export interface LineItemOption {
80
94
  options: Record<string, string>;
81
95
  quantity?: number;
82
96
  }
83
- type TFrequency = 'hourly' | 'daily' | 'weekly' | 'monthly' | 'two-month' | 'three-month' | 'four-month' | 'six-month' | 'yearly';
97
+ type TFrequency = "hourly" | "daily" | "weekly" | "monthly" | "two-month" | "three-month" | "four-month" | "six-month" | "yearly";
84
98
  export interface CustomLineItem {
85
99
  name?: string;
86
100
  imageUrl?: string | null;
@@ -134,11 +148,11 @@ interface TSetGiftCardOrCouponCodeParams {
134
148
  include?: string[];
135
149
  state?: OrderState;
136
150
  }
137
- export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state }: TSetGiftCardOrCouponCodeParams): Promise<{
151
+ export declare function setGiftCardOrCouponCode({ code, codeType, dispatch, config, order, include, state, }: TSetGiftCardOrCouponCodeParams): Promise<{
138
152
  success: boolean;
139
153
  order?: Order;
140
154
  }>;
141
- export type CodeType = 'coupon' | 'gift_card';
155
+ export type CodeType = "coupon" | "gift_card";
142
156
  export type OrderCodeType = `${CodeType}_code`;
143
157
  interface TRemoveGiftCardOrCouponCodeParams {
144
158
  codeType: OrderCodeType;
@@ -148,7 +162,7 @@ interface TRemoveGiftCardOrCouponCodeParams {
148
162
  include?: string[];
149
163
  state?: OrderState;
150
164
  }
151
- export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state }: TRemoveGiftCardOrCouponCodeParams): Promise<{
165
+ export declare function removeGiftCardOrCouponCode({ codeType, dispatch, config, order, include, state, }: TRemoveGiftCardOrCouponCodeParams): Promise<{
152
166
  success: boolean;
153
167
  order?: Order;
154
168
  }>;
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
2
+ import{setCustomerOrderParam}from"../utils/localStorage";import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getSdk from"../utils/getSdk";import getErrors,{setErrors}from"../utils/getErrors";import{getOrganizationConfig}from"../utils/organization";import{publish}from"../utils/events";import{getDomain}from"../utils/getDomain";import{getApplicationLink}from"../utils/getApplicationLink";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export async function createOrder(params){if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return"";const o=await sdk?.orders.create({metadata,...orderAttributes});return dispatch&&dispatch({type:"setOrderId",payload:{orderId:o?.id}}),persistKey&&setLocalOrder&&setLocalOrder(persistKey,o.id),o.id}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""}export const getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return;const options={};state?.include&&state.include.length>0&&(options.include=state.include);const order=await sdk.orders.retrieve(id??"",options);return clearWhenPlaced&&order.editable===!1?(persistKey&&deleteLocalOrder&&deleteLocalOrder(persistKey),dispatch&&dispatch({type:"setOrder",payload:{order:void 0,orderId:""}})):dispatch&&dispatch({type:"setOrder",payload:{order,orderId:order.id}}),order}catch(error){const errors=getErrors({error,resource:"orders"});console.error("Retrieve order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch});return}};export async function updateOrder({id,attributes,dispatch,config,include,state}){const sdk=config!=null?getSdk(config):void 0;try{if(sdk==null)return{success:!1};const resource={...attributes,id};await sdk.orders.update(resource,{include});const order=await getApiOrder({id,config,dispatch,state});return dispatch&&order&&dispatch({type:"setOrder",payload:{order}}),{success:!0,order}}catch(error){const errors=getErrors({error,resource:"orders"});return dispatch&&(setOrderErrors({errors,dispatch}),dispatch({type:"setErrors",payload:{errors}})),{success:!1,error}}}export async function paymentSourceRequest({resource,requestType,dispatch,attributes,config,order,state}){const sdk=config!=null?getSdk(config):void 0;try{return sdk==null?{success:!1}:(await sdk[resource][requestType](attributes),{success:!0,order:(await updateOrder({id:order.id,attributes:{},config,include:state?.include,dispatch,state}))?.order})}catch(error){console.error("Resource request",error);const errors=getErrors({error,resource:"orders"});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const setOrder=(order,dispatch)=>{dispatch&&dispatch({type:"setOrder",payload:{order}})};export function addResourceToInclude({resourcesIncluded=[],dispatch,newResource,newResourceLoaded,resourceIncludedLoaded}){const payload={include:void 0,includeLoaded:void 0};if(newResource){const resources=typeof newResource=="string"?[newResource]:newResource;payload.include=[...new Set([...resourcesIncluded,...resources])],resources.forEach(resource=>{const includeLoaded={...payload.includeLoaded,[resource]:!0};payload.includeLoaded=includeLoaded})}else delete payload.include;const payloadIncludeLoaded={...resourceIncludedLoaded,...newResourceLoaded,...payload.includeLoaded&&payload.includeLoaded};payload.includeLoaded=payloadIncludeLoaded,dispatch&&dispatch({type:"setIncludesResource",payload:{...payload,withoutIncludes:!1}})}export async function addToCart(params){const{skuCode,bundleCode,quantity,config,dispatch,lineItem,state,errors=[],buyNowMode,checkoutUrl,lineItemOption,openMiniCart=!0}=params;try{if(config){const sdk=getSdk(config),id=await createOrder(params);if(id){const order=sdk.orders.relationship(id),name=lineItem?.name,imageUrl=lineItem?.imageUrl,metadata=lineItem?.metadata,frequency=lineItem?.frequency,externalPrice=lineItem?.externalPrice;if(buyNowMode)if(state?.order?.line_items)await Promise.all(state?.order?.line_items.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}));else{const{line_items:lineItems}=await sdk.orders.retrieve(id,{fields:["line_items"],include:["line_items"]});lineItems&&lineItems?.length>0&&await Promise.all(lineItems.map(async lineItem2=>{await sdk.line_items.delete(lineItem2.id)}))}const attrs={order,sku_code:skuCode,name,image_url:imageUrl,quantity:quantity??1,_update_quantity:lineItem?._update_quantity??!0,bundle_code:bundleCode,metadata,frequency};externalPrice===!0&&(attrs._external_price=externalPrice);const newLineItem=await sdk.line_items.create(attrs);if(lineItemOption!=null){const{skuOptionId,options,quantity:quantity2}=lineItemOption,skuOption=sdk.sku_options.relationship(skuOptionId),lineItemRel=sdk.line_items.relationship(newLineItem.id),lineItemOptionsAttributes={quantity:quantity2??1,options,sku_option:skuOption,line_item:lineItemRel};await sdk.line_item_options.create(lineItemOptionsAttributes),await getApiOrder({id,...params})}else await getApiOrder({id,...params,state});if(!isEmpty(errors)&&dispatch&&dispatch({type:"setErrors",payload:{errors:[]}}),buyNowMode&&id&&config?.accessToken!=null&&config?.endpoint!=null){const params2=`${id}?accessToken=${config.accessToken??""}`,{domain,slug}=getDomain(config.endpoint),href=getApplicationLink({slug,orderId:id,accessToken:config.accessToken,applicationType:"checkout",domain}),organizationConfig=await getOrganizationConfig({accessToken:config.accessToken,endpoint:config.endpoint,params:{accessToken:config.accessToken,orderId:order?.id,slug}}),redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:organizationConfig?.links?.checkout??href;location.href=redirectUrl}else openMiniCart&&publish("open-cart");return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors({error,resource:"orders"});return console.error("Add to cart",errors2),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors2,dispatch}),{success:!1}}}export const unsetOrderState=dispatch=>{dispatch({type:"setOrderId",payload:{orderId:""}}),dispatch({type:"setOrder",payload:{order:void 0}})};export function setOrderErrors({dispatch,errors=[]}){return dispatch&&dispatch({type:"setErrors",payload:{errors}}),{success:!1}}export const saveAddressToCustomerAddressBook=({type,value,dispatch})=>{const k=`_save_${type}_to_customer_address_book`,v=`${value.toString()}`;setCustomerOrderParam(k,v),dispatch&&dispatch({type:"setSaveAddressToCustomerAddressBook",payload:{[k]:v}})};export async function setGiftCardOrCouponCode({code,codeType,dispatch,config,order,include,state}){try{if(config&&order&&code&&dispatch){const attributes={[codeType]:code},{success,order:currentOrder,error}=await updateOrder({id:order.id,attributes,config,include,dispatch,state});if(!success)throw error;return dispatch({type:"setErrors",payload:{errors:[]}}),{success,order:currentOrder}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export async function removeGiftCardOrCouponCode({codeType,dispatch,config,order,include,state}){try{if(config&&order&&dispatch){const attributes={[codeType]:""},orderUpdated=await updateOrder({id:order.id,attributes,config,include,dispatch,state});return dispatch({type:"setErrors",payload:{errors:[]}}),{success:!0,order:orderUpdated?.order}}return{success:!1}}catch(error){const errors=getErrors({error,resource:"orders",field:codeType});return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
@@ -0,0 +1,16 @@
1
+ import type { Order } from "@commercelayer/sdk";
2
+ export interface GiftCardData {
3
+ cardSummary: string;
4
+ currentBalanceValue: number;
5
+ currentBalanceCurrency: string;
6
+ formattedBalanceValue: string;
7
+ cardBrand: string;
8
+ }
9
+ interface Props {
10
+ order?: Order;
11
+ }
12
+ interface ReturnTypes extends GiftCardData {
13
+ formattedOrderTotal: string;
14
+ }
15
+ export declare function manageGiftCard({ order }: Props): ReturnTypes | null;
16
+ export {};
@@ -0,0 +1,2 @@
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_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}}
@@ -88,5 +88,5 @@ interface TExpressRedirectUrlParams {
88
88
  */
89
89
  config: CommerceLayerConfig;
90
90
  }
91
- export declare function expressRedirectUrl({ order, config: { accessToken, endpoint }, }: TExpressRedirectUrlParams): void;
91
+ export declare function expressRedirectUrl({ order, config: { accessToken, endpoint }, }: TExpressRedirectUrlParams): Promise<void>;
92
92
  export {};