Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/headless-components/ecom/src/services/checkout-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { redirects } from '@wix/redirects';
export { ChannelType } from '@wix/auto_sdk_ecom_checkout';

export type LineItem = checkout.LineItem;
export type CheckoutInfo = checkout.Checkout;

/**
* API interface for the Checkout service
Expand All @@ -17,7 +18,10 @@ export interface CheckoutServiceAPI {
isLoading: Signal<boolean>;
error: Signal<string | null>;

createCheckout: (lineItems: LineItem[]) => Promise<void>;
createCheckout: (
lineItems: LineItem[],
checkoutInfo?: CheckoutInfo,
) => Promise<void>;
}

export const CheckoutServiceDefinition =
Expand All @@ -40,14 +44,18 @@ export const CheckoutService =
const isLoading: Signal<boolean> = signalsService.signal(false);
const error: Signal<string | null> = signalsService.signal(null as any);

const createCheckout = async (lineItems: LineItem[]) => {
const createCheckout = async (
lineItems: LineItem[],
checkoutInfo?: CheckoutInfo,
) => {
try {
isLoading.set(true);
error.set(null);

const checkoutResult = await checkout.createCheckout({
lineItems,
channelType: config.channelType || checkout.ChannelType.WEB,
checkoutInfo,
});

if (!checkoutResult._id) {
Expand Down
2 changes: 1 addition & 1 deletion packages/headless-components/pricing-plans/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.8",
"type": "module",
"scripts": {
"prebuild": "cd ../utils && yarn build && cd ../components && yarn build && cd ../media && yarn build",
"prebuild": "cd ../utils && yarn build && cd ../components && yarn build && cd ../media && yarn build && cd ../ecom && yarn build",
"build": "npm run build:esm && npm run build:cjs",
"build:esm": "tsc -p tsconfig.json",
"build:cjs": "tsc -p tsconfig.cjs.json",
Expand Down
67 changes: 35 additions & 32 deletions packages/headless-components/pricing-plans/src/react/Plan.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import React from 'react';
export { WixMediaImage } from '@wix/headless-media/react';
import { AsChildChildren, AsChildSlot } from '@wix/headless-utils/react';
import {
PlanServiceConfig,
PlanServiceDefinition,
PRICING_PLANS_APP_ID,
} from '../services/index.js';
import { PlanServiceConfig } from '../services/index.js';
import {
Root as CoreRoot,
Plan as CorePlan,
Expand Down Expand Up @@ -35,10 +31,10 @@ import {
PerkItemContext,
PerkItemData,
PerkItem as CorePerkItem,
ActionBuyNow as CoreActionBuyNow,
ActionBuyNowRenderProps,
} from './core/Plan.js';
import { WixMediaImage } from '@wix/headless-media/react';
import { Commerce } from '@wix/headless-ecom/react';
import { useService } from '@wix/services-manager-react';

enum PlanTestId {
Plan = 'plan-plan',
Expand Down Expand Up @@ -760,7 +756,17 @@ export const PerkItem = React.forwardRef<HTMLElement, PerkItemProps>(
),
);

type ActionBuyNowProps = Omit<Commerce.ActionAddToCartProps, 'lineItems'>;
export type PlanActionBuyNowRenderProps = ActionBuyNowRenderProps;

// TODO: Check if docs are still correct
interface ActionBuyNowProps {
asChild?: boolean;
children?: AsChildChildren<ActionBuyNowRenderProps>;
className?: string;
label?: string;
disabled?: boolean;
loadingState?: React.ReactNode;
}

/**
* Initiates the plan purchase flow.
Expand All @@ -787,31 +793,28 @@ type ActionBuyNowProps = Omit<Commerce.ActionAddToCartProps, 'lineItems'>;
* ```
*/
const ActionBuyNow = React.forwardRef<HTMLButtonElement, ActionBuyNowProps>(
(props, ref) => {
const { planSignal } = useService(PlanServiceDefinition);

({ asChild, children, className, label, disabled, loadingState }, ref) => {
return (
<Commerce.Actions.BuyNow
{...props}
lineItems={[
{
quantity: 1,
catalogReference: {
appId: PRICING_PLANS_APP_ID,
catalogItemId: planSignal.get()!._id!,
options: {
type: 'PLAN',
planOptions: {
pricingVariantId:
planSignal.get()!.enhancedData.price.pricingVariantId,
},
},
},
},
]}
ref={ref}
data-testid={PlanTestId.ActionBuyNow}
/>
<CoreActionBuyNow>
{(actionBuyNowRenderProps) => (
<AsChildSlot
ref={ref}
asChild={asChild}
customElement={children}
customElementProps={actionBuyNowRenderProps}
className={className}
disabled={disabled || actionBuyNowRenderProps.isLoading}
data-testid={PlanTestId.ActionBuyNow}
data-is-loading={actionBuyNowRenderProps.isLoading}
data-is-disabled={disabled || actionBuyNowRenderProps.isLoading}
onClick={actionBuyNowRenderProps.goToPlanCheckout}
>
<button type="button">
{actionBuyNowRenderProps.isLoading ? loadingState : label}
</button>
</AsChildSlot>
)}
</CoreActionBuyNow>
);
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import {
CheckoutService,
CheckoutServiceDefinition,
} from '@wix/headless-ecom/services';
import {
PlanCheckoutService,
PlanCheckoutServiceDefinition,
} from '../../services/plan-checkout-service.js';

interface RootProps {
planServiceConfig: PlanServiceConfig;
Expand All @@ -38,7 +42,8 @@ export function Root({ planServiceConfig, children }: RootProps) {
channelType: ChannelType.WEB,
// TODO: Perhaps we can add postFlowUrl?
// postFlowUrl: ''
})}
})
.addService(PlanCheckoutServiceDefinition, PlanCheckoutService)}
>
{children}
</WixServices>
Expand Down Expand Up @@ -340,3 +345,36 @@ export function PerkItem({ children }: PerkItemProps) {

return children({ perk: perkItem.perk });
}

