@commercelayer/react-components 4.2.2 → 4.2.3-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.
- package/lib/cjs/components/addresses/BillingAddressContainer.d.ts +2 -2
- package/lib/cjs/components/customers/CustomerContainer.d.ts +2 -2
- package/lib/cjs/components/customers/CustomerContainer.js +1 -1
- package/lib/cjs/components/customers/CustomerPaymentSource.d.ts +10 -0
- package/lib/cjs/components/customers/CustomerPaymentSource.js +1 -0
- package/lib/cjs/components/customers/CustomerPaymentSourceEmpty.d.ts +13 -0
- package/lib/cjs/components/customers/CustomerPaymentSourceEmpty.js +1 -0
- package/lib/cjs/components/line_items/LineItemOption.js +1 -1
- package/lib/cjs/components/line_items/LineItemQuantity.js +1 -1
- package/lib/cjs/components/orders/OrderList.js +1 -1
- package/lib/cjs/components/orders/PlaceOrderContainer.js +1 -1
- package/lib/cjs/components/payment_source/CheckoutComPayment.d.ts +2 -2
- package/lib/cjs/components/payment_source/CheckoutComPayment.js +1 -1
- package/lib/cjs/components/payment_source/KlarnaPayment.d.ts +1 -1
- package/lib/cjs/components/payment_source/KlarnaPayment.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceBrandIcon.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceBrandName.js +1 -1
- package/lib/cjs/components/payment_source/PaymentSourceDetail.d.ts +4 -1
- package/lib/cjs/components/payment_source/PaymentSourceDetail.js +1 -1
- package/lib/cjs/components/payment_source/PaypalPayment.d.ts +3 -3
- package/lib/cjs/components/payment_source/PaypalPayment.js +1 -1
- package/lib/cjs/components/shipments/Shipment.js +1 -1
- package/lib/cjs/components/shipments/ShipmentsContainer.js +1 -1
- package/lib/cjs/components/skus/AvailabilityContainer.js +1 -1
- package/lib/cjs/components/skus/AvailabilityTemplate.js +1 -1
- package/lib/cjs/components/utils/BaseInput.d.ts +1 -1
- package/lib/cjs/components/utils/GenericFieldComponent.js +1 -1
- package/lib/cjs/components/utils/getAllErrors.d.ts +2 -4
- package/lib/cjs/components/utils/getAllErrors.js +1 -1
- package/lib/cjs/context/CouponAndGiftCardFormContext.d.ts +2 -2
- package/lib/cjs/context/CustomerAddressFormContext.d.ts +2 -2
- package/lib/cjs/context/CustomerContext.d.ts +5 -5
- package/lib/cjs/context/CustomerPaymentSourceContext.d.ts +11 -0
- package/lib/cjs/context/CustomerPaymentSourceContext.js +1 -0
- package/lib/cjs/context/PaymentSourceContext.d.ts +2 -2
- package/lib/cjs/reducers/AvailabilityReducer.d.ts +1 -0
- package/lib/cjs/reducers/AvailabilityReducer.js +1 -1
- package/lib/cjs/reducers/BillingAddressReducer.d.ts +3 -3
- package/lib/cjs/reducers/BillingAddressReducer.js +1 -1
- package/lib/cjs/reducers/CustomerReducer.d.ts +7 -4
- package/lib/cjs/reducers/CustomerReducer.js +1 -1
- package/lib/cjs/reducers/GiftCardReducer.js +1 -1
- package/lib/cjs/reducers/LineItemReducer.d.ts +3 -3
- package/lib/cjs/reducers/LineItemReducer.js +1 -1
- package/lib/cjs/reducers/OrderReducer.d.ts +2 -1
- package/lib/cjs/reducers/OrderReducer.js +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.d.ts +1 -1
- package/lib/cjs/reducers/PaymentMethodReducer.js +1 -1
- package/lib/cjs/reducers/PlaceOrderReducer.js +1 -1
- package/lib/cjs/reducers/PriceReducer.js +1 -1
- package/lib/cjs/reducers/ShippingAddressReducer.d.ts +4 -4
- package/lib/cjs/reducers/ShippingAddressReducer.js +1 -1
- package/lib/cjs/typings/errors.d.ts +4 -1
- package/lib/cjs/utils/baseReducer.js +1 -1
- package/lib/cjs/utils/checkIncludeResource.d.ts +3 -3
- package/lib/cjs/utils/compareObjAttribute.d.ts +3 -3
- package/lib/cjs/utils/countryStateCity.d.ts +5 -6
- package/lib/cjs/utils/customMessages.d.ts +1 -1
- package/lib/cjs/utils/filterChildren.d.ts +1 -1
- package/lib/cjs/utils/getAmount.d.ts +1 -3
- package/lib/cjs/utils/getAmount.js +1 -1
- package/lib/cjs/utils/getCardDetails.d.ts +5 -5
- package/lib/cjs/utils/getCartLink.d.ts +2 -2
- package/lib/cjs/utils/getErrors.d.ts +11 -5
- package/lib/cjs/utils/getErrors.js +1 -1
- package/lib/cjs/utils/jwt.d.ts +2 -2
- package/lib/cjs/utils/promisify.js +1 -1
- package/lib/cjs/utils/shipments.js +1 -1
- package/lib/esm/components/addresses/BillingAddressContainer.d.ts +2 -2
- package/lib/esm/components/customers/CustomerContainer.d.ts +2 -2
- package/lib/esm/components/customers/CustomerContainer.js +1 -1
- package/lib/esm/components/customers/CustomerPaymentSource.d.ts +10 -0
- package/lib/esm/components/customers/CustomerPaymentSource.js +1 -0
- package/lib/esm/components/customers/CustomerPaymentSourceEmpty.d.ts +13 -0
- package/lib/esm/components/customers/CustomerPaymentSourceEmpty.js +1 -0
- package/lib/esm/components/line_items/LineItemOption.js +1 -1
- package/lib/esm/components/line_items/LineItemQuantity.js +1 -1
- package/lib/esm/components/orders/OrderList.js +1 -1
- package/lib/esm/components/orders/PlaceOrderContainer.js +1 -1
- package/lib/esm/components/payment_source/CheckoutComPayment.d.ts +2 -2
- package/lib/esm/components/payment_source/CheckoutComPayment.js +1 -1
- package/lib/esm/components/payment_source/KlarnaPayment.d.ts +1 -1
- package/lib/esm/components/payment_source/KlarnaPayment.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceBrandIcon.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceBrandName.js +1 -1
- package/lib/esm/components/payment_source/PaymentSourceDetail.d.ts +4 -1
- package/lib/esm/components/payment_source/PaymentSourceDetail.js +1 -1
- package/lib/esm/components/payment_source/PaypalPayment.d.ts +3 -3
- package/lib/esm/components/payment_source/PaypalPayment.js +1 -1
- package/lib/esm/components/shipments/Shipment.js +1 -1
- package/lib/esm/components/shipments/ShipmentsContainer.js +1 -1
- package/lib/esm/components/skus/AvailabilityContainer.js +1 -1
- package/lib/esm/components/skus/AvailabilityTemplate.js +1 -1
- package/lib/esm/components/utils/BaseInput.d.ts +1 -1
- package/lib/esm/components/utils/GenericFieldComponent.js +1 -1
- package/lib/esm/components/utils/getAllErrors.d.ts +2 -4
- package/lib/esm/components/utils/getAllErrors.js +1 -1
- package/lib/esm/context/CouponAndGiftCardFormContext.d.ts +2 -2
- package/lib/esm/context/CustomerAddressFormContext.d.ts +2 -2
- package/lib/esm/context/CustomerContext.d.ts +5 -5
- package/lib/esm/context/CustomerPaymentSourceContext.d.ts +11 -0
- package/lib/esm/context/CustomerPaymentSourceContext.js +1 -0
- package/lib/esm/context/PaymentSourceContext.d.ts +2 -2
- package/lib/esm/reducers/AvailabilityReducer.d.ts +1 -0
- package/lib/esm/reducers/AvailabilityReducer.js +1 -1
- package/lib/esm/reducers/BillingAddressReducer.d.ts +3 -3
- package/lib/esm/reducers/BillingAddressReducer.js +1 -1
- package/lib/esm/reducers/CustomerReducer.d.ts +7 -4
- package/lib/esm/reducers/CustomerReducer.js +1 -1
- package/lib/esm/reducers/GiftCardReducer.js +1 -1
- package/lib/esm/reducers/LineItemReducer.d.ts +3 -3
- package/lib/esm/reducers/LineItemReducer.js +1 -1
- package/lib/esm/reducers/OrderReducer.d.ts +2 -1
- package/lib/esm/reducers/OrderReducer.js +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.d.ts +1 -1
- package/lib/esm/reducers/PaymentMethodReducer.js +1 -1
- package/lib/esm/reducers/PlaceOrderReducer.js +1 -1
- package/lib/esm/reducers/PriceReducer.js +1 -1
- package/lib/esm/reducers/ShippingAddressReducer.d.ts +4 -4
- package/lib/esm/reducers/ShippingAddressReducer.js +1 -1
- package/lib/esm/typings/errors.d.ts +4 -1
- package/lib/esm/utils/baseReducer.js +1 -1
- package/lib/esm/utils/checkIncludeResource.d.ts +3 -3
- package/lib/esm/utils/compareObjAttribute.d.ts +3 -3
- package/lib/esm/utils/countryStateCity.d.ts +5 -6
- package/lib/esm/utils/customMessages.d.ts +1 -1
- package/lib/esm/utils/filterChildren.d.ts +1 -1
- package/lib/esm/utils/getAmount.d.ts +1 -3
- package/lib/esm/utils/getAmount.js +1 -1
- package/lib/esm/utils/getCardDetails.d.ts +5 -5
- package/lib/esm/utils/getCartLink.d.ts +2 -2
- package/lib/esm/utils/getErrors.d.ts +11 -5
- package/lib/esm/utils/getErrors.js +1 -1
- package/lib/esm/utils/jwt.d.ts +2 -2
- package/lib/esm/utils/promisify.js +1 -1
- package/lib/esm/utils/shipments.js +1 -1
- package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
- package/lib/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +17 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PlaceOrderContext from"../../context/PlaceOrderContext";import{useContext,useEffect,useReducer}from"react";import placeOrderReducer,{placeOrderInitialState,placeOrderPermitted,setButtonRef}from"../../reducers/PlaceOrderReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import{setPlaceOrder}from"../../reducers/PlaceOrderReducer";import useCustomContext from"../../utils/hooks/useCustomContext";export function PlaceOrderContainer(props){const{children,options}=props,[state,dispatch]=useReducer(placeOrderReducer,placeOrderInitialState),{order,setOrder,setOrderErrors,include,addResourceToInclude,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PlaceOrderContainer",key:"order"}),config=useContext(CommerceLayerContext);useEffect(()=>{include?.includes("shipments.available_shipping_methods")?includeLoaded?.["shipments.available_shipping_methods"]||addResourceToInclude({newResourceLoaded:{"shipments.available_shipping_methods":!0,"shipments.
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PlaceOrderContext from"../../context/PlaceOrderContext";import{useContext,useEffect,useReducer}from"react";import placeOrderReducer,{placeOrderInitialState,placeOrderPermitted,setButtonRef}from"../../reducers/PlaceOrderReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import{setPlaceOrder}from"../../reducers/PlaceOrderReducer";import useCustomContext from"../../utils/hooks/useCustomContext";export function PlaceOrderContainer(props){const{children,options}=props,[state,dispatch]=useReducer(placeOrderReducer,placeOrderInitialState),{order,setOrder,setOrderErrors,include,addResourceToInclude,includeLoaded}=useCustomContext({context:OrderContext,contextComponentName:"OrderContainer",currentComponentName:"PlaceOrderContainer",key:"order"}),config=useContext(CommerceLayerContext);useEffect(()=>{include?.includes("shipments.available_shipping_methods")?includeLoaded?.["shipments.available_shipping_methods"]||addResourceToInclude({newResourceLoaded:{"shipments.available_shipping_methods":!0,"shipments.stock_line_items.line_item":!0,"shipments.shipping_method":!0,"shipments.stock_transfers.line_item":!0,"shipments.stock_location":!0}}):addResourceToInclude({newResource:["shipments.available_shipping_methods","shipments.stock_line_items.line_item","shipments.shipping_method","shipments.stock_transfers.line_item","shipments.stock_location"]}),include?.includes("billing_address")?includeLoaded?.billing_address||addResourceToInclude({newResourceLoaded:{billing_address:!0}}):addResourceToInclude({newResource:"billing_address"}),include?.includes("shipping_address")?includeLoaded?.shipping_address||addResourceToInclude({newResourceLoaded:{shipping_address:!0}}):addResourceToInclude({newResource:"shipping_address",resourcesIncluded:include}),order&&placeOrderPermitted({config,dispatch,order,options:{...options}})},[order,include,includeLoaded]);const contextValue={...state,setPlaceOrder:async({paymentSource})=>await setPlaceOrder({config,order,state,setOrderErrors,paymentSource,include,setOrder}),placeOrderPermitted:()=>placeOrderPermitted({config,dispatch,order,options:{...options}}),setButtonRef:ref=>setButtonRef(ref,dispatch)};return _jsx(PlaceOrderContext.Provider,{value:contextValue,children})}export default PlaceOrderContainer;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PaymentMethodConfig } from '../../reducers/PaymentMethodReducer';
|
|
2
2
|
import { PaymentSourceProps } from './PaymentSource';
|
|
3
3
|
import { FramesStyle } from 'frames-react';
|
|
4
|
-
export
|
|
4
|
+
export interface CheckoutComConfig {
|
|
5
5
|
containerClassName?: string;
|
|
6
6
|
hintLabel?: string;
|
|
7
7
|
name?: string;
|
|
@@ -11,7 +11,7 @@ export type CheckoutComConfig = {
|
|
|
11
11
|
style: FramesStyle;
|
|
12
12
|
};
|
|
13
13
|
[key: string]: unknown;
|
|
14
|
-
}
|
|
14
|
+
}
|
|
15
15
|
type Props = PaymentMethodConfig['checkoutComPayment'] & JSX.IntrinsicElements['div'] & {
|
|
16
16
|
show?: boolean;
|
|
17
17
|
publicKey: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Frames,CardNumber,ExpiryDate,Cvv}from"frames-react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://cdn.checkout.com/js/framesv2.min.js",systemLanguages=["DE-DE","EN-GB","ES-ES","FR-FR","IT-IT","KR-KR","NL-NL"],defaultOptions={style:{base:{color:"black",fontSize:"18px"},autofill:{backgroundColor:"yellow"},hover:{color:"blue"},focus:{color:"blue"},valid:{color:"green"},invalid:{color:"red"},placeholder:{base:{color:"gray"},focus:{border:"solid 1px blue"}}}};export function CheckoutComPayment({publicKey,options=defaultOptions,locale="EN-GB",...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,
|
|
1
|
+
import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useContext,useRef}from"react";import useExternalScript from"../../utils/hooks/useExternalScript";import PaymentMethodContext from"../../context/PaymentMethodContext";import{Frames,CardNumber,ExpiryDate,Cvv}from"frames-react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import{setCustomerOrderParam}from"../../utils/localStorage";const scriptUrl="https://cdn.checkout.com/js/framesv2.min.js",systemLanguages=["DE-DE","EN-GB","ES-ES","FR-FR","IT-IT","KR-KR","NL-NL"],defaultOptions={style:{base:{color:"black",fontSize:"18px"},autofill:{backgroundColor:"yellow"},hover:{color:"blue"},focus:{color:"blue"},valid:{color:"green"},invalid:{color:"red"},placeholder:{base:{color:"gray"},focus:{border:"solid 1px blue"}}}};export function CheckoutComPayment({publicKey,options=defaultOptions,locale="EN-GB",...p}){const ref=useRef(null),loaded=useExternalScript(scriptUrl),{setPaymentRef,currentPaymentMethodType,paymentSource,setPaymentSource,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{containerClassName,templateCustomerSaveToWallet,successUrl=window.location.href,failureUrl=window.location.href,show,...divProps}=p,handleSubmit=async()=>{const savePaymentSourceToCustomerWallet=ref?.current?.elements?.save_payment_source_to_customer_wallet?.checked;if(savePaymentSourceToCustomerWallet&&setCustomerOrderParam("_save_payment_source_to_customer_wallet",savePaymentSourceToCustomerWallet),window.Frames){window.Frames.cardholder={name:order?.billing_address?.full_name,billingAddress:{addressLine1:order?.billing_address?.line_1,addressLine2:order?.billing_address?.line_2,zip:order?.billing_address?.zip_code,city:order?.billing_address?.city,state:order?.billing_address?.state_code,country:order?.billing_address?.country_code},phone:order?.billing_address?.phone};try{const data=await window.Frames.submitCard();if(data.token&&paymentSource&¤tPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{token:data.token,payment_type:"token",success_url:successUrl,failure_url:failureUrl,_authorize:!0}});ps?.redirect_uri&&(window.location.href=ps.redirect_uri)}}catch(error){console.error(error),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:error?.message}])}}return!1},lang=`${locale.toUpperCase()}-${locale.toUpperCase()}`,localization=systemLanguages.includes(lang)?lang:"EN-GB";return loaded&&show?_jsxs("form",{ref,children:[_jsx("div",{className:containerClassName,...divProps,children:_jsxs(Frames,{config:{debug:!0,publicKey,localization,...options},cardValidationChanged:e=>{e.isValid&&ref.current&&(ref.current.onsubmit=async()=>await handleSubmit(),setPaymentRef({ref}))},cardTokenized:data=>data,children:[_jsx(CardNumber,{}),_jsx(ExpiryDate,{}),_jsx(Cvv,{})]})}),templateCustomerSaveToWallet&&_jsx(Parent,{name:"save_payment_source_to_customer_wallet",children:templateCustomerSaveToWallet})]}):null}export default CheckoutComPayment;
|
|
@@ -5,5 +5,5 @@ type KlarnaPaymentProps = PaymentMethodConfig['klarnaPayment'] & JSX.IntrinsicEl
|
|
|
5
5
|
clientToken: string;
|
|
6
6
|
locale?: string;
|
|
7
7
|
};
|
|
8
|
-
export default function KlarnaPayment({ clientToken, placeOrderCallback, locale, ...p }: KlarnaPaymentProps): JSX.Element;
|
|
8
|
+
export default function KlarnaPayment({ clientToken, placeOrderCallback, locale, ...p }: KlarnaPaymentProps): JSX.Element | null;
|
|
9
9
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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";import PlaceOrderContext from"../../context/PlaceOrderContext";function typeOfLine(lineItemType){switch(lineItemType){case"
|
|
1
|
+
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";import PlaceOrderContext from"../../context/PlaceOrderContext";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{name:item.name,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,setPaymentMethodErrors}=useContext(PaymentMethodContext),{order}=useContext(OrderContext),{setPlaceOrder}=useContext(PlaceOrderContext),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&¤tPaymentMethodType&&loaded&&klarna&&(ref.current.onsubmit=async()=>await handleClick(klarna),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType,loaded,klarna]);const handleClick=async kl=>{const[first]=paymentSource?.payment_methods||void 0,paymentMethodCategory=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)};try{kl.Payments.load({container:"#klarna-payments-container",payment_method_category:paymentMethodCategory},{billing_address:billingAddress,shipping_address:shippingAddress},async function({show_form}){if(show_form)try{await kl.Payments.authorize({payment_method_category:paymentMethodCategory},klarnaData,async function(res){if(res.approved&&paymentSource&¤tPaymentMethodType){const ps=await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{auth_token:res.authorization_token}}),{placed}=setPlaceOrder&&ps&&await setPlaceOrder({paymentSource:ps})||{placed:!1};placed&&placeOrderCallback&&placeOrderCallback({placed})}})}catch(e){console.error("e",e),setPaymentMethodErrors([{code:"PAYMENT_INTENT_AUTHENTICATION_FAILURE",resource:"payment_methods",field:currentPaymentMethodType,message:"Authorization error"}])}})}catch(e){console.error("Load Klarna libray",e)}};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},{billing_address:{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:order?.billing_address?.line_2,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},shipping_address:{given_name:order?.shipping_address?.first_name,family_name:order?.shipping_address?.last_name,street_address:order?.shipping_address?.line_1,street_address2:order?.shipping_address?.line_2,postal_code:order?.shipping_address?.zip_code,city:order?.shipping_address?.city,region:order?.shipping_address?.state_code,phone:order?.shipping_address?.phone,country:order?.shipping_address?.country_code}})}return _jsx("form",{ref,children:_jsx("div",{className:containerClassName,...divProps,children:_jsx("div",{id:"klarna-payments-container"})})})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import{useContext,useRef}from"react";import Parent from"../utils/Parent";export function PaymentSourceBrandIcon({src,width=32,children,...p}){const{brand}=useContext(PaymentSourceContext),ref=useRef(null),defaultSrc="//data.commercelayer.app/assets/images/icons/credit-cards/color/credit-card.svg",url=src||`//data.commercelayer.app/assets/images/icons/credit-cards/color/${
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import{useContext,useRef}from"react";import Parent from"../utils/Parent";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";export function PaymentSourceBrandIcon({src,width=32,children,...p}){const{brand}=useContext(PaymentSourceContext),{brand:customerCardBrand}=useContext(CustomerPaymentSourceContext),cardBrand=brand??customerCardBrand,ref=useRef(null),defaultSrc="//data.commercelayer.app/assets/images/icons/credit-cards/color/credit-card.svg",url=src||`//data.commercelayer.app/assets/images/icons/credit-cards/color/${cardBrand??"credit-card"}.svg`,handleError=()=>{ref.current&&(ref.current.src=defaultSrc)},parentProps={brand:cardBrand,defaultSrc,url,width,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("img",{ref,src:url,onError:handleError,width,...p})}export default PaymentSourceBrandIcon;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import capitalize from"lodash/capitalize";import{useContext}from"react";import Parent from"../utils/Parent";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";export function PaymentSourceBrandName({children,label,...props}){const{brand}=useContext(PaymentSourceContext),{brand:customerCardBrand}=useContext(CustomerPaymentSourceContext),cardBrand=brand??customerCardBrand,brandName=cardBrand&&capitalize(cardBrand.replaceAll(/_|-/gm," ")),parentProps={brand:brandName,label,...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{...props,children:label||capitalize(brandName)})}export default PaymentSourceBrandName;
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { ChildrenFunction } from '../../typings/index';
|
|
1
|
+
import type { ChildrenFunction } from '../../typings/index';
|
|
2
2
|
export type PaymentSourceDetailType = 'last4' | 'exp_year' | 'exp_month';
|
|
3
3
|
interface ChildrenProps extends Omit<Props, 'children'> {
|
|
4
4
|
text: string;
|
|
5
5
|
}
|
|
6
6
|
interface Props extends Omit<JSX.IntrinsicElements['span'], 'children'> {
|
|
7
7
|
children?: ChildrenFunction<ChildrenProps>;
|
|
8
|
+
/**
|
|
9
|
+
* Type of detail to display
|
|
10
|
+
*/
|
|
8
11
|
type: PaymentSourceDetailType;
|
|
9
12
|
}
|
|
10
13
|
export declare function PaymentSourceDetail({ type, children, ...p }: Props): JSX.Element;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import{
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentSourceContext from"../../context/PaymentSourceContext";import{useContext}from"react";import Parent from"../utils/Parent";import CustomerPaymentSourceContext from"../../context/CustomerPaymentSourceContext";export function PaymentSourceDetail({type,children,...p}){const card=useContext(PaymentSourceContext),customerCard=useContext(CustomerPaymentSourceContext),cardObj=Object.keys(card).length>0?card:customerCard,text=type in cardObj?cardObj[type]:type==="last4"?"****":"**",parentProps={type,text,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{...p,children:text})}export default PaymentSourceDetail;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { ReactNode } from 'react';
|
|
2
|
-
export
|
|
2
|
+
export interface PaypalConfig {
|
|
3
3
|
return_url: string;
|
|
4
4
|
cancel_url: string;
|
|
5
5
|
infoMessage?: {
|
|
6
6
|
text?: string | ReactNode;
|
|
7
7
|
className?: string;
|
|
8
8
|
};
|
|
9
|
-
}
|
|
9
|
+
}
|
|
10
10
|
type Props = Omit<PaypalConfig, 'return_url' | 'cancel_url'> & JSX.IntrinsicElements['div'];
|
|
11
|
-
export declare function PaypalPayment({ infoMessage, ...p }: Props): JSX.Element;
|
|
11
|
+
export declare function PaypalPayment({ infoMessage, ...p }: Props): JSX.Element | null;
|
|
12
12
|
export default PaypalPayment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext from"../../context/PaymentMethodContext";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef}from"react";const defaultMessage="by placing the order, you will be redirected to the PayPal website to sign in and authorize the payment";export function PaypalPayment({infoMessage,...p}){const ref=useRef(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext);useEffect(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&paymentSource?.approval_url&&(ref.current.onsubmit=()=>handleClick(),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType]);const handleClick=async()=>{if(paymentSource&¤tPaymentMethodType)try{return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{metadata:{card:{id:paymentSource.id,brand:"paypal",last4:""}}}}),!0}catch{return!1}return!1};return _jsx("form",{ref,children:_jsx("div",{...p,children:_jsx("span",{className:infoMessage?.className,children:isFunction(infoMessage?.text)?infoMessage?.text():infoMessage?.text||defaultMessage})})})}export default PaypalPayment;
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext from"../../context/PaymentMethodContext";import isFunction from"lodash/isFunction";import{useContext,useEffect,useRef}from"react";const defaultMessage="by placing the order, you will be redirected to the PayPal website to sign in and authorize the payment";export function PaypalPayment({infoMessage,...p}){const ref=useRef(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext);useEffect(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&paymentSource?.approval_url&&(ref.current.onsubmit=async()=>await handleClick(),setPaymentRef({ref})),()=>{setPaymentRef({ref:{current:null}})}),[ref,paymentSource,currentPaymentMethodType]);const handleClick=async()=>{if(paymentSource&¤tPaymentMethodType)try{return await setPaymentSource({paymentSourceId:paymentSource.id,paymentResource:currentPaymentMethodType,attributes:{metadata:{card:{id:paymentSource.id,brand:"paypal",last4:""}}}}),!0}catch{return!1}return!1};return _jsx("form",{ref,children:_jsx("div",{...p,children:_jsx("span",{className:infoMessage?.className,children:isFunction(infoMessage?.text)?infoMessage?.text():infoMessage?.text||defaultMessage})})})}export default PaypalPayment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useState,useEffect}from"react";import ShipmentContext from"../../context/ShipmentContext";import ShipmentChildrenContext from"../../context/ShipmentChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import OrderContext from"../../context/OrderContext";export function Shipment({children,loader="Loading...",autoSelectSingleShippingMethod=!1}){const[loading,setLoading]=useState(!0),{shipments,deliveryLeadTimes,setShippingMethod}=useContext(ShipmentContext),{order}=useContext(OrderContext);useEffect(()=>(shipments!=null&&(autoSelectSingleShippingMethod?(async()=>{for(const shipment of shipments){const isSingle=shipment?.available_shipping_methods?.length===1;if(!shipment?.shipping_method&&isSingle){const[shippingMethod]=shipment?.available_shipping_methods||[];if(shippingMethod&&setShippingMethod!=null){const{success,order:order2}=await setShippingMethod(shipment.id,shippingMethod.id);typeof autoSelectSingleShippingMethod=="function"&&success&&autoSelectSingleShippingMethod(order2)}}else setTimeout(()=>{setLoading(!1)},200)}})():setLoading(!1)),()=>{setLoading(!0)}),[shipments!=null,shipments?.length,order?.gift_card_or_coupon_code]);const components=shipments?.map((shipment,k)=>{const lineItems=shipment.
|
|
1
|
+
import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useState,useEffect}from"react";import ShipmentContext from"../../context/ShipmentContext";import ShipmentChildrenContext from"../../context/ShipmentChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import OrderContext from"../../context/OrderContext";export function Shipment({children,loader="Loading...",autoSelectSingleShippingMethod=!1}){const[loading,setLoading]=useState(!0),{shipments,deliveryLeadTimes,setShippingMethod}=useContext(ShipmentContext),{order}=useContext(OrderContext);useEffect(()=>(shipments!=null&&(autoSelectSingleShippingMethod?(async()=>{for(const shipment of shipments){const isSingle=shipment?.available_shipping_methods?.length===1;if(!shipment?.shipping_method&&isSingle){const[shippingMethod]=shipment?.available_shipping_methods||[];if(shippingMethod&&setShippingMethod!=null){const{success,order:order2}=await setShippingMethod(shipment.id,shippingMethod.id);typeof autoSelectSingleShippingMethod=="function"&&success&&autoSelectSingleShippingMethod(order2)}}else setTimeout(()=>{setLoading(!1)},200)}})():setLoading(!1)),()=>{setLoading(!0)}),[shipments!=null,shipments?.length,order?.gift_card_or_coupon_code]);const components=shipments?.map((shipment,k)=>{const lineItems=shipment.stock_line_items?.map(shipmentLineItem=>{const l=shipmentLineItem.line_item;return l&&(l.quantity=shipmentLineItem.quantity),l}),shippingMethods=shipment.available_shipping_methods,currentShippingMethodId=autoSelectSingleShippingMethod&&shippingMethods&&shippingMethods.length===1?shippingMethods[0]?.id:shipment.shipping_method?.id,stockTransfers=shipment.stock_transfers,parcels=shipment.parcels,times=deliveryLeadTimes?.filter(time=>time.stock_location?.id===shipment.stock_location?.id),shipmentProps={parcels,lineItems,shippingMethods,currentShippingMethodId,stockTransfers,deliveryLeadTimes:times,shipment,keyNumber:k+1};return _jsx(ShipmentChildrenContext.Provider,{value:shipmentProps,children},k)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default Shipment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import ShipmentContext,{defaultShipmentContext}from"../../context/ShipmentContext";import{useContext,useEffect,useMemo,useReducer}from"react";import shipmentReducer,{shipmentInitialState,setShipmentErrors,getShipments,setShippingMethod}from"../../reducers/ShipmentReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import isEmpty from"lodash/isEmpty";export function ShipmentsContainer(props){const{children}=props,[state,dispatch]=useReducer(shipmentReducer,shipmentInitialState),{order,getOrder,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{include?.includes("shipments.available_shipping_methods")?includeLoaded?.["shipments.available_shipping_methods"]||addResourceToInclude({newResourceLoaded:{"shipments.available_shipping_methods":!0,"shipments.
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import ShipmentContext,{defaultShipmentContext}from"../../context/ShipmentContext";import{useContext,useEffect,useMemo,useReducer}from"react";import shipmentReducer,{shipmentInitialState,setShipmentErrors,getShipments,setShippingMethod}from"../../reducers/ShipmentReducer";import OrderContext from"../../context/OrderContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import isEmpty from"lodash/isEmpty";export function ShipmentsContainer(props){const{children}=props,[state,dispatch]=useReducer(shipmentReducer,shipmentInitialState),{order,getOrder,include,addResourceToInclude,includeLoaded}=useContext(OrderContext),config=useContext(CommerceLayerContext);useEffect(()=>{include?.includes("shipments.available_shipping_methods")?includeLoaded?.["shipments.available_shipping_methods"]||addResourceToInclude({newResourceLoaded:{"shipments.available_shipping_methods":!0,"shipments.stock_line_items.line_item":!0,"shipments.shipping_method":!0,"shipments.stock_transfers.line_item":!0,"shipments.stock_location":!0,"shipments.parcels.parcel_line_items":!0}}):addResourceToInclude({newResource:["shipments.available_shipping_methods","shipments.stock_line_items.line_item","shipments.shipping_method","shipments.stock_transfers.line_item","shipments.stock_location","shipments.parcels.parcel_line_items"]})},[include?.length,includeLoaded!=null]),useEffect(()=>{order!=null&&!isEmpty(config)&&order.shipments&&getShipments({order,dispatch,config})},[order!=null,order?.shipments?.length]),useEffect(()=>(order&&(order.shipments&&order.shipments.length>0&&order.shipments.map(shipment=>shipment.available_shipping_methods&&shipment.available_shipping_methods.length>0).includes(!1)&&setShipmentErrors([...state.errors||[],{code:"NO_SHIPPING_METHODS",message:"No shipping methods",resource:"shipments"}],dispatch),order.line_items&&order.line_items.length>0&&order.line_items.filter(({item_type:itemType})=>itemType==="skus").map(lineItem=>!!(lineItem.item?.do_not_ship||lineItem.item?.do_not_track||lineItem.item?.inventory?.quantity>=lineItem?.quantity)).includes(!1)&&setShipmentErrors([...state.errors||[],{code:"OUT_OF_STOCK",message:"No stock available",resource:"line_items"}],dispatch)),()=>{setShipmentErrors([],dispatch)}),[order?.shipments]);const contextValue=useMemo(()=>({...state,setShipmentErrors:errors=>defaultShipmentContext.setShipmentErrors(errors,dispatch),setShippingMethod:async(shipmentId,shippingMethodId)=>await setShippingMethod({shippingMethodId,shipmentId,config,getOrder,order})}),[state]);return _jsx(ShipmentContext.Provider,{value:contextValue,children})}export default ShipmentsContainer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useReducer,useEffect}from"react";import availabilityReducer,{availabilityInitialState,getAvailability}from"../../reducers/AvailabilityReducer";import AvailabilityContext from"../../context/AvailabilityContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import LineItemChildrenContext from"../../context/LineItemChildrenContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityContainer({children,skuCode,getQuantity}){const{lineItem}=useContext(LineItemChildrenContext),{sku}=useContext(SkuChildrenContext),{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=useReducer(availabilityReducer,availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{useContext,useReducer,useEffect,useMemo}from"react";import availabilityReducer,{availabilityInitialState,getAvailability}from"../../reducers/AvailabilityReducer";import AvailabilityContext from"../../context/AvailabilityContext";import CommerceLayerContext from"../../context/CommerceLayerContext";import LineItemChildrenContext from"../../context/LineItemChildrenContext";import SkuChildrenContext from"../../context/SkuChildrenContext";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityContainer({children,skuCode,getQuantity}){const{lineItem}=useContext(LineItemChildrenContext),{sku}=useContext(SkuChildrenContext),{accessToken,endpoint}=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"AvailabilityContainer",key:"accessToken"}),[state,dispatch]=useReducer(availabilityReducer,availabilityInitialState),sCode=skuCode||lineItem?.sku_code||sku?.code;useEffect(()=>(accessToken!=null&&accessToken!==""&&sCode&&getAvailability({skuCode:sCode,config:{accessToken,endpoint},dispatch}),()=>{dispatch({type:"setAvailability",payload:{}})}),[accessToken,sCode]),useEffect(()=>{getQuantity!=null&&state?.quantity!=null&&getQuantity(state?.quantity)},[state.quantity]);const memoized=useMemo(()=>({...state,parent:!0}),[state]);return _jsx(AvailabilityContext.Provider,{value:memoized,children})}export default AvailabilityContainer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import AvailabilityContext from"../../context/AvailabilityContext";import Parent from"../utils/Parent";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityTemplate(props){const{timeFormat,showShippingMethodName,showShippingMethodPrice,children,...p}=props,{min,max,shipping_method:shippingMethod,quantity}=useCustomContext({context:AvailabilityContext,contextComponentName:"AvailabilityContainer",currentComponentName:"AvailabilityTemplate",key:"parent"}),text=[],mn=min!=null&&timeFormat!=null?min?.[timeFormat]:"",mx=max!=null&&timeFormat!=null?max?.[timeFormat]:"",shippingMethodPrice=showShippingMethodPrice&&shippingMethod?.formatted_price_amount?`(${shippingMethod?.formatted_price_amount})`:"",name=showShippingMethodName&&shippingMethod?`with ${shippingMethod.name}`:"";quantity&&quantity>0?(text.push("Available"),mn&&mx&&timeFormat&&text.push(`in ${mn} - ${mx} ${timeFormat} ${name} ${shippingMethodPrice}`)):quantity===0&&text.push("Out of stock");const parentProps={min,max,shipping_method:shippingMethod,quantity,text:text.join(" "),...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import AvailabilityContext from"../../context/AvailabilityContext";import Parent from"../utils/Parent";import useCustomContext from"../../utils/hooks/useCustomContext";export function AvailabilityTemplate(props){const{timeFormat,showShippingMethodName,showShippingMethodPrice,children,...p}=props,{min,max,shipping_method:shippingMethod,quantity,skuCode}=useCustomContext({context:AvailabilityContext,contextComponentName:"AvailabilityContainer",currentComponentName:"AvailabilityTemplate",key:"parent"}),text=[],mn=min!=null&&timeFormat!=null?min?.[timeFormat]:"",mx=max!=null&&timeFormat!=null?max?.[timeFormat]:"",shippingMethodPrice=showShippingMethodPrice&&shippingMethod?.formatted_price_amount?`(${shippingMethod?.formatted_price_amount})`:"",name=showShippingMethodName&&shippingMethod?`with ${shippingMethod.name}`:"";quantity&&quantity>0?(text.push("Available"),mn&&mx&&timeFormat&&text.push(`in ${mn} - ${mx} ${timeFormat} ${name} ${shippingMethodPrice}`)):quantity===0&&text.push("Out of stock");const parentProps={min,max,shipping_method:shippingMethod,quantity,text:text.join(" "),...props};return children?_jsx(Parent,{...parentProps,children}):_jsx("span",{"data-testid":skuCode?`availability-${skuCode}`:"",...p,children:text.join(" ")})}export default AvailabilityTemplate;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { BaseInputComponentProps } from '../../typings/index';
|
|
3
3
|
export type BaseInputProps = BaseInputComponentProps & Omit<JSX.IntrinsicElements['input'], 'children'> & Omit<JSX.IntrinsicElements['textarea'], 'children'>;
|
|
4
|
-
declare const _default: React.ForwardRefExoticComponent<
|
|
4
|
+
declare const _default: React.ForwardRefExoticComponent<Omit<BaseInputProps, "ref"> & React.RefAttributes<any>>;
|
|
5
5
|
export default _default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context,...p}=props,resourceContext=useContext(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import Parent from"./Parent";import{useContext}from"react";import{defaultImgUrl}from"../../utils/placeholderImages";export default function GenericFieldComponent(props){const{children,tagElement,attribute,context,resource,...p}=props,resourceContext=useContext(context);let attributeValue="";const keysContext=Object.keys(resourceContext).filter(key=>key===resource);if(keysContext.length===1){const[keyResource]=keysContext;keyResource&&attribute&&(attributeValue=resourceContext[keyResource][attribute])}const Tag=tagElement||"span";if(Tag==="img"&&!children)return _jsx("img",{alt:"",src:attributeValue||defaultImgUrl,...p});const parentProps={attributeValue,tagElement,...p};return children?_jsx(Parent,{...parentProps,children}):_jsx(Tag,{"data-testid":attributeValue,...p,children:attributeValue},attributeValue)}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LineItem } from '@commercelayer/sdk';
|
|
2
2
|
import { BaseError } from '../../typings/errors';
|
|
3
3
|
import { TResourceError } from '../errors/Errors';
|
|
4
|
-
export
|
|
4
|
+
export interface AllErrorsParams {
|
|
5
5
|
allErrors: BaseError[];
|
|
6
6
|
messages: BaseError[];
|
|
7
7
|
field?: string;
|
|
@@ -9,9 +9,7 @@ export type AllErrorsParams = {
|
|
|
9
9
|
lineItem?: LineItem;
|
|
10
10
|
resource?: TResourceError;
|
|
11
11
|
returnHtml?: boolean;
|
|
12
|
-
};
|
|
13
|
-
export interface GetAllErrors {
|
|
14
|
-
<P extends AllErrorsParams>(params: P): Array<JSX.Element | string | undefined>;
|
|
15
12
|
}
|
|
13
|
+
export type GetAllErrors = <P extends AllErrorsParams>(params: P) => Array<JSX.Element | string | undefined>;
|
|
16
14
|
declare const getAllErrors: GetAllErrors;
|
|
17
15
|
export default getAllErrors;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import customMessages from"../../utils/customMessages";const getAllErrors=params=>{const{allErrors,messages,field,props,lineItem,resource,returnHtml=!0}=params;return allErrors.map((v,k)=>{const objMsg=customMessages(messages,v);let text=v?.title&&!v.detail?.includes(v.title)?`${v.title} - ${v.detail}`:`${v?.detail||v.message}`;if(objMsg?.message&&(text=objMsg?.message),field){if(v.resource==="line_items"&&lineItem&&v.id===lineItem.id)return returnHtml?_jsx("span",{...props,children:text},k):text;if(field===v.field&&resource===v.resource)return returnHtml?_jsx("span",{...props,children:text},k):text}if(resource===v.resource&&!field)return returnHtml?_jsx("span",{...props,children:text},k):text}).filter(v=>v!==void 0)};export default getAllErrors;
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import customMessages from"../../utils/customMessages";const getAllErrors=params=>{const{allErrors,messages,field,props,lineItem,resource,returnHtml=!0}=params;return allErrors.map((v,k)=>{const objMsg=customMessages(messages,v);let text=v?.title&&v?.detail!=null&&!v.detail?.includes(v.title)?`${v.title} - ${v.detail}`:`${v?.detail||v.message}`;if(objMsg?.message&&(text=objMsg?.message),field){if(v.resource==="line_items"&&lineItem&&v.id===lineItem.id)return returnHtml?_jsx("span",{...props,children:text},k):text;if(field===v.field&&resource===v.resource)return returnHtml?_jsx("span",{...props,children:text},k):text}if(resource===v.resource&&!field)return returnHtml?_jsx("span",{...props,children:text},k):text}).filter(v=>v!==void 0)};export default getAllErrors;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
2
|
import { OrderCodeType } from '../reducers/OrderReducer';
|
|
3
|
-
|
|
3
|
+
interface DefaultContext {
|
|
4
4
|
validation?: void;
|
|
5
5
|
setValue?: (name: string, value: string) => void;
|
|
6
6
|
codeType?: OrderCodeType;
|
|
7
|
-
}
|
|
7
|
+
}
|
|
8
8
|
declare const CouponAndGiftCardFormContext: import("react").Context<DefaultContext>;
|
|
9
9
|
export default CouponAndGiftCardFormContext;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
2
|
import { AddressCountrySelectName, AddressInputName } from '../typings/index';
|
|
3
3
|
import { AddressField } from '../reducers/AddressReducer';
|
|
4
|
-
export
|
|
4
|
+
export interface DefaultContextAddress {
|
|
5
5
|
validation?: void;
|
|
6
6
|
setValue?: (name: AddressField | AddressInputName | AddressCountrySelectName, value: any) => void;
|
|
7
7
|
errors?: {
|
|
@@ -15,6 +15,6 @@ export type DefaultContextAddress = {
|
|
|
15
15
|
requiresBillingInfo?: boolean;
|
|
16
16
|
resetField?: (name: string) => void;
|
|
17
17
|
values?: Record<string, any>;
|
|
18
|
-
}
|
|
18
|
+
}
|
|
19
19
|
declare const CustomerAddressFormContext: import("react").Context<DefaultContextAddress>;
|
|
20
20
|
export default CustomerAddressFormContext;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { SetCustomerErrors, deleteCustomerAddress, CustomerState,
|
|
2
|
+
import { SetCustomerErrors, deleteCustomerAddress, CustomerState, getCustomerPaymentSources, setCustomerEmail, TCustomerAddress, getCustomerAddresses } from '../reducers/CustomerReducer';
|
|
3
3
|
export type InitialCustomerContext = Partial<{
|
|
4
4
|
saveCustomerUser: (customerEmail: string) => Promise<void>;
|
|
5
5
|
setCustomerErrors: SetCustomerErrors;
|
|
6
6
|
setCustomerEmail: typeof setCustomerEmail;
|
|
7
7
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
8
|
-
deleteCustomerAddress: typeof deleteCustomerAddress
|
|
9
|
-
getCustomerAddresses:
|
|
8
|
+
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
9
|
+
getCustomerAddresses: typeof getCustomerAddresses;
|
|
10
10
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
11
11
|
} & CustomerState>;
|
|
12
12
|
export declare const defaultCustomerContext: {};
|
|
@@ -15,8 +15,8 @@ declare const CustomerContext: import("react").Context<Partial<{
|
|
|
15
15
|
setCustomerErrors: SetCustomerErrors;
|
|
16
16
|
setCustomerEmail: typeof setCustomerEmail;
|
|
17
17
|
getCustomerPaymentSources: typeof getCustomerPaymentSources;
|
|
18
|
-
deleteCustomerAddress: typeof deleteCustomerAddress
|
|
19
|
-
getCustomerAddresses:
|
|
18
|
+
deleteCustomerAddress: typeof deleteCustomerAddress;
|
|
19
|
+
getCustomerAddresses: typeof getCustomerAddresses;
|
|
20
20
|
createCustomerAddress: (address: TCustomerAddress) => Promise<void>;
|
|
21
21
|
} & Partial<import("../reducers/CustomerReducer").CustomerActionPayload>>>;
|
|
22
22
|
export default CustomerContext;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { IconBrand } from './PaymentSourceContext';
|
|
3
|
+
interface DefaultContext {
|
|
4
|
+
brand?: IconBrand | string;
|
|
5
|
+
exp_month?: number | string;
|
|
6
|
+
exp_year?: number | string;
|
|
7
|
+
last4?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare const defaultCustomerPaymentSourceContext: {};
|
|
10
|
+
declare const CustomerPaymentSourceContext: import("react").Context<DefaultContext>;
|
|
11
|
+
export default CustomerPaymentSourceContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createContext}from"react";export const defaultCustomerPaymentSourceContext={};const CustomerPaymentSourceContext=createContext(defaultCustomerPaymentSourceContext);export default CustomerPaymentSourceContext;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
2
|
export type IconBrand = 'visa' | 'credit-card' | 'amex' | 'mastercard' | 'jcb' | 'wire-transfer' | 'maestro' | 'cirrus' | 'paypal';
|
|
3
|
-
|
|
3
|
+
interface DefaultContext {
|
|
4
4
|
brand?: IconBrand | string;
|
|
5
5
|
exp_month?: number | string;
|
|
6
6
|
exp_year?: number | string;
|
|
@@ -8,7 +8,7 @@ type DefaultContext = {
|
|
|
8
8
|
showCard?: boolean;
|
|
9
9
|
readonly?: boolean;
|
|
10
10
|
handleEditClick?: (e: MouseEvent) => void;
|
|
11
|
-
}
|
|
11
|
+
}
|
|
12
12
|
export declare const defaultPaymentSourceContext: {};
|
|
13
13
|
declare const PaymentSourceContext: import("react").Context<DefaultContext>;
|
|
14
14
|
export default PaymentSourceContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,dispatch,config}){const sdk=getSdk(config);try{const[sku]=await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const availabilityInitialState={};export async function getAvailability({skuCode,dispatch,config}){const sdk=getSdk(config);try{const[sku]=await sdk.skus.list({fields:{skus:["id"]},filters:{code_in:skuCode}});if(sku){const skuInventory=await sdk.skus.retrieve(sku.id,{fields:{skus:["inventory"]}}),[level]=skuInventory.inventory?.levels||[],[delivery]=level?.delivery_lead_times||[];dispatch({type:"setAvailability",payload:{...delivery,quantity:skuInventory.inventory.quantity,skuCode}})}}catch(error){console.error("Get SKU availability",error)}}const typeAction=["setAvailability","setErrors"],availabilityReducer=(state,reducer)=>baseReducer(state,reducer,typeAction);export default availabilityReducer;
|
|
@@ -21,11 +21,11 @@ export type SetBillingAddress = (id: string, options?: {
|
|
|
21
21
|
customerAddressId?: string;
|
|
22
22
|
}) => Promise<void>;
|
|
23
23
|
export declare const setBillingAddress: SetBillingAddress;
|
|
24
|
-
|
|
24
|
+
interface SetBillingCustomerAddressIdParams {
|
|
25
25
|
dispatch: Dispatch<BillingAddressAction>;
|
|
26
26
|
order: Order;
|
|
27
27
|
setCloneAddress: (id: string, resource: AddressResource) => void;
|
|
28
|
-
}
|
|
29
|
-
export declare
|
|
28
|
+
}
|
|
29
|
+
export declare function setBillingCustomerAddressId({ dispatch, order, setCloneAddress }: SetBillingCustomerAddressIdParams): void;
|
|
30
30
|
declare const billingAddressReducer: (state: BillingAddressState, reducer: BillingAddressAction) => BillingAddressState;
|
|
31
31
|
export default billingAddressReducer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const billingAddressInitialState={_billing_address_clone_id:""},setBillingAddress=async(id,options)=>{try{if(options?.order){if(options.customerAddressId){const sdk=getSdk(options.config),attributes={id,reference:options.customerAddressId};await sdk.addresses.update(attributes)}options.dispatch({type:"setBillingAddress",payload:{_billing_address_clone_id:id}})}}catch(error){console.error("Set billing address",error)}}
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";export const billingAddressInitialState={_billing_address_clone_id:""},setBillingAddress=async(id,options)=>{try{if(options?.order){if(options.customerAddressId){const sdk=getSdk(options.config),attributes={id,reference:options.customerAddressId};await sdk.addresses.update(attributes)}options.dispatch({type:"setBillingAddress",payload:{_billing_address_clone_id:id}})}}catch(error){console.error("Set billing address",error)}};export function setBillingCustomerAddressId({dispatch,order,setCloneAddress}){const customerAddressId=order?.billing_address?.reference;try{customerAddressId&&(dispatch({type:"setBillingCustomerAddressId",payload:{billingCustomerAddressId:customerAddressId}}),setCloneAddress(customerAddressId,"billing_address"))}catch(error){console.error("error",error)}}const type=["setBillingAddress","setBillingCustomerAddressId","cleanup"],billingAddressReducer=(state,reducer)=>baseReducer(state,reducer,type);export default billingAddressReducer;
|
|
@@ -6,7 +6,7 @@ import { updateOrder } from './OrderReducer';
|
|
|
6
6
|
export type CustomerActionType = 'setErrors' | 'setCustomerEmail' | 'setAddresses' | 'setPayments' | 'setOrders';
|
|
7
7
|
export interface CustomerActionPayload {
|
|
8
8
|
addresses: Address[] | null;
|
|
9
|
-
payments: CustomerPaymentSource[];
|
|
9
|
+
payments: CustomerPaymentSource[] | null;
|
|
10
10
|
customerEmail: string;
|
|
11
11
|
errors: BaseError[];
|
|
12
12
|
orders: Order[];
|
|
@@ -93,7 +93,7 @@ export interface GetCustomerPaymentSources {
|
|
|
93
93
|
order?: Order;
|
|
94
94
|
}
|
|
95
95
|
export declare function getCustomerPaymentSources(params?: GetCustomerPaymentSources): void;
|
|
96
|
-
|
|
96
|
+
interface GetCustomerOrdersProps {
|
|
97
97
|
/**
|
|
98
98
|
* The Commerce Layer config
|
|
99
99
|
*/
|
|
@@ -102,8 +102,8 @@ export type GetCustomerOrders = (params: {
|
|
|
102
102
|
* The Customer dispatch function
|
|
103
103
|
*/
|
|
104
104
|
dispatch: Dispatch<CustomerAction>;
|
|
105
|
-
}
|
|
106
|
-
export declare
|
|
105
|
+
}
|
|
106
|
+
export declare function getCustomerOrders({ config, dispatch }: GetCustomerOrdersProps): Promise<void>;
|
|
107
107
|
export type TCustomerAddress = AddressCreate & AddressUpdate;
|
|
108
108
|
interface TCreateCustomerAddress {
|
|
109
109
|
/**
|
|
@@ -124,6 +124,9 @@ interface TCreateCustomerAddress {
|
|
|
124
124
|
state?: CustomerState;
|
|
125
125
|
}
|
|
126
126
|
export declare function createCustomerAddress({ address, config, dispatch, state }: TCreateCustomerAddress): Promise<void>;
|
|
127
|
+
interface GetCustomerPaymentsParams extends GetCustomerOrdersProps {
|
|
128
|
+
}
|
|
129
|
+
export declare function getCustomerPayments({ config, dispatch }: GetCustomerPaymentsParams): Promise<void>;
|
|
127
130
|
export declare const customerInitialState: CustomerState;
|
|
128
131
|
declare const customerReducer: (state: CustomerState, reducer: CustomerAction) => CustomerState;
|
|
129
132
|
export default customerReducer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&addresses.push(customerAddress.address)}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors(error,"addresses");dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";import jwtDecode from"../utils/jwt";export async function saveCustomerUser({customerEmail,order,updateOrder}){if(order){const attributes={customer_email:customerEmail,id:order.id};await updateOrder({id:order.id,attributes})}}export function setCustomerErrors(errors,dispatch){dispatch&&dispatch({type:"setErrors",payload:{errors}})}export function setCustomerEmail(customerEmail,dispatch){dispatch&&dispatch({type:"setCustomerEmail",payload:{customerEmail}})}export async function getCustomerAddresses({config,dispatch}){try{const addresses=[];(await getSdk(config).customer_addresses.list({include:["address"]})).forEach(customerAddress=>{customerAddress.address&&addresses.push(customerAddress.address)}),addresses.sort((a,b)=>a.full_name&&b.full_name?a.full_name.localeCompare(b.full_name):0),dispatch({type:"setAddresses",payload:{addresses}})}catch(error){const errors=getErrors({error,resource:"addresses"});dispatch({type:"setErrors",payload:{errors}})}}export async function deleteCustomerAddress({config,dispatch,customerAddressId,addresses}){if(config&&addresses&&dispatch&&config)try{await getSdk(config).customer_addresses.delete(customerAddressId);const newAddresses=addresses.filter(({reference})=>reference!==customerAddressId);dispatch({type:"setAddresses",payload:{addresses:newAddresses}})}catch{throw new Error("Couldn't delete address")}}export function getCustomerPaymentSources(params){if(params){const{order,dispatch}=params;order?.available_customer_payment_sources&&dispatch&&dispatch({type:"setPayments",payload:{payments:order.available_customer_payment_sources}})}}export async function getCustomerOrders({config,dispatch}){if(config.accessToken){const{owner}=jwtDecode(config.accessToken);if(owner?.id){const customers=await getSdk(config).customers.retrieve(owner.id,{include:["orders"]}),orders=customers.orders?.filter(order=>order.status!=="pending"&&order.status!=="draft");dispatch({type:"setOrders",payload:{orders,customers}})}}}export async function createCustomerAddress({address,config,dispatch,state}){if(config&&address){const sdk=getSdk(config),{id}=address;try{if(id){const upAddress=await sdk.addresses.update(address),updatedAddresses=state?.addresses?.map(a=>a.id===upAddress.id?upAddress:a);dispatch&&dispatch({type:"setAddresses",payload:{addresses:updatedAddresses}})}else{const newAddress=await sdk.addresses.create(address);if(state?.customers?.id&&newAddress?.id){const newCustomerAddress=await sdk.customer_addresses.create({customer:sdk.customers.relationship(state?.customers?.id),address:sdk.addresses.relationship(newAddress.id)});await sdk.addresses.update({id:newAddress.id,reference:newCustomerAddress.id}),dispatch&&state?.addresses&&(newAddress.reference=newCustomerAddress.id,dispatch({type:"setAddresses",payload:{addresses:[...state.addresses,newAddress]}}))}}}catch{throw new Error("Couldn't create customer address")}}}export async function getCustomerPayments({config,dispatch}){if(config!=null&&dispatch!=null){const payments=await getSdk(config).customer_payment_sources.list({include:["payment_source"]});dispatch({type:"setPayments",payload:{payments}})}}export const customerInitialState={errors:[],addresses:null,payments:null};const type=["setErrors","setCustomerEmail","setAddresses","setPayments","setOrders"],customerReducer=(state,reducer)=>baseReducer(state,reducer,type);export default customerReducer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";export const giftCardInitialState={currencyCode:"",balanceCent:0,singleUse:!1,rechargeable:!0,loading:!1,expiresAt:null,errors:[]};export async function addGiftCardRecipient(values,config,dispatch){try{const recipient=await getSdk(config).gift_card_recipients.create(values);dispatch({type:"setGiftCardRecipient",payload:{giftCardRecipient:recipient}})}catch(error){console.error(error)}}export const addGiftCardLoading=(loading,dispatch)=>{dispatch({type:"setGiftCardLoading",payload:{loading}})};export async function addGiftCard(values,{config,dispatch,getOrder,createOrder,order}){try{const sdk=getSdk(config);addGiftCardLoading(!0,dispatch);const{firstName,lastName,email,...val}=values,giftCardValue={recipient_email:email,...val},giftCard=await sdk.gift_cards.create(giftCardValue,{include:["gift_card_recipient"]}),recipientValues={id:giftCard.gift_card_recipient?.id};if(firstName&&(recipientValues.first_name=firstName),lastName&&(recipientValues.last_name=lastName),isEmpty(recipientValues)||await sdk.gift_card_recipients.update(recipientValues),createOrder&&getOrder){const id=order?order.id:await createOrder();if(id){const order2=sdk.orders.relationship(id),item=sdk.gift_cards.relationship(giftCard.id);await sdk.line_items.create({quantity:1,order:order2,item}),await getOrder(id)}}dispatch({type:"setGiftCardRecipient",payload:{...giftCardValue}}),addGiftCardLoading(!1,dispatch)}catch(error){const errors=getErrors(error,"gift_cards");dispatch({type:"setGiftCardErrors",payload:{errors}}),addGiftCardLoading(!1,dispatch)}}export const addGiftCardError=(errors,dispatch)=>{dispatch({type:"setGiftCardErrors",payload:{errors}})};const type=["setAvailability","setGiftCardRecipient","setGiftCardErrors","setGiftCardLoading"],giftCardReducer=(state,reducer)=>baseReducer(state,reducer,type);export default giftCardReducer;
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import isEmpty from"lodash/isEmpty";import getErrors from"../utils/getErrors";import getSdk from"../utils/getSdk";export const giftCardInitialState={currencyCode:"",balanceCent:0,singleUse:!1,rechargeable:!0,loading:!1,expiresAt:null,errors:[]};export async function addGiftCardRecipient(values,config,dispatch){try{const recipient=await getSdk(config).gift_card_recipients.create(values);dispatch({type:"setGiftCardRecipient",payload:{giftCardRecipient:recipient}})}catch(error){console.error(error)}}export const addGiftCardLoading=(loading,dispatch)=>{dispatch({type:"setGiftCardLoading",payload:{loading}})};export async function addGiftCard(values,{config,dispatch,getOrder,createOrder,order}){try{const sdk=getSdk(config);addGiftCardLoading(!0,dispatch);const{firstName,lastName,email,...val}=values,giftCardValue={recipient_email:email,...val},giftCard=await sdk.gift_cards.create(giftCardValue,{include:["gift_card_recipient"]}),recipientValues={id:giftCard.gift_card_recipient?.id};if(firstName&&(recipientValues.first_name=firstName),lastName&&(recipientValues.last_name=lastName),isEmpty(recipientValues)||await sdk.gift_card_recipients.update(recipientValues),createOrder&&getOrder){const id=order?order.id:await createOrder();if(id){const order2=sdk.orders.relationship(id),item=sdk.gift_cards.relationship(giftCard.id);await sdk.line_items.create({quantity:1,order:order2,item}),await getOrder(id)}}dispatch({type:"setGiftCardRecipient",payload:{...giftCardValue}}),addGiftCardLoading(!1,dispatch)}catch(error){const errors=getErrors({error,resource:"gift_cards"});dispatch({type:"setGiftCardErrors",payload:{errors}}),addGiftCardLoading(!1,dispatch)}}export const addGiftCardError=(errors,dispatch)=>{dispatch({type:"setGiftCardErrors",payload:{errors}})};const type=["setAvailability","setGiftCardRecipient","setGiftCardErrors","setGiftCardLoading"],giftCardReducer=(state,reducer)=>baseReducer(state,reducer,type);export default giftCardReducer;
|
|
@@ -30,15 +30,15 @@ export interface LineItemPayload {
|
|
|
30
30
|
errors?: BaseError[];
|
|
31
31
|
}
|
|
32
32
|
export interface LineItemState extends LineItemPayload {
|
|
33
|
-
updateLineItem?: (lineItemId: string, quantity?: number) => void
|
|
34
|
-
deleteLineItem?: (lineItemId: string) => void
|
|
33
|
+
updateLineItem?: (lineItemId: string, quantity?: number) => Promise<void>;
|
|
34
|
+
deleteLineItem?: (lineItemId: string) => Promise<void>;
|
|
35
35
|
}
|
|
36
36
|
export interface LineItemAction {
|
|
37
37
|
type: LineItemActionType;
|
|
38
38
|
payload: LineItemPayload;
|
|
39
39
|
}
|
|
40
40
|
export declare const getLineItems: GetLineItems;
|
|
41
|
-
export declare
|
|
41
|
+
export declare function updateLineItem(params: UpdateLineItemParams): Promise<void>;
|
|
42
42
|
export declare const deleteLineItem: DeleteLineItem;
|
|
43
43
|
export declare const lineItemInitialState: LineItemState;
|
|
44
44
|
export type LineItemActionType = 'setLineItems' | 'setErrors' | 'setLoading';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";export const getLineItems=params=>{const{order,dispatch,config}=params,sdk=getSdk(config);let allLineItems=[];order&&sdk.orders.retrieve(order?.id,{include:["line_items","line_items.line_item_options.sku_option"],fields:{orders:["line_items"]}}).then(response=>{dispatch({type:"setLoading",payload:{loading:!1}});const items=response.line_items||[];allLineItems=[...allLineItems,...items],dispatch({type:"setLineItems",payload:{lineItems:allLineItems}})}).catch(error=>{const errors=getErrors(error,"line_items");dispatch({type:"setErrors",payload:{errors}})})}
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";export const getLineItems=params=>{const{order,dispatch,config}=params,sdk=getSdk(config);let allLineItems=[];order&&sdk.orders.retrieve(order?.id,{include:["line_items","line_items.line_item_options.sku_option"],fields:{orders:["line_items"]}}).then(response=>{dispatch({type:"setLoading",payload:{loading:!1}});const items=response.line_items||[];allLineItems=[...allLineItems,...items],dispatch({type:"setLineItems",payload:{lineItems:allLineItems}})}).catch(error=>{const errors=getErrors({error,resource:"line_items"});dispatch({type:"setErrors",payload:{errors}})})};export async function updateLineItem(params){const{config,lineItemId,quantity,getOrder,orderId,dispatch}=params,sdk=getSdk(config);try{await sdk.line_items.update({id:lineItemId,quantity}),getOrder&&await getOrder(orderId),dispatch({type:"setErrors",payload:{errors:[]}})}catch(error){const errors=getErrors({error,resource:"line_items",attributes:{id:lineItemId}});dispatch({type:"setErrors",payload:{errors}})}}export const deleteLineItem=async params=>{const{config,lineItemId,getOrder,orderId,dispatch}=params,sdk=getSdk(config);try{await sdk.line_items.delete(lineItemId),getOrder&&await getOrder(orderId),dispatch({type:"setErrors",payload:{errors:[]}})}catch(error){const errors=getErrors({error,resource:"line_items"});dispatch({type:"setErrors",payload:{errors}})}},lineItemInitialState={loading:!1,errors:[]};const actionType=["setLineItems","setErrors","setLoading"],lineItemReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default lineItemReducer;
|
|
@@ -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' | 'shipments.available_shipping_methods' | 'shipments.stock_transfers' | 'shipments.stock_transfers.line_item' | 'shipments.
|
|
29
|
+
export type ResourceIncluded = 'billing_address' | 'shipping_address' | 'line_items.line_item_options.sku_option' | 'line_items.item' | 'available_customer_payment_sources.payment_source' | '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;
|
|
@@ -83,6 +83,7 @@ export interface LineItemOption {
|
|
|
83
83
|
export interface CustomLineItem {
|
|
84
84
|
name?: string;
|
|
85
85
|
imageUrl?: string | null;
|
|
86
|
+
metadata?: Record<string, string>;
|
|
86
87
|
}
|
|
87
88
|
export type AddToCartParams = Partial<{
|
|
88
89
|
bundleCode: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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 getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{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,"orders");console.error("Create order",errors),dispatch&&setErrors({currentErrors:state?.errors,newErrors:errors,dispatch})}}return""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{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,"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=getSdk(config);try{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,"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}=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;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:!0,bundle_code:bundleCode},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){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}return{success:!0,orderId:id}}}return{success:!1}}catch(error){const errors2=getErrors(error,"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,"orders",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,"orders",codeType);return console.error("Remove gift card o coupon code",errors),dispatch&&setOrderErrors({errors,dispatch}),{success:!1}}}export const orderInitialState={loading:!0,orderId:"",order:void 0,errors:[],include:void 0,withoutIncludes:!0};const orderReducer=(state,reducer)=>baseReducer(state,reducer,actionType);export default orderReducer;
|
|
1
|
+
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 getOrganizationSlug from"../utils/organization";const actionType=["setLoading","setOrderId","setOrder","setSingleQuantity","setCurrentSkuCodes","setCurrentSkuPrices","setErrors","setCurrentItem","setSaveAddressToCustomerAddressBook","setIncludesResource"];export const createOrder=async params=>{if(params){const{persistKey,state,dispatch,config,orderMetadata:metadata,orderAttributes={},setLocalOrder}=params;if(state?.orderId)return state.orderId;const sdk=getSdk(config);try{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""},getApiOrder=async params=>{const{id,dispatch,config,clearWhenPlaced,persistKey,deleteLocalOrder,state}=params,sdk=getSdk(config);try{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=getSdk(config);try{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}=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;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:!0,bundle_code:bundleCode,metadata},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){const{organization}=getOrganizationSlug(config.endpoint??""),params2=`${id}?accessToken=${config.accessToken??""}`,redirectUrl=checkoutUrl?`${checkoutUrl}/${params2}`:`https://${organization}.checkout.commercelayer.app/${params2}`;location.href=redirectUrl}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;
|
|
@@ -5,7 +5,7 @@ import { StripeConfig } from '../components/payment_source/StripePayment';
|
|
|
5
5
|
import { WireTransferConfig } from '../components/payment_source/WireTransferPayment';
|
|
6
6
|
import { CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
7
7
|
import { getOrderContext, updateOrder } from './OrderReducer';
|
|
8
|
-
import { BaseError } from '../typings/errors';
|
|
8
|
+
import type { BaseError } from '../typings/errors';
|
|
9
9
|
import { Order, PaymentMethod, StripePayment, WireTransfer, AdyenPayment, BraintreePayment, CheckoutComPayment, ExternalPayment, PaypalPayment, KlarnaPayment } from '@commercelayer/sdk';
|
|
10
10
|
import { Dispatch, MutableRefObject } from 'react';
|
|
11
11
|
import { CheckoutComConfig } from '../components/payment_source/CheckoutComPayment';
|