@commercelayer/react-components 4.3.5 → 4.3.6
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/in_stock_subscriptions/InStockSubscriptionButton.d.ts +35 -0
- package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionButton.js +1 -0
- package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionsContainer.d.ts +9 -0
- package/lib/cjs/components/in_stock_subscriptions/InStockSubscriptionsContainer.js +1 -0
- package/lib/cjs/components/payment_gateways/WireTransferGateway.d.ts +1 -1
- package/lib/cjs/components/payment_gateways/WireTransferGateway.js +1 -1
- package/lib/cjs/components/payment_source/StripeExpressPayment.d.ts +5 -0
- package/lib/cjs/components/payment_source/StripeExpressPayment.js +1 -0
- package/lib/cjs/components/payment_source/WireTransferPayment.js +1 -1
- package/lib/cjs/context/InStockSubscriptionContext.d.ts +7 -0
- package/lib/cjs/context/InStockSubscriptionContext.js +1 -0
- package/lib/cjs/reducers/InStockSubscriptionReducer.d.ts +33 -0
- package/lib/cjs/reducers/InStockSubscriptionReducer.js +1 -0
- package/lib/cjs/utils/expressPaymentHelper.d.ts +92 -0
- package/lib/cjs/utils/expressPaymentHelper.js +1 -0
- package/lib/cjs/utils/getAvailableExpressPayments.d.ts +2 -0
- package/lib/cjs/utils/getAvailableExpressPayments.js +1 -0
- package/lib/cjs/utils/getDomain.d.ts +4 -0
- package/lib/cjs/utils/getDomain.js +1 -0
- package/lib/cjs/utils/isEmpty.d.ts +1 -0
- package/lib/cjs/utils/isEmpty.js +1 -0
- package/lib/esm/components/in_stock_subscriptions/InStockSubscriptionButton.d.ts +35 -0
- package/lib/esm/components/in_stock_subscriptions/InStockSubscriptionButton.js +1 -0
- package/lib/esm/components/in_stock_subscriptions/InStockSubscriptionsContainer.d.ts +9 -0
- package/lib/esm/components/in_stock_subscriptions/InStockSubscriptionsContainer.js +1 -0
- package/lib/esm/components/payment_gateways/WireTransferGateway.d.ts +1 -1
- package/lib/esm/components/payment_gateways/WireTransferGateway.js +1 -1
- package/lib/esm/components/payment_source/StripeExpressPayment.d.ts +5 -0
- package/lib/esm/components/payment_source/StripeExpressPayment.js +1 -0
- package/lib/esm/components/payment_source/WireTransferPayment.js +1 -1
- package/lib/esm/context/InStockSubscriptionContext.d.ts +7 -0
- package/lib/esm/context/InStockSubscriptionContext.js +1 -0
- package/lib/esm/reducers/InStockSubscriptionReducer.d.ts +33 -0
- package/lib/esm/reducers/InStockSubscriptionReducer.js +1 -0
- package/lib/esm/utils/expressPaymentHelper.d.ts +92 -0
- package/lib/esm/utils/expressPaymentHelper.js +1 -0
- package/lib/esm/utils/getAvailableExpressPayments.d.ts +2 -0
- package/lib/esm/utils/getAvailableExpressPayments.js +1 -0
- package/lib/esm/utils/getDomain.d.ts +4 -0
- package/lib/esm/utils/getDomain.js +1 -0
- package/lib/esm/utils/isEmpty.d.ts +1 -0
- package/lib/esm/utils/isEmpty.js +1 -0
- package/lib/tsconfig.prod.esm.tsbuildinfo +1 -1
- package/lib/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ChildrenFunction } from '../../typings/index';
|
|
2
|
+
interface Props extends Omit<JSX.IntrinsicElements['button'], 'children' | 'onClick'> {
|
|
3
|
+
/**
|
|
4
|
+
* The code of the sku.
|
|
5
|
+
*/
|
|
6
|
+
skuCode: string;
|
|
7
|
+
/**
|
|
8
|
+
* The label to display.
|
|
9
|
+
*/
|
|
10
|
+
label?: string | JSX.Element;
|
|
11
|
+
/**
|
|
12
|
+
* The label to display when the button is loading.
|
|
13
|
+
*/
|
|
14
|
+
loadingLabel?: string | JSX.Element;
|
|
15
|
+
/**
|
|
16
|
+
* The email of the customer.
|
|
17
|
+
*/
|
|
18
|
+
customerEmail?: string;
|
|
19
|
+
/**
|
|
20
|
+
* The children of the component.
|
|
21
|
+
*/
|
|
22
|
+
children?: ChildrenFunction<Omit<Props, 'children'>>;
|
|
23
|
+
/**
|
|
24
|
+
* Show the button.
|
|
25
|
+
*/
|
|
26
|
+
show?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The callback function to call when the button is clicked.
|
|
29
|
+
*/
|
|
30
|
+
onClick?: (response: {
|
|
31
|
+
success: boolean;
|
|
32
|
+
}) => void;
|
|
33
|
+
}
|
|
34
|
+
export declare function InStockSubscriptionButton({ skuCode, customerEmail, children, onClick, show, label, loadingLabel, ...props }: Props): JSX.Element | null;
|
|
35
|
+
export default InStockSubscriptionButton;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InStockSubscriptionButton=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),InStockSubscriptionContext_1=tslib_1.__importDefault(require("../../context/InStockSubscriptionContext")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),jwt_1=tslib_1.__importDefault(require("../../utils/jwt")),react_1=require("react");function InStockSubscriptionButton(_a){var{skuCode,customerEmail,children,onClick,show=!1,label="Subscribe",loadingLabel="Loading..."}=_a,props=tslib_1.__rest(_a,["skuCode","customerEmail","children","onClick","show","label","loadingLabel"]);const{setInStockSubscription}=(0,useCustomContext_1.default)({context:InStockSubscriptionContext_1.default,contextComponentName:"InStockSubscriptionsContainer",currentComponentName:"InStockSubscriptionButton",key:"setInStockSubscription"}),{accessToken}=(0,react_1.useContext)(CommerceLayerContext_1.default),[loading,setLoading]=(0,react_1.useState)(!1),handleClick=()=>tslib_1.__awaiter(this,void 0,void 0,function*(){if(accessToken!=null&&customerEmail==null){const get=(0,jwt_1.default)(accessToken);if(get?.owner==null){console.error("Missing customerEmail");return}}if(setInStockSubscription==null){console.error("Missing <InStockSubscriptionsContainer>");return}setLoading(!0);const res=yield setInStockSubscription({customerEmail,skuCode});onClick?.(res),setLoading(!1)});if(children!=null){const parentProps=Object.assign({skuCode,customerEmail,onClick,show,label,loadingLabel},props);return(0,jsx_runtime_1.jsx)(Parent_1.default,Object.assign({},parentProps,{children}))}return show?(0,jsx_runtime_1.jsx)("button",Object.assign({onClick:()=>{handleClick()},disabled:loading},props,{children:loading?loadingLabel:label})):null}exports.InStockSubscriptionButton=InStockSubscriptionButton,exports.default=InStockSubscriptionButton;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type DefaultChildrenType } from '../../typings/globals';
|
|
2
|
+
interface Props {
|
|
3
|
+
/**
|
|
4
|
+
* The children of the component.
|
|
5
|
+
*/
|
|
6
|
+
children: DefaultChildrenType;
|
|
7
|
+
}
|
|
8
|
+
export declare function InStockSubscriptionsContainer({ children }: Props): JSX.Element | null;
|
|
9
|
+
export default InStockSubscriptionsContainer;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InStockSubscriptionsContainer=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),InStockSubscriptionContext_1=tslib_1.__importDefault(require("../../context/InStockSubscriptionContext")),InStockSubscriptionReducer_1=tslib_1.__importStar(require("../../reducers/InStockSubscriptionReducer")),useCustomContext_1=tslib_1.__importDefault(require("../../utils/hooks/useCustomContext")),react_1=require("react");function InStockSubscriptionsContainer({children}){const config=(0,useCustomContext_1.default)({context:CommerceLayerContext_1.default,contextComponentName:"CommerceLayer",currentComponentName:"InStockSubscriptionsContainer",key:"accessToken"}),[state,dispatch]=(0,react_1.useReducer)(InStockSubscriptionReducer_1.default,InStockSubscriptionReducer_1.inStockSubscriptionInitialState),value=Object.assign(Object.assign({},state),{setInStockSubscription:({customerEmail,skuCode})=>tslib_1.__awaiter(this,void 0,void 0,function*(){return yield(0,InStockSubscriptionReducer_1.setInStockSubscription)({customerEmail,skuCode,config,dispatch})})});return(0,jsx_runtime_1.jsx)(InStockSubscriptionContext_1.default.Provider,Object.assign({value},{children}))}exports.InStockSubscriptionsContainer=InStockSubscriptionsContainer,exports.default=InStockSubscriptionsContainer;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GatewayBaseType } from '../payment_gateways/PaymentGateway';
|
|
1
|
+
import { type GatewayBaseType } from '../payment_gateways/PaymentGateway';
|
|
2
2
|
type Props = GatewayBaseType;
|
|
3
3
|
export declare function WireTransferGateway(props: Props): JSX.Element | null;
|
|
4
4
|
export default WireTransferGateway;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WireTransferGateway=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),WireTransferPayment_1=tslib_1.__importDefault(require("../payment_source/WireTransferPayment")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),PaymentMethodReducer_1=require("../../reducers/PaymentMethodReducer"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=require("react");function WireTransferGateway(props){const{readonly,showCard,handleEditClick,children,...p}=props,{payment}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{currentPaymentMethodId,config,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource="wire_transfers";if(!readonly&&payment?.id!==currentPaymentMethodId)return null;if(readonly||showCard){const card=paymentSource?.options?.card||paymentSource?.metadata?.card,value={...card,showCard,handleEditClick,readonly};return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}const wireTransferConfig=config&&paymentResource?(0,PaymentMethodReducer_1.getPaymentConfig)(paymentResource,config):{};return(0,jsx_runtime_1.jsx)(WireTransferPayment_1.default,{...p,...wireTransferConfig})}exports.WireTransferGateway=WireTransferGateway,exports.default=WireTransferGateway;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WireTransferGateway=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),WireTransferPayment_1=tslib_1.__importDefault(require("../payment_source/WireTransferPayment")),PaymentMethodChildrenContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodChildrenContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),PaymentSourceContext_1=tslib_1.__importDefault(require("../../context/PaymentSourceContext")),PaymentMethodReducer_1=require("../../reducers/PaymentMethodReducer"),isEmpty_1=tslib_1.__importDefault(require("lodash/isEmpty")),react_1=require("react");function WireTransferGateway(props){const{readonly,showCard,handleEditClick,children,...p}=props,{payment}=(0,react_1.useContext)(PaymentMethodChildrenContext_1.default),{currentPaymentMethodId,config,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default),paymentResource="wire_transfers";if(!readonly&&payment?.id!==currentPaymentMethodId)return null;if(readonly||showCard){const card=paymentSource?.options?.card||paymentSource?.metadata?.card,value={...card,showCard,handleEditClick,readonly};return(0,isEmpty_1.default)(card)?null:(0,jsx_runtime_1.jsx)(PaymentSourceContext_1.default.Provider,{value,children})}const wireTransferConfig=config&&paymentResource?(0,PaymentMethodReducer_1.getPaymentConfig)(paymentResource,config):{};return(0,jsx_runtime_1.jsx)(WireTransferPayment_1.default,{...p,...wireTransferConfig?.wireTransfer})}exports.WireTransferGateway=WireTransferGateway,exports.default=WireTransferGateway;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StripeExpressPayment=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),expressPaymentHelper_1=require("../../utils/expressPaymentHelper"),isEmpty_1=require("../../utils/isEmpty"),react_stripe_js_1=require("@stripe/react-stripe-js"),react_1=require("react");function StripeExpressPayment({clientSecret}){const stripe=(0,react_stripe_js_1.useStripe)(),[paymentRequest,setPaymentRequest]=(0,react_1.useState)(null),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default),{order}=(0,react_1.useContext)(OrderContext_1.default),{paymentMethods,paymentSource}=(0,react_1.useContext)(PaymentMethodContext_1.default);return(0,react_1.useEffect)(()=>{var _a,_b,_c,_d,_e;if(stripe==null||order==null)return;const pr=stripe.paymentRequest({country:(_a=order?.country_code)!==null&&_a!==void 0?_a:"US",currency:(_c=(_b=order?.currency_code)===null||_b===void 0?void 0:_b.toLowerCase())!==null&&_c!==void 0?_c:"",total:{label:`#${(_d=order?.number)!==null&&_d!==void 0?_d:""}`,amount:(_e=order?.total_amount_with_taxes_cents)!==null&&_e!==void 0?_e:0},requestPayerName:!0,requestPayerEmail:!0,requestPayerPhone:!0,requestShipping:!0});pr.canMakePayment().then(result=>{console.log("available payment:",result),result&&setPaymentRequest(pr)}).catch(err=>{console.error("Can make payment:",err)})},[(0,isEmpty_1.isEmpty)(stripe),(0,isEmpty_1.isEmpty)(order)]),paymentRequest!=null&&stripe!=null?(paymentRequest.on("shippingaddresschange",ev=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g;if(order!=null&&accessToken!=null&&endpoint!=null){const requiresBillingInfo=(_a=order?.requires_billing_info)!==null&&_a!==void 0?_a:!1,orderWithShipments=yield(0,expressPaymentHelper_1.setExpressFakeAddress)({orderId:order.id,config:{accessToken,endpoint},address:{first_name:"Fake name",last_name:"Fake lastname",country_code:(_b=ev.shippingAddress.country)!==null&&_b!==void 0?_b:"",line_1:"Fake street 123",city:(_c=ev.shippingAddress.city)!==null&&_c!==void 0?_c:"Fake city",zip_code:(_d=ev.shippingAddress.postalCode)!==null&&_d!==void 0?_d:"12345",state_code:(_e=ev.shippingAddress.region)!==null&&_e!==void 0?_e:"Fake state",phone:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0}}),shippingOptions=(0,expressPaymentHelper_1.getExpressShippingMethods)(orderWithShipments);shippingOptions!=null&&!(0,isEmpty_1.isEmpty)(shippingOptions)?ev.updateWith({status:"success",shippingOptions,total:{label:`#${(_f=orderWithShipments?.number)!==null&&_f!==void 0?_f:""}`,amount:(_g=orderWithShipments?.total_amount_with_taxes_cents)!==null&&_g!==void 0?_g:0}}):ev.updateWith({status:"invalid_shipping_address"})}else ev.updateWith({status:"fail"})})),paymentRequest.on("shippingoptionchange",ev=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _h,_j;if(order!=null&&accessToken!=null&&endpoint!=null){const updatedOrder=yield(0,expressPaymentHelper_1.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:`#${(_h=updatedOrder?.number)!==null&&_h!==void 0?_h:""}`,amount:(_j=updatedOrder?.total_amount_with_taxes_cents)!==null&&_j!==void 0?_j:0}})}else ev.updateWith({status:"fail"})})),paymentRequest.on("paymentmethod",ev=>tslib_1.__awaiter(this,void 0,void 0,function*(){var _k,_l,_m,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_0;if(order?.id==null)throw new Error("Order is null");if(paymentMethods==null)throw new Error("Payment methods are null");const[paymentMethod]=(0,expressPaymentHelper_1.getAvailableExpressPayments)(paymentMethods);if(paymentMethod==null)throw new Error("Payment method is null");if(paymentSource==null)throw new Error("Payment source is null");const requiresBillingInfo=(_k=order?.requires_billing_info)!==null&&_k!==void 0?_k:!1,paymentResource=paymentMethod?.payment_source_type;if(accessToken!=null&&endpoint!=null){const[firstName,lastName]=(_m=(_l=ev.payerName)===null||_l===void 0?void 0:_l.split(" "))!==null&&_m!==void 0?_m:[],[line]=(_p=(_o=ev.shippingAddress)===null||_o===void 0?void 0:_o.addressLine)!==null&&_p!==void 0?_p:"",email=(_q=ev.payerEmail)!==null&&_q!==void 0?_q:"";yield(0,expressPaymentHelper_1.setExpressFakeAddress)({orderId:order.id,config:{accessToken,endpoint},address:{first_name:firstName??"Fake name",last_name:lastName??"Fake lastname",country_code:(_s=(_r=ev?.shippingAddress)===null||_r===void 0?void 0:_r.country)!==null&&_s!==void 0?_s:"",line_1:line??"Fake street 123",city:(_u=(_t=ev?.shippingAddress)===null||_t===void 0?void 0:_t.city)!==null&&_u!==void 0?_u:"Fake city",zip_code:(_w=(_v=ev?.shippingAddress)===null||_v===void 0?void 0:_v.postalCode)!==null&&_w!==void 0?_w:"12345",state_code:(_y=(_x=ev?.shippingAddress)===null||_x===void 0?void 0:_x.region)!==null&&_y!==void 0?_y:"Fake state",phone:(_z=ev?.payerPhone)!==null&&_z!==void 0?_z:"1234567890",billing_info:requiresBillingInfo?"Fake billing info":void 0},email}),yield(0,expressPaymentHelper_1.setExpressShippingMethod)({orderId:order.id,config:{accessToken,endpoint},selectFirst:!1,selectedShippingMethodId:(_0=ev?.shippingOption)===null||_0===void 0?void 0:_0.id,params:{include:["shipments.available_shipping_methods"]}});const placeOrderParams={config:{accessToken,endpoint},orderId:order?.id,paymentResource,paymentSourceId:paymentSource?.id};yield(0,expressPaymentHelper_1.setExpressPlaceOrder)(placeOrderParams);const{paymentIntent,error:confirmError}=yield 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}=yield 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=yield(0,expressPaymentHelper_1.setExpressPlaceOrder)(placeOrderParams2);ev.complete("success"),(0,expressPaymentHelper_1.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=yield(0,expressPaymentHelper_1.setExpressPlaceOrder)(placeOrderParams2);ev.complete("success"),(0,expressPaymentHelper_1.expressRedirectUrl)({order:order2,config:{accessToken,endpoint}})}catch(err){console.error("Place order:",err),ev.complete("fail")}}}})),(0,jsx_runtime_1.jsx)(react_stripe_js_1.PaymentRequestButtonElement,{className:"",options:{paymentRequest}})):null}exports.StripeExpressPayment=StripeExpressPayment;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WireTransferPayment=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_1=require("react"),defaultMessage="after placing the order, you will need to manually complete the payment with your bank";function WireTransferPayment({infoMessage,...p}){const{className,"data-testid":dataTestId}=p,ref=(0,react_1.useRef)(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default);(0,react_1.useEffect)(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&(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:"wire-transfer",last4:""}}}}),!0}catch{return!1}return!1};return(0,jsx_runtime_1.jsx)("form",{ref,children:(0,jsx_runtime_1.jsx)("div",{className,"data-testid":dataTestId,children:(0,jsx_runtime_1.jsx)("span",{className:infoMessage?.className,children:infoMessage?.text
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WireTransferPayment=void 0;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),PaymentMethodContext_1=tslib_1.__importDefault(require("../../context/PaymentMethodContext")),react_1=require("react"),defaultMessage="after placing the order, you will need to manually complete the payment with your bank";function WireTransferPayment({infoMessage,...p}){const{className,"data-testid":dataTestId}=p,ref=(0,react_1.useRef)(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=(0,react_1.useContext)(PaymentMethodContext_1.default);(0,react_1.useEffect)(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&(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:"wire-transfer",last4:""}}}}),!0}catch{return!1}return!1};return(0,jsx_runtime_1.jsx)("form",{ref,children:(0,jsx_runtime_1.jsx)("div",{className,"data-testid":dataTestId,children:(0,jsx_runtime_1.jsx)("span",{className:infoMessage?.className,children:infoMessage?.text??defaultMessage})})})}exports.WireTransferPayment=WireTransferPayment,exports.default=WireTransferPayment;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { type setInStockSubscription, type InStockSubscriptionState } from '../reducers/InStockSubscriptionReducer';
|
|
3
|
+
export interface InitialInStockSubscriptionContext extends InStockSubscriptionState {
|
|
4
|
+
setInStockSubscription?: typeof setInStockSubscription;
|
|
5
|
+
}
|
|
6
|
+
declare const InStockSubscriptionContext: import("react").Context<InitialInStockSubscriptionContext>;
|
|
7
|
+
export default InStockSubscriptionContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const react_1=require("react"),initial={},InStockSubscriptionContext=(0,react_1.createContext)(initial);exports.default=InStockSubscriptionContext;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type BaseAction } from '../typings/index';
|
|
3
|
+
import { type Dispatch } from 'react';
|
|
4
|
+
import type { BaseError } from '../typings/errors';
|
|
5
|
+
type InStockSubscriptionActionType = 'setErrors';
|
|
6
|
+
type InStockSubscriptionAction = BaseAction<InStockSubscriptionActionType, InStockSubscriptionState>;
|
|
7
|
+
export interface InStockSubscriptionState {
|
|
8
|
+
errors?: BaseError[];
|
|
9
|
+
}
|
|
10
|
+
export declare const inStockSubscriptionInitialState: InStockSubscriptionState;
|
|
11
|
+
interface TSetInStockSubscriptionParams {
|
|
12
|
+
/**
|
|
13
|
+
* Commerce Layer config
|
|
14
|
+
*/
|
|
15
|
+
config?: CommerceLayerConfig;
|
|
16
|
+
/**
|
|
17
|
+
* Customer email
|
|
18
|
+
*/
|
|
19
|
+
customerEmail?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Sku code
|
|
22
|
+
*/
|
|
23
|
+
skuCode: string;
|
|
24
|
+
/**
|
|
25
|
+
* Dispatch function
|
|
26
|
+
*/
|
|
27
|
+
dispatch?: Dispatch<InStockSubscriptionAction>;
|
|
28
|
+
}
|
|
29
|
+
export declare function setInStockSubscription<T extends TSetInStockSubscriptionParams>({ config, customerEmail, skuCode, dispatch }: T): Promise<{
|
|
30
|
+
success: boolean;
|
|
31
|
+
}>;
|
|
32
|
+
export default function inStockSubscriptionReducer(state: InStockSubscriptionState, reducer: InStockSubscriptionAction): InStockSubscriptionState;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setInStockSubscription=exports.inStockSubscriptionInitialState=void 0;const tslib_1=require("tslib"),baseReducer_1=tslib_1.__importDefault(require("../utils/baseReducer")),getSdk_1=tslib_1.__importDefault(require("../utils/getSdk")),getErrors_1=tslib_1.__importDefault(require("../utils/getErrors")),actionType=["setErrors"];exports.inStockSubscriptionInitialState={errors:[]};function setInStockSubscription({config,customerEmail,skuCode,dispatch}){return tslib_1.__awaiter(this,void 0,void 0,function*(){try{if(config==null)throw new Error("Access token and endpoint is required");const sdk=(0,getSdk_1.default)(config),attributes={sku_code:skuCode};return customerEmail!=null&&(attributes.customer_email=customerEmail),yield sdk.in_stock_subscriptions.create(attributes),{success:!0}}catch(error){const errors=(0,getErrors_1.default)({error,resource:"in_stock_subscriptions"});return dispatch?.({type:"setErrors",payload:{errors}}),{success:!1}}})}exports.setInStockSubscription=setInStockSubscription;function inStockSubscriptionReducer(state,reducer){return(0,baseReducer_1.default)(state,reducer,actionType)}exports.default=inStockSubscriptionReducer;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type Order, type PaymentMethod, type QueryParamsRetrieve, type AddressCreate } from '@commercelayer/sdk';
|
|
3
|
+
import { type PaymentRequestShippingOption } from '@stripe/stripe-js';
|
|
4
|
+
import { type PaymentResource } from '../reducers/PaymentMethodReducer';
|
|
5
|
+
export declare function getAvailableExpressPayments(paymentMethods: PaymentMethod[]): PaymentMethod[];
|
|
6
|
+
interface TFakeAddressParams {
|
|
7
|
+
/**
|
|
8
|
+
* The order id
|
|
9
|
+
*/
|
|
10
|
+
orderId: string;
|
|
11
|
+
/**
|
|
12
|
+
* The Commerce Layer config
|
|
13
|
+
*/
|
|
14
|
+
config: Required<CommerceLayerConfig>;
|
|
15
|
+
/**
|
|
16
|
+
* The address resource
|
|
17
|
+
*/
|
|
18
|
+
address: AddressCreate;
|
|
19
|
+
/**
|
|
20
|
+
* The customer email
|
|
21
|
+
*/
|
|
22
|
+
email?: string;
|
|
23
|
+
}
|
|
24
|
+
export declare function setExpressFakeAddress({ orderId, config, address, email }: TFakeAddressParams): Promise<Order>;
|
|
25
|
+
export declare function getExpressShippingMethods(order: Order): PaymentRequestShippingOption[] | null;
|
|
26
|
+
type TSetExpressShippingMethodParams = {
|
|
27
|
+
/**
|
|
28
|
+
* The Commerce Layer config
|
|
29
|
+
*/
|
|
30
|
+
config: CommerceLayerConfig;
|
|
31
|
+
/**
|
|
32
|
+
* The order id
|
|
33
|
+
*/
|
|
34
|
+
orderId: string;
|
|
35
|
+
/**
|
|
36
|
+
* The query params
|
|
37
|
+
*/
|
|
38
|
+
params?: QueryParamsRetrieve;
|
|
39
|
+
} & ({
|
|
40
|
+
/**
|
|
41
|
+
* Select the first shipping method
|
|
42
|
+
*/
|
|
43
|
+
selectFirst: false;
|
|
44
|
+
/**
|
|
45
|
+
* The selected shipping method id
|
|
46
|
+
*/
|
|
47
|
+
selectedShippingMethodId?: string;
|
|
48
|
+
} | {
|
|
49
|
+
selectFirst?: true;
|
|
50
|
+
selectedShippingMethodId?: never;
|
|
51
|
+
});
|
|
52
|
+
export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params }: TSetExpressShippingMethodParams): Promise<Order>;
|
|
53
|
+
export type TSetExpressPlaceOrderParams = {
|
|
54
|
+
/**
|
|
55
|
+
* The Commerce Layer config
|
|
56
|
+
*/
|
|
57
|
+
config: CommerceLayerConfig;
|
|
58
|
+
/**
|
|
59
|
+
* The order id
|
|
60
|
+
*/
|
|
61
|
+
orderId: string;
|
|
62
|
+
} & ({
|
|
63
|
+
/**
|
|
64
|
+
* The payment resource
|
|
65
|
+
*/
|
|
66
|
+
paymentResource: PaymentResource;
|
|
67
|
+
/**
|
|
68
|
+
* The payment source id
|
|
69
|
+
*/
|
|
70
|
+
paymentSourceId: string;
|
|
71
|
+
/**
|
|
72
|
+
* Place the order
|
|
73
|
+
*/
|
|
74
|
+
placeTheOrder?: false;
|
|
75
|
+
} | {
|
|
76
|
+
paymentResource?: never;
|
|
77
|
+
paymentSourceId?: never;
|
|
78
|
+
placeTheOrder?: true;
|
|
79
|
+
});
|
|
80
|
+
export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder }: TSetExpressPlaceOrderParams): Promise<Order>;
|
|
81
|
+
interface TExpressRedirectUrlParams {
|
|
82
|
+
/**
|
|
83
|
+
* Order resource
|
|
84
|
+
*/
|
|
85
|
+
order: Order;
|
|
86
|
+
/**
|
|
87
|
+
* The Commerce Layer config
|
|
88
|
+
*/
|
|
89
|
+
config: CommerceLayerConfig;
|
|
90
|
+
}
|
|
91
|
+
export declare function expressRedirectUrl({ order, config: { accessToken, endpoint } }: TExpressRedirectUrlParams): void;
|
|
92
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.expressRedirectUrl=exports.setExpressPlaceOrder=exports.setExpressShippingMethod=exports.getExpressShippingMethods=exports.setExpressFakeAddress=exports.getAvailableExpressPayments=void 0;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)}exports.getAvailableExpressPayments=getAvailableExpressPayments;function setExpressFakeAddress({orderId,config,address,email}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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)})}exports.setExpressFakeAddress=setExpressFakeAddress;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:""}]}}exports.getExpressShippingMethods=getExpressShippingMethods;function setExpressShippingMethod({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){var _a,_b,_c;return tslib_1.__awaiter(this,void 0,void 0,function*(){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(_a=order?.shipments)!==null&&_a!==void 0?_a:[]){const[firstShippingMethodId]=(_c=(_b=shipment?.available_shipping_methods)===null||_b===void 0?void 0:_b.map(method=>method.id))!==null&&_c!==void 0?_c:[];firstShippingMethodId!=null&&(yield sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)}))}return yield sdk.orders.retrieve(order.id,params)})}exports.setExpressShippingMethod=setExpressShippingMethod;function setExpressPlaceOrder({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){return tslib_1.__awaiter(this,void 0,void 0,function*(){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})})}exports.setExpressPlaceOrder=setExpressPlaceOrder;function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=(0,getDomain_1.getDomain)(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;window.location.pathname.includes("/checkout")||window.location.pathname.includes(`/${order.id}`)?window.location.reload():window.location.href=href}exports.expressRedirectUrl=expressRedirectUrl;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAvailableExpressPayments=void 0;const availablePaymentMethods=["stripe_payments"];function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}exports.getAvailableExpressPayments=getAvailableExpressPayments;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDomain=void 0;function getDomain(endpoint){const url=new URL(endpoint),[slug]=url.hostname.split(".");return{domain:url.hostname.replace(`${slug??""}.`,""),slug}}exports.getDomain=getDomain;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function isEmpty<V>(value: V): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isEmpty=void 0;function isEmpty(value){if(value==null)return!0;if(Array.isArray(value)||typeof value=="string")return value.length===0;if(typeof value=="object")return Object.keys(value).length===0;throw new Error("Invalid value for isEmpty function")}exports.isEmpty=isEmpty;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ChildrenFunction } from '../../typings/index';
|
|
2
|
+
interface Props extends Omit<JSX.IntrinsicElements['button'], 'children' | 'onClick'> {
|
|
3
|
+
/**
|
|
4
|
+
* The code of the sku.
|
|
5
|
+
*/
|
|
6
|
+
skuCode: string;
|
|
7
|
+
/**
|
|
8
|
+
* The label to display.
|
|
9
|
+
*/
|
|
10
|
+
label?: string | JSX.Element;
|
|
11
|
+
/**
|
|
12
|
+
* The label to display when the button is loading.
|
|
13
|
+
*/
|
|
14
|
+
loadingLabel?: string | JSX.Element;
|
|
15
|
+
/**
|
|
16
|
+
* The email of the customer.
|
|
17
|
+
*/
|
|
18
|
+
customerEmail?: string;
|
|
19
|
+
/**
|
|
20
|
+
* The children of the component.
|
|
21
|
+
*/
|
|
22
|
+
children?: ChildrenFunction<Omit<Props, 'children'>>;
|
|
23
|
+
/**
|
|
24
|
+
* Show the button.
|
|
25
|
+
*/
|
|
26
|
+
show?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The callback function to call when the button is clicked.
|
|
29
|
+
*/
|
|
30
|
+
onClick?: (response: {
|
|
31
|
+
success: boolean;
|
|
32
|
+
}) => void;
|
|
33
|
+
}
|
|
34
|
+
export declare function InStockSubscriptionButton({ skuCode, customerEmail, children, onClick, show, label, loadingLabel, ...props }: Props): JSX.Element | null;
|
|
35
|
+
export default InStockSubscriptionButton;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import InStockSubscriptionContext from"../../context/InStockSubscriptionContext";import useCustomContext from"../../utils/hooks/useCustomContext";import jwt from"../../utils/jwt";import{useContext,useState}from"react";export function InStockSubscriptionButton({skuCode,customerEmail,children,onClick,show=!1,label="Subscribe",loadingLabel="Loading...",...props}){const{setInStockSubscription}=useCustomContext({context:InStockSubscriptionContext,contextComponentName:"InStockSubscriptionsContainer",currentComponentName:"InStockSubscriptionButton",key:"setInStockSubscription"}),{accessToken}=useContext(CommerceLayerContext),[loading,setLoading]=useState(!1),handleClick=async()=>{if(accessToken!=null&&customerEmail==null&&jwt(accessToken)?.owner==null){console.error("Missing customerEmail");return}if(setInStockSubscription==null){console.error("Missing <InStockSubscriptionsContainer>");return}setLoading(!0);const res=await setInStockSubscription({customerEmail,skuCode});onClick?.(res),setLoading(!1)};if(children!=null){const parentProps={skuCode,customerEmail,onClick,show,label,loadingLabel,...props};return _jsx(Parent,{...parentProps,children})}return show?_jsx("button",{onClick:()=>{handleClick()},disabled:loading,...props,children:loading?loadingLabel:label}):null}export default InStockSubscriptionButton;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type DefaultChildrenType } from '../../typings/globals';
|
|
2
|
+
interface Props {
|
|
3
|
+
/**
|
|
4
|
+
* The children of the component.
|
|
5
|
+
*/
|
|
6
|
+
children: DefaultChildrenType;
|
|
7
|
+
}
|
|
8
|
+
export declare function InStockSubscriptionsContainer({ children }: Props): JSX.Element | null;
|
|
9
|
+
export default InStockSubscriptionsContainer;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import CommerceLayerContext from"../../context/CommerceLayerContext";import InStockSubscriptionContext from"../../context/InStockSubscriptionContext";import inStockSubscriptionReducer,{inStockSubscriptionInitialState,setInStockSubscription}from"../../reducers/InStockSubscriptionReducer";import useCustomContext from"../../utils/hooks/useCustomContext";import{useReducer}from"react";export function InStockSubscriptionsContainer({children}){const config=useCustomContext({context:CommerceLayerContext,contextComponentName:"CommerceLayer",currentComponentName:"InStockSubscriptionsContainer",key:"accessToken"}),[state,dispatch]=useReducer(inStockSubscriptionReducer,inStockSubscriptionInitialState),value={...state,setInStockSubscription:async({customerEmail,skuCode})=>await setInStockSubscription({customerEmail,skuCode,config,dispatch})};return _jsx(InStockSubscriptionContext.Provider,{value,children})}export default InStockSubscriptionsContainer;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GatewayBaseType } from '../payment_gateways/PaymentGateway';
|
|
1
|
+
import { type GatewayBaseType } from '../payment_gateways/PaymentGateway';
|
|
2
2
|
type Props = GatewayBaseType;
|
|
3
3
|
export declare function WireTransferGateway(props: Props): JSX.Element | null;
|
|
4
4
|
export default WireTransferGateway;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import WireTransferPayment from"../payment_source/WireTransferPayment";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import{getPaymentConfig}from"../../reducers/PaymentMethodReducer";import isEmpty from"lodash/isEmpty";import{useContext}from"react";export function WireTransferGateway(props){const{readonly,showCard,handleEditClick,children,...p}=props,{payment}=useContext(PaymentMethodChildrenContext),{currentPaymentMethodId,config,paymentSource}=useContext(PaymentMethodContext),paymentResource="wire_transfers";if(!readonly&&payment?.id!==currentPaymentMethodId)return null;if(readonly||showCard){const card=paymentSource?.options?.card||paymentSource?.metadata?.card,value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}const wireTransferConfig=config&&paymentResource?getPaymentConfig(paymentResource,config):{};return _jsx(WireTransferPayment,{...p,...wireTransferConfig})}export default WireTransferGateway;
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import WireTransferPayment from"../payment_source/WireTransferPayment";import PaymentMethodChildrenContext from"../../context/PaymentMethodChildrenContext";import PaymentMethodContext from"../../context/PaymentMethodContext";import PaymentSourceContext from"../../context/PaymentSourceContext";import{getPaymentConfig}from"../../reducers/PaymentMethodReducer";import isEmpty from"lodash/isEmpty";import{useContext}from"react";export function WireTransferGateway(props){const{readonly,showCard,handleEditClick,children,...p}=props,{payment}=useContext(PaymentMethodChildrenContext),{currentPaymentMethodId,config,paymentSource}=useContext(PaymentMethodContext),paymentResource="wire_transfers";if(!readonly&&payment?.id!==currentPaymentMethodId)return null;if(readonly||showCard){const card=paymentSource?.options?.card||paymentSource?.metadata?.card,value={...card,showCard,handleEditClick,readonly};return isEmpty(card)?null:_jsx(PaymentSourceContext.Provider,{value,children})}const wireTransferConfig=config&&paymentResource?getPaymentConfig(paymentResource,config):{};return _jsx(WireTransferPayment,{...p,...wireTransferConfig?.wireTransfer})}export default WireTransferGateway;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsx as _jsx}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=>{console.log("available payment:",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(PaymentRequestButtonElement,{className:"",options:{paymentRequest}})):null}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext from"../../context/PaymentMethodContext";import{useContext,useEffect,useRef}from"react";const defaultMessage="after placing the order, you will need to manually complete the payment with your bank";export function WireTransferPayment({infoMessage,...p}){const{className,"data-testid":dataTestId}=p,ref=useRef(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext);useEffect(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&(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:"wire-transfer",last4:""}}}}),!0}catch{return!1}return!1};return _jsx("form",{ref,children:_jsx("div",{className,"data-testid":dataTestId,children:_jsx("span",{className:infoMessage?.className,children:infoMessage?.text
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import PaymentMethodContext from"../../context/PaymentMethodContext";import{useContext,useEffect,useRef}from"react";const defaultMessage="after placing the order, you will need to manually complete the payment with your bank";export function WireTransferPayment({infoMessage,...p}){const{className,"data-testid":dataTestId}=p,ref=useRef(null),{setPaymentSource,paymentSource,currentPaymentMethodType,setPaymentRef}=useContext(PaymentMethodContext);useEffect(()=>(ref.current&&paymentSource&¤tPaymentMethodType&&(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:"wire-transfer",last4:""}}}}),!0}catch{return!1}return!1};return _jsx("form",{ref,children:_jsx("div",{className,"data-testid":dataTestId,children:_jsx("span",{className:infoMessage?.className,children:infoMessage?.text??defaultMessage})})})}export default WireTransferPayment;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
import { type setInStockSubscription, type InStockSubscriptionState } from '../reducers/InStockSubscriptionReducer';
|
|
3
|
+
export interface InitialInStockSubscriptionContext extends InStockSubscriptionState {
|
|
4
|
+
setInStockSubscription?: typeof setInStockSubscription;
|
|
5
|
+
}
|
|
6
|
+
declare const InStockSubscriptionContext: import("react").Context<InitialInStockSubscriptionContext>;
|
|
7
|
+
export default InStockSubscriptionContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createContext}from"react";const initial={},InStockSubscriptionContext=createContext(initial);export default InStockSubscriptionContext;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type BaseAction } from '../typings/index';
|
|
3
|
+
import { type Dispatch } from 'react';
|
|
4
|
+
import type { BaseError } from '../typings/errors';
|
|
5
|
+
type InStockSubscriptionActionType = 'setErrors';
|
|
6
|
+
type InStockSubscriptionAction = BaseAction<InStockSubscriptionActionType, InStockSubscriptionState>;
|
|
7
|
+
export interface InStockSubscriptionState {
|
|
8
|
+
errors?: BaseError[];
|
|
9
|
+
}
|
|
10
|
+
export declare const inStockSubscriptionInitialState: InStockSubscriptionState;
|
|
11
|
+
interface TSetInStockSubscriptionParams {
|
|
12
|
+
/**
|
|
13
|
+
* Commerce Layer config
|
|
14
|
+
*/
|
|
15
|
+
config?: CommerceLayerConfig;
|
|
16
|
+
/**
|
|
17
|
+
* Customer email
|
|
18
|
+
*/
|
|
19
|
+
customerEmail?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Sku code
|
|
22
|
+
*/
|
|
23
|
+
skuCode: string;
|
|
24
|
+
/**
|
|
25
|
+
* Dispatch function
|
|
26
|
+
*/
|
|
27
|
+
dispatch?: Dispatch<InStockSubscriptionAction>;
|
|
28
|
+
}
|
|
29
|
+
export declare function setInStockSubscription<T extends TSetInStockSubscriptionParams>({ config, customerEmail, skuCode, dispatch }: T): Promise<{
|
|
30
|
+
success: boolean;
|
|
31
|
+
}>;
|
|
32
|
+
export default function inStockSubscriptionReducer(state: InStockSubscriptionState, reducer: InStockSubscriptionAction): InStockSubscriptionState;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import baseReducer from"../utils/baseReducer";import getSdk from"../utils/getSdk";import getErrors from"../utils/getErrors";const actionType=["setErrors"];export const inStockSubscriptionInitialState={errors:[]};export async function setInStockSubscription({config,customerEmail,skuCode,dispatch}){try{if(config==null)throw new Error("Access token and endpoint is required");const sdk=getSdk(config),attributes={sku_code:skuCode};return customerEmail!=null&&(attributes.customer_email=customerEmail),await sdk.in_stock_subscriptions.create(attributes),{success:!0}}catch(error){const errors=getErrors({error,resource:"in_stock_subscriptions"});return dispatch?.({type:"setErrors",payload:{errors}}),{success:!1}}}export default function inStockSubscriptionReducer(state,reducer){return baseReducer(state,reducer,actionType)}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type CommerceLayerConfig } from '../context/CommerceLayerContext';
|
|
2
|
+
import { type Order, type PaymentMethod, type QueryParamsRetrieve, type AddressCreate } from '@commercelayer/sdk';
|
|
3
|
+
import { type PaymentRequestShippingOption } from '@stripe/stripe-js';
|
|
4
|
+
import { type PaymentResource } from '../reducers/PaymentMethodReducer';
|
|
5
|
+
export declare function getAvailableExpressPayments(paymentMethods: PaymentMethod[]): PaymentMethod[];
|
|
6
|
+
interface TFakeAddressParams {
|
|
7
|
+
/**
|
|
8
|
+
* The order id
|
|
9
|
+
*/
|
|
10
|
+
orderId: string;
|
|
11
|
+
/**
|
|
12
|
+
* The Commerce Layer config
|
|
13
|
+
*/
|
|
14
|
+
config: Required<CommerceLayerConfig>;
|
|
15
|
+
/**
|
|
16
|
+
* The address resource
|
|
17
|
+
*/
|
|
18
|
+
address: AddressCreate;
|
|
19
|
+
/**
|
|
20
|
+
* The customer email
|
|
21
|
+
*/
|
|
22
|
+
email?: string;
|
|
23
|
+
}
|
|
24
|
+
export declare function setExpressFakeAddress({ orderId, config, address, email }: TFakeAddressParams): Promise<Order>;
|
|
25
|
+
export declare function getExpressShippingMethods(order: Order): PaymentRequestShippingOption[] | null;
|
|
26
|
+
type TSetExpressShippingMethodParams = {
|
|
27
|
+
/**
|
|
28
|
+
* The Commerce Layer config
|
|
29
|
+
*/
|
|
30
|
+
config: CommerceLayerConfig;
|
|
31
|
+
/**
|
|
32
|
+
* The order id
|
|
33
|
+
*/
|
|
34
|
+
orderId: string;
|
|
35
|
+
/**
|
|
36
|
+
* The query params
|
|
37
|
+
*/
|
|
38
|
+
params?: QueryParamsRetrieve;
|
|
39
|
+
} & ({
|
|
40
|
+
/**
|
|
41
|
+
* Select the first shipping method
|
|
42
|
+
*/
|
|
43
|
+
selectFirst: false;
|
|
44
|
+
/**
|
|
45
|
+
* The selected shipping method id
|
|
46
|
+
*/
|
|
47
|
+
selectedShippingMethodId?: string;
|
|
48
|
+
} | {
|
|
49
|
+
selectFirst?: true;
|
|
50
|
+
selectedShippingMethodId?: never;
|
|
51
|
+
});
|
|
52
|
+
export declare function setExpressShippingMethod({ config, orderId, selectFirst, selectedShippingMethodId, params }: TSetExpressShippingMethodParams): Promise<Order>;
|
|
53
|
+
export type TSetExpressPlaceOrderParams = {
|
|
54
|
+
/**
|
|
55
|
+
* The Commerce Layer config
|
|
56
|
+
*/
|
|
57
|
+
config: CommerceLayerConfig;
|
|
58
|
+
/**
|
|
59
|
+
* The order id
|
|
60
|
+
*/
|
|
61
|
+
orderId: string;
|
|
62
|
+
} & ({
|
|
63
|
+
/**
|
|
64
|
+
* The payment resource
|
|
65
|
+
*/
|
|
66
|
+
paymentResource: PaymentResource;
|
|
67
|
+
/**
|
|
68
|
+
* The payment source id
|
|
69
|
+
*/
|
|
70
|
+
paymentSourceId: string;
|
|
71
|
+
/**
|
|
72
|
+
* Place the order
|
|
73
|
+
*/
|
|
74
|
+
placeTheOrder?: false;
|
|
75
|
+
} | {
|
|
76
|
+
paymentResource?: never;
|
|
77
|
+
paymentSourceId?: never;
|
|
78
|
+
placeTheOrder?: true;
|
|
79
|
+
});
|
|
80
|
+
export declare function setExpressPlaceOrder({ config, orderId, paymentResource, paymentSourceId, placeTheOrder }: TSetExpressPlaceOrderParams): Promise<Order>;
|
|
81
|
+
interface TExpressRedirectUrlParams {
|
|
82
|
+
/**
|
|
83
|
+
* Order resource
|
|
84
|
+
*/
|
|
85
|
+
order: Order;
|
|
86
|
+
/**
|
|
87
|
+
* The Commerce Layer config
|
|
88
|
+
*/
|
|
89
|
+
config: CommerceLayerConfig;
|
|
90
|
+
}
|
|
91
|
+
export declare function expressRedirectUrl({ order, config: { accessToken, endpoint } }: TExpressRedirectUrlParams): void;
|
|
92
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import getSdk from"./getSdk";import{getDomain}from"./getDomain";const availablePaymentMethods=["stripe_payments"];export function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}export async function setExpressFakeAddress({orderId,config,address,email}){const params={include:["shipments.available_shipping_methods"]},sdk=getSdk(config),fakeAddress=await sdk.addresses.create(address),resource={id:orderId,billing_address:sdk.addresses.relationship(fakeAddress.id),_shipping_address_same_as_billing:!0};return email!=null&&(resource.customer_email=email),await sdk.orders.update(resource,params),await sdk.orders.retrieve(orderId,params)}export function getExpressShippingMethods(order){const isSingleShipment=order?.shipments?.length===1,shippingMethods=order?.shipments?.map(shipment=>shipment.available_shipping_methods);if(isSingleShipment)return shippingMethods==null?null:shippingMethods.flat().map(method=>({id:method?.id??"",label:method?.name??"",amount:method?.price_amount_for_shipment_cents??0,detail:""}));{if(shippingMethods==null)return null;const shippingOptionsAmount=[];return shippingMethods.forEach(methods=>{if(methods!=null){const[firstMethod]=methods;firstMethod!=null&&shippingOptionsAmount.push(firstMethod.price_amount_for_shipment_cents??0)}}),[{id:"shipping",label:"Shipping",amount:shippingOptionsAmount.reduce((a,b)=>a+b,0),detail:""}]}}export async function setExpressShippingMethod({config,orderId,selectFirst=!0,selectedShippingMethodId,params}){const sdk=getSdk(config),order=await sdk.orders.retrieve(orderId,params),shippingMethods=getExpressShippingMethods(order);if(order?.shipments==null)throw new Error("No shipments found");const isSingleShipment=order.shipments.length===1,[shipmentId]=order.shipments.map(shipment=>shipment.id);if(shipmentId==null)throw new Error("No shipment found");if(shippingMethods==null||shippingMethods?.length===0)throw new Error("No shipping methods found");if(isSingleShipment)if(selectFirst){const[firstShippingMethodId]=shippingMethods.map(method=>method.id);firstShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}else selectedShippingMethodId!=null&&await sdk.shipments.update({id:shipmentId,shipping_method:sdk.shipping_methods.relationship(selectedShippingMethodId)});else for(const shipment of order?.shipments??[]){const[firstShippingMethodId]=shipment?.available_shipping_methods?.map(method=>method.id)??[];firstShippingMethodId!=null&&await sdk.shipments.update({id:shipment.id,shipping_method:sdk.shipping_methods.relationship(firstShippingMethodId)})}return await sdk.orders.retrieve(order.id,params)}export async function setExpressPlaceOrder({config,orderId,paymentResource,paymentSourceId,placeTheOrder=!1}){const sdk=getSdk(config);if(!placeTheOrder&&paymentResource!=null&&paymentSourceId!=null){const include=["shipments.shipping_method","payment_source","payment_method"];return await sdk.orders.retrieve(orderId,{include}),await sdk[paymentResource].update({id:paymentSourceId,order:sdk.orders.relationship(orderId)}),await sdk.orders.update({id:orderId,payment_source:sdk[paymentResource].relationship(paymentSourceId)}),await sdk[paymentResource].update({id:paymentSourceId,_update:!0}),await sdk.orders.retrieve(orderId,{include})}return await sdk.orders.update({id:orderId,_place:!0})}export function expressRedirectUrl({order,config:{accessToken,endpoint}}){if(accessToken==null)throw new Error("No access token found");if(endpoint==null)throw new Error("No endpoint found");const{slug}=getDomain(endpoint);if(slug==null)throw new Error("No slug found");const href=order?.checkout_url!=null?order?.checkout_url:`https://${slug}.commercelayer.app/checkout/${order.id}?accessToken=${accessToken}`;window.location.pathname.includes("/checkout")||window.location.pathname.includes(`/${order.id}`)?window.location.reload():window.location.href=href}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const availablePaymentMethods=["stripe_payments"];export function getAvailableExpressPayments(paymentMethods){return paymentMethods.filter(payment=>payment.payment_source_type?availablePaymentMethods.includes(payment.payment_source_type):!1)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function getDomain(endpoint){const url=new URL(endpoint),[slug]=url.hostname.split(".");return{domain:url.hostname.replace(`${slug??""}.`,""),slug}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function isEmpty<V>(value: V): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function isEmpty(value){if(value==null)return!0;if(Array.isArray(value)||typeof value=="string")return value.length===0;if(typeof value=="object")return Object.keys(value).length===0;throw new Error("Invalid value for isEmpty function")}
|