export interface ActionBuyNowRenderProps {
isLoading: boolean;
error: string | null;
goToPlanCheckout: () => Promise<void>;
}

interface ActionBuyNowProps {
children: (props: ActionBuyNowRenderProps) => React.ReactNode;
}

export function ActionBuyNow({ children }: ActionBuyNowProps) {
const { planSignal } = useService(PlanServiceDefinition);
const {
isLoadingSignal,
errorSignal,
goToPlanCheckout: _goToPlanCheckout,
} = useService(PlanCheckoutServiceDefinition);
const plan = planSignal.get();

if (!plan) {
return null;
}

const isLoading = isLoadingSignal.get();
const error = errorSignal.get();

return children({
isLoading,
error,
goToPlanCheckout: () => _goToPlanCheckout(plan),
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export type {
PlanDurationData,
PlanPerksData,
PlanPerkItemData,
PlanActionBuyNowRenderProps,
} from './Plan.js';

export const PricingPlans = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { httpClient } from '@wix/essentials';
import { CheckoutServiceDefinition } from '@wix/headless-ecom/services';
import { defineService, implementService } from '@wix/services-definitions';
import {
ReadOnlySignal,
SignalsServiceDefinition,
} from '@wix/services-definitions/core-services/signals';
import { PlanWithEnhancedData, PRICING_PLANS_APP_ID } from './plan-service.js';

export const PlanCheckoutServiceDefinition = defineService<{
isLoadingSignal: ReadOnlySignal<boolean>;
errorSignal: ReadOnlySignal<string | null>;
goToPlanCheckout: (plan: PlanWithEnhancedData) => Promise<void>;
}>('planCheckoutService');

export const PlanCheckoutService = implementService.withConfig<void>()(
PlanCheckoutServiceDefinition,
({ getService }) => {
const signalsService = getService(SignalsServiceDefinition);
const ecomCheckoutService = getService(CheckoutServiceDefinition);

const isLoadingSignal = signalsService.signal<boolean>(false);
const errorSignal = signalsService.signal<string | null>(null);

return {
isLoadingSignal,
errorSignal,
goToPlanCheckout: async (plan: PlanWithEnhancedData) => {
isLoadingSignal.set(true);
errorSignal.set(null);
try {
const address = await fetchAddress().catch(() => null);
await ecomCheckoutService.createCheckout(
[
{
quantity: 1,
catalogReference: {
appId: PRICING_PLANS_APP_ID,
catalogItemId: plan._id!,
options: {
type: 'PLAN',
planOptions: {
pricingVariantId:
plan.enhancedData.price.pricingVariantId,
},
},
},
},
],
{ billingInfo: address ? { address } : undefined },
);
} catch (error) {
errorSignal.set(
error instanceof Error
? error.message
: 'Failed to go to plan checkout',
);
} finally {
isLoadingSignal.set(false);
}
},
};
},
);

type AddressResponse = {
country?: string;
subdivision?: string;
city?: string;
};

async function fetchAddress(): Promise<AddressResponse> {
try {
const response = await httpClient.fetchWithAuth(
'/_api/pricing-plans-ecom/address',
);
return response.json();
} catch (error) {
console.error('Error fetching address:', error);
throw error;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import {
SignalsServiceDefinition,
} from '@wix/services-definitions/core-services/signals';
import { plansV3 } from '@wix/pricing-plans';
import {
CheckoutServiceDefinition,
LineItem,
} from '@wix/headless-ecom/services';
import { httpClient } from '@wix/essentials';

type ValidPeriod = Exclude<plansV3.PeriodWithLiterals, 'UNKNOWN_PERIOD'>;

Expand Down Expand Up @@ -42,6 +47,7 @@ export const PlanServiceDefinition = defineService<{
planSignal: ReadOnlySignal<PlanWithEnhancedData | null>;
isLoadingSignal: ReadOnlySignal<boolean>;
errorSignal: ReadOnlySignal<Error | null>;
goToPlanCheckout: (plan: PlanWithEnhancedData) => Promise<void>;
}>('planService');

export type PlanServiceConfig =
Expand All @@ -52,6 +58,7 @@ export const PlanService = implementService.withConfig<PlanServiceConfig>()(
PlanServiceDefinition,
({ getService, config }) => {
const signalsService = getService(SignalsServiceDefinition);
const checkoutService = getService(CheckoutServiceDefinition);
const isLoadingSignal = signalsService.signal<boolean>(false);
const errorSignal = signalsService.signal<Error | null>(null);
const configHasPlan = 'plan' in config;
Expand All @@ -78,10 +85,20 @@ export const PlanService = implementService.withConfig<PlanServiceConfig>()(
}
}

async function goToPlanCheckout(plan: PlanWithEnhancedData): Promise<void> {
const address = await fetchAddress().catch(() => null);
const lineItem = buildPlanLineItem(plan);
// TODO: Decide if we need `externalReference` here
return checkoutService.createCheckout([lineItem], {
billingInfo: address ? { address } : undefined,
});
}

return {
planSignal: planSignal,
isLoadingSignal: isLoadingSignal,
errorSignal: errorSignal,
planSignal,
isLoadingSignal,
errorSignal,
goToPlanCheckout,
};
},
);
Expand Down Expand Up @@ -245,3 +262,37 @@ export async function loadPlanServiceConfig(
const plan = await fetchAndEnhancePlan(planId);
return { plan };
}

type AddressResponse = {
country?: string;
subdivision?: string;
city?: string;
};

async function fetchAddress(): Promise<AddressResponse> {
try {
const response = await httpClient.fetchWithAuth(
'/_api/pricing-plans-ecom/address',
);
return response.json();
} catch (error) {
console.error('Error fetching address:', error);
throw error;
}
}

function buildPlanLineItem(plan: PlanWithEnhancedData): LineItem {
return {
quantity: 1,
catalogReference: {
appId: PRICING_PLANS_APP_ID,
catalogItemId: plan._id!,
options: {
type: 'PLAN',
planOptions: {
pricingVariantId: plan.enhancedData.price.pricingVariantId,
},
},
},
};
}