Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(headless-ssr-commerce): fix client side recommendation refresh with a productId #4793

Merged
merged 22 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
52 changes: 36 additions & 16 deletions packages/headless-react/src/ssr-commerce/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import {
InferControllerStaticStateMapFromDefinitionsWithSolutionType,
InferHydratedState,
NavigatorContext,
ControllerWithKind,
Kind,
SolutionType,
Context,
HydrateStaticStateOptions,
ParameterManager,
Parameters,
Recommendations,
} from '@coveo/headless/ssr-commerce';
import {PropsWithChildren, useEffect, useState} from 'react';
import {ReactCommerceEngineDefinition} from './commerce-engine.js';
Expand Down Expand Up @@ -48,24 +51,41 @@ export function buildProviderWithDefinition<
const {searchActions, controllers} = staticState;
const hydrateArguments: ControllerPropsMap = {};

if ('parameterManager' in controllers) {
hydrateArguments.parameterManager = {
initialState: {
parameters: (
controllers.parameterManager as ParameterManager<Parameters>
).state.parameters,
},
};
}
for (const [key, controller] of Object.entries(controllers)) {
const typedController = controller as ControllerWithKind;

if ('cart' in controllers) {
hydrateArguments.cart = {
initialState: {items: (controllers.cart as Cart).state.items},
};
}
switch (typedController._kind) {
case Kind.Cart:
hydrateArguments[key] = {
initialState: {
items: (controllers as Record<string, Cart>)[key].state.items,
},
};
break;

case Kind.Context:
hydrateArguments[key] = (controllers as Record<string, Context>)[
key
].state;
break;

case Kind.ParameterManager:
hydrateArguments[key] = {
initialState: {
parameters: (
controllers as Record<string, ParameterManager<Parameters>>
)[key].state.parameters,
},
};
break;

if ('context' in controllers) {
hydrateArguments.context = (controllers.context as Context).state;
case Kind.Recommendations:
hydrateArguments[key] = {
productId: (controllers as Record<string, Recommendations>)[key]
.state.productId,
};
break;
}
}

const args: HydrateStaticStateOptions<UnknownAction> &
Expand Down
8 changes: 8 additions & 0 deletions packages/headless/src/app/commerce-ssr-engine/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
ControllerDefinition,
ControllerDefinitionOption,
ControllerDefinitionsMap,
ControllerWithKind,
EngineStaticState,
InferControllerFromDefinition,
InferControllerPropsFromDefinition,
Expand All @@ -19,6 +20,12 @@ import {
SolutionType,
} from './types/common.js';

function hasKindProperty(
controller: Controller | ControllerWithKind
): controller is ControllerWithKind {
return '_kind' in controller;
}

export function createStaticState<TSearchAction extends UnknownAction>({
searchActions,
controllers,
Expand All @@ -32,6 +39,7 @@ export function createStaticState<TSearchAction extends UnknownAction>({
return {
controllers: mapObject(controllers, (controller) => ({
state: clone(controller.state),
...(hasKindProperty(controller) && {_kind: controller._kind}),
})) as InferControllerStaticStateMapFromControllers<ControllersMap>,
searchActions: searchActions.map((action) => clone(action)),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
HasOptionalKeys,
} from '../../ssr-engine/types/common.js';
import {SSRCommerceEngine} from '../factories/build-factory.js';
import {Kind} from './kind.js';

export type {
EngineDefinitionBuildResult,
Expand Down Expand Up @@ -59,6 +60,10 @@ export interface ControllerDefinitionWithoutProps<
build(engine: SSRCommerceEngine, solutionType?: SolutionType): TController;
}

export interface ControllerWithKind extends Controller {
_kind: Kind;
}

export interface ControllerDefinitionWithProps<
TController extends Controller,
TProps,
Expand All @@ -75,7 +80,7 @@ export interface ControllerDefinitionWithProps<
engine: SSRCommerceEngine,
props: TProps,
solutionType?: SolutionType
): TController;
): TController & ControllerWithKind;
}

export interface EngineStaticState<
Expand Down
6 changes: 6 additions & 0 deletions packages/headless/src/app/commerce-ssr-engine/types/kind.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export enum Kind {
Cart = 'CART',
Context = 'CONTEXT',
ParameterManager = 'PARAMETER_MANAGER',
Recommendations = 'RECOMMENDATIONS',
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {UniversalControllerDefinitionWithProps} from '../../../../app/commerce-ssr-engine/types/common.js';
import {Kind} from '../../../../app/commerce-ssr-engine/types/kind.js';
import {Cart, buildCart, CartInitialState} from './headless-cart.js';

export type {CartState, CartItem, CartProps} from './headless-cart.js';
Expand All @@ -25,7 +26,11 @@ export function defineCart(): CartDefinition {
search: true,
standalone: true,
recommendation: true,
buildWithProps: (engine, props) =>
buildCart(engine, {initialState: props.initialState}),
buildWithProps: (engine, props) => {
return {
...buildCart(engine, {initialState: props.initialState}),
_kind: Kind.Cart,
};
},
};
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {UniversalControllerDefinitionWithProps} from '../../../app/commerce-ssr-engine/types/common.js';
import {Kind} from '../../../app/commerce-ssr-engine/types/kind.js';
import {
Context,
buildContext,
Expand Down Expand Up @@ -27,6 +28,11 @@ export function defineContext(): ContextDefinition {
search: true,
standalone: true,
recommendation: true,
buildWithProps: (engine, props) => buildContext(engine, {options: props}),
buildWithProps: (engine, props) => {
return {
...buildContext(engine, {options: props}),
_kind: Kind.Context,
};
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
recommendationInternalOptionKey,
RecommendationOnlyControllerDefinitionWithProps,
} from '../../../app/commerce-ssr-engine/types/common.js';
import {Kind} from '../../../app/commerce-ssr-engine/types/kind.js';
import {
RecommendationsOptions,
RecommendationsState,
Expand Down Expand Up @@ -48,9 +49,19 @@ export function defineRecommendations(
options: Omit<RecommendationsOptions, 'slotId'>
) => {
const staticOptions = props.options;
return buildRecommendations(engine, {
const controller = buildRecommendations(engine, {
options: {...staticOptions, ...options},
});
const copy = Object.defineProperties(
{},
Object.getOwnPropertyDescriptors(controller)
);

Object.defineProperty(copy, '_kind', {
value: Kind.Recommendations,
});

return copy as typeof controller & {_kind: Kind.Recommendations};
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export interface RecommendationsState {
error: CommerceAPIErrorStatusResponse | null;
isLoading: boolean;
responseId: string;
productId: string;
}

export interface RecommendationsOptions {
Expand Down Expand Up @@ -133,7 +134,7 @@ export function buildRecommendations(
const {dispatch} = engine;

const {slotId, productId} = props.options;
dispatch(registerRecommendationsSlot({slotId}));
dispatch(registerRecommendationsSlot({slotId, productId}));

const recommendationStateSelector = createSelector(
(state: CommerceEngineState) => state.recommendations[slotId]!,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export const fetchMoreRecommendations = createAsyncThunk<

export interface SlotIdPayload {
slotId: string;
productId?: string;
}

export type RegisterRecommendationsSlotPayload = SlotIdPayload;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,13 @@ export const recommendationsReducer = createReducer(
builder
.addCase(registerRecommendationsSlot, (state, action) => {
const slotId = action.payload.slotId;
const productId = action.payload.productId;

if (slotId in state) {
return;
}

state[slotId] = buildRecommendationsSlice();
state[slotId] = buildRecommendationsSlice({productId});
})
.addCase(fetchRecommendations.rejected, (state, action) => {
handleError(state, action.meta.arg.slotId, action.payload);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface RecommendationsSlice {
isLoading: boolean;
responseId: string;
products: Product[];
productId: string;
}

/**
Expand All @@ -25,4 +26,5 @@ export const getRecommendationsSliceInitialState =
isLoading: false,
responseId: '',
products: [],
productId: '',
});
2 changes: 2 additions & 0 deletions packages/headless/src/ssr-commerce.index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ export type {
EngineDefinitionControllersPropsOption,
HydratedState,
OptionsTuple,
ControllerWithKind,
} from './app/commerce-ssr-engine/types/common.js';
export {Kind} from './app/commerce-ssr-engine/types/kind.js';
export type {
EngineDefinition,
InferStaticState,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import * as externalCartAPI from '@/actions/external-cart-api';
import ContextDropdown from '@/components/context-dropdown';
import {StandaloneProvider} from '@/components/providers/providers';
import {
RecommendationProvider,
StandaloneProvider,
} from '@/components/providers/providers';
import ViewedTogether from '@/components/recommendations/viewed-together';
import StandaloneSearchBox from '@/components/standalone-search-box';
import {standaloneEngineDefinition} from '@/lib/commerce-engine';
import {
recommendationEngineDefinition,
standaloneEngineDefinition,
} from '@/lib/commerce-engine';
import {NextJsNavigatorContext} from '@/lib/navigatorContextProvider';
import {defaultContext} from '@/utils/context';
import {headers} from 'next/headers';
Expand Down Expand Up @@ -38,6 +45,23 @@ export default async function ProductDescriptionPage({
},
});

const recsStaticState = await recommendationEngineDefinition.fetchStaticState(
{
controllers: {
viewedTogether: {enabled: true, productId: params.productId},
cart: {initialState: {items}},
context: {
language: defaultContext.language,
country: defaultContext.country,
currency: defaultContext.currency,
view: {
url: `https://sports.barca.group/products/${params.productId}`,
},
},
},
}
);

const resolvedSearchParams = await searchParams;
const price = Number(resolvedSearchParams.price) ?? NaN;
const name = resolvedSearchParams.name ?? params.productId;
Expand All @@ -54,6 +78,13 @@ export default async function ProductDescriptionPage({
{name} ({params.productId}) - ${price}
</p>
<br />

<RecommendationProvider
staticState={recsStaticState}
navigatorContext={navigatorContext.marshal}
>
<ViewedTogether />
</RecommendationProvider>
</StandaloneProvider>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use client';

import {useViewedTogether} from '@/lib/commerce-engine';
import ProductButtonWithImage from '../product-button-with-image';

export default function ViewedTogether() {
const {state, methods} = useViewedTogether();

return (
<>
<ul>
<h3>{state.headline}</h3>
{state.products.map((product) => (
<li key={product.ec_product_id}>
<ProductButtonWithImage methods={methods} product={product} />
</li>
))}
<button onClick={() => methods?.refresh()}>Refresh</button>
</ul>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ export default {
slotId: 'af4fb7ba-6641-4b67-9cf9-be67e9f30174',
},
}),
viewedTogether: defineRecommendations({
options: {
slotId: 'ff5d8804-d398-4dd5-b68c-6a729c66454b',
},
}),
cart: defineCart(),
searchBox: defineSearchBox(),
context: defineContext(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const {
usePagination,
usePopularBought,
usePopularViewed,
useViewedTogether,
useProductView,
useQueryTrigger,
useRecentQueriesList,
Expand Down
Loading