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

Release v0.49.0 #925

Merged
merged 14 commits into from
Oct 19, 2023
Merged
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
31 changes: 30 additions & 1 deletion docs/INTEGRATION_RECOMMENDATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ Context variables may be applied to individual recommendation profiles similar t
| product | current product sku | product detail page | used to identify the current product being viewed |
| cart | array (or function that returns an array) of current cart skus | all | optional method of setting cart contents |
| options.siteId | global siteId overwrite | all | optional global siteId overwrite |
| options.categories | category path | all | optional category identifier to restrict recommendations |
| options.categories | array of category path strings | all | optional category identifiers used in category trending recommendation profiles |
| options.brands | array of brand strings | all | optional brand identifiers used in brand trending recommendation profiles |
| options.branch | template branch overwrite | all | optional branch overwrite for recommendations template (advanced usage) |
| options.filters | array of filters | all | optional recommendation filters |
| options.batched | boolean (default: `true`)| all | only applies to recommendation context, optional disable profile from being batched in a single request, can also be set globally [via config](https://github.com/searchspring/snap/tree/main/packages/snap-controller/src/Recommendation) |
| options.order | number | all | optional order number for recommendation params to be added to the batched request. Profiles that do not specify an order will be placed at the end, in the occurrence they appear in the DOM.
| options.limit | number (default: 20, max: 20) | all | optional maximum number of results to display, can also be set globally [via config globals](https://github.com/searchspring/snap/tree/main/packages/snap-controller/src/Recommendation) |
Expand Down Expand Up @@ -73,4 +75,31 @@ Having multiple scripts batched using the order context variable
order: 1
};
</script>
```

### Filters
The example shown below will filter the recommendations for products matching color: blue, & red, and price range 0 - 20.

```html
<script type="searchspring/recommend" profile="customers-also-bought">
options = {
filters: [
{
type: 'value',
field: 'color',
value: 'blue'
},
{
type: 'value',
field: 'color',
value: 'red'
},
{
type: 'range',
field: 'price',
value: { low: 0, high: 20 }
}
]
}
</script>
```
7 changes: 7 additions & 0 deletions docs/documents.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,13 @@ var documents = [
url: './packages/snap-toolbox/src/getContext/README.md',
searchable: true,
},
{
label: 'Until',
route: '/package-toolbox-until',
type: 'markdown',
url: './packages/snap-toolbox/src/until/README.md',
searchable: true,
},
{
label: 'Typedocs',
type: 'external',
Expand Down
81 changes: 81 additions & 0 deletions packages/snap-client/src/Client/apis/Recommend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,41 @@ describe('Recommend Api', () => {
requestMock.mockReset();
});

it('batchRecommendations handles multiple brands as expected', async () => {
const api = new RecommendAPI(new ApiConfiguration({}));

const requestMock = jest
.spyOn(global.window, 'fetch')
.mockImplementation(() => Promise.resolve({ status: 200, json: () => Promise.resolve(mockData.recommend()) } as Response));

const GETRequestUrl = `https://8uyt2m.a.searchspring.io/boost/8uyt2m/recommend?tags=similar&tags=crossSell&limits=14&limits=10&brands=shirts&brands=pants&brands=pants2&siteId=8uyt2m&lastViewed=marnie-runner-2-7x10&lastViewed=ruby-runner-2-7x10&lastViewed=abbie-runner-2-7x10&lastViewed=riley-4x6&lastViewed=joely-5x8&lastViewed=helena-4x6&lastViewed=kwame-4x6&lastViewed=sadie-4x6&lastViewed=candice-runner-2-7x10&lastViewed=esmeray-4x6&lastViewed=camilla-230x160&lastViewed=candice-4x6&lastViewed=sahara-4x6&lastViewed=dayna-4x6&lastViewed=moema-4x6&product=marnie-runner-2-7x10`;

//shirt category
// @ts-ignore
api.batchRecommendations({
tags: ['similar'],
brands: ['shirts'],
limits: 14,
batched: true,
...batchParams,
});
//pants category
// @ts-ignore
api.batchRecommendations({
tags: ['crossSell'],
brands: ['pants', 'pants2'],
limits: 10,
batched: true,
...batchParams,
});

//add delay for paramBatch.timeout
await wait(250);

expect(requestMock).toHaveBeenCalledWith(GETRequestUrl, GETParams);
requestMock.mockReset();
});

it('batchRecommendations handles order prop as expected', async () => {
const api = new RecommendAPI(new ApiConfiguration({}));

Expand Down Expand Up @@ -286,6 +321,35 @@ describe('Recommend Api', () => {
requestMock.mockReset();
});

it('batchRecommendations handles filters expected', async () => {
const api = new RecommendAPI(new ApiConfiguration({}));

const requestMock = jest
.spyOn(global.window, 'fetch')
.mockImplementation(() => Promise.resolve({ status: 200, json: () => Promise.resolve(mockData.recommend()) } as Response));

// @ts-ignore
api.batchRecommendations({
tags: ['crossSell'],
limits: 10,
filters: [
{
type: 'value',
field: 'color',
value: 'red',
},
],
...batchParams,
});

//add delay for paramBatch.timeout
await wait(250);
const reorderedGetURL =
'https://8uyt2m.a.searchspring.io/boost/8uyt2m/recommend?tags=crossSell&limits=10&siteId=8uyt2m&lastViewed=marnie-runner-2-7x10&lastViewed=ruby-runner-2-7x10&lastViewed=abbie-runner-2-7x10&lastViewed=riley-4x6&lastViewed=joely-5x8&lastViewed=helena-4x6&lastViewed=kwame-4x6&lastViewed=sadie-4x6&lastViewed=candice-runner-2-7x10&lastViewed=esmeray-4x6&lastViewed=camilla-230x160&lastViewed=candice-4x6&lastViewed=sahara-4x6&lastViewed=dayna-4x6&lastViewed=moema-4x6&product=marnie-runner-2-7x10&filter.color=red';
expect(requestMock).toHaveBeenCalledWith(reorderedGetURL, GETParams);
requestMock.mockReset();
});

it('batchRecommendations resolves in right order with order prop', async () => {
const api = new RecommendAPI(new ApiConfiguration({}));
const response = mockData.file('recommend/results/8uyt2m/ordered.json');
Expand Down Expand Up @@ -385,6 +449,11 @@ describe('Recommend Api', () => {
'moema-4x6',
],
product: 'marnie-runner-2-7x10',
filters: [
{ field: 'color', type: '=', values: ['blue'] },
{ field: 'price', type: '>=', values: [0] },
{ field: 'price', type: '<=', values: [20] },
],
}),
};
const POSTRequestUrl = 'https://8uyt2m.a.searchspring.io/boost/8uyt2m/recommend';
Expand All @@ -398,6 +467,18 @@ describe('Recommend Api', () => {
api.batchRecommendations({
tags: [i.toString()],
...batchParams,
filters: [
{
type: 'value',
field: 'color',
value: 'blue',
},
{
type: 'range',
field: 'price',
value: { low: 0, high: 20 },
},
],
batched: true,
});
}
Expand Down
41 changes: 34 additions & 7 deletions packages/snap-client/src/Client/apis/Recommend.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { API, ApiConfiguration } from './Abstract';
import { HTTPHeaders } from '../../types';
import { HTTPHeaders, PostRecommendRequestFiltersModel, PostRecommendRequestModel, GetRecommendRequestModel } from '../../types';
import { AppMode, charsParams } from '@searchspring/snap-toolbox';

import { transformRecommendationFiltersGet, transformRecommendationFiltersPost } from '../transforms';
import { ProfileRequestModel, ProfileResponseModel, RecommendRequestModel, RecommendResponseModel } from '../../types';

class Deferred {
Expand Down Expand Up @@ -74,7 +74,7 @@ export class RecommendAPI extends API {
// now that the requests are in proper order, map through them
// and build out the batches
batch.entries.map((entry) => {
const { tags, categories, ...otherParams } = entry.request;
const { tags, categories, brands, ...otherParams } = entry.request;
let limits = entry.request.limits;

if (!limits) {
Expand All @@ -96,6 +96,14 @@ export class RecommendAPI extends API {
}
}

if (brands) {
if (!batch.request.brands) {
batch.request.brands = Array.isArray(brands) ? brands : [brands];
} else {
batch.request.brands = batch.request.brands.concat(brands);
}
}

batch.request.limits = (batch.request.limits as number[]).concat(limits);
batch.request = { ...batch.request, ...otherParams };
});
Expand All @@ -110,9 +118,28 @@ export class RecommendAPI extends API {
if (batch.request['product']) {
batch.request['product'] = batch.request['product'].toString();
}
response = await this.postRecommendations(batch.request as RecommendRequestModel);

//transform filters here
if (batch.request.filters) {
(batch.request as PostRecommendRequestModel)['filters'] = transformRecommendationFiltersPost(
batch.request.filters
) as PostRecommendRequestFiltersModel[];
}

response = await this.postRecommendations(batch.request as PostRecommendRequestModel);
} else {
response = await this.getRecommendations(batch.request as RecommendRequestModel);
if (batch.request.filters) {
const filters = transformRecommendationFiltersGet(batch.request.filters);
if (filters) {
Object.keys(filters).map((filter) => {
const _filter = filter as `filter.${string}`;
(batch.request as GetRecommendRequestModel)[_filter] = filters[_filter as keyof typeof filters];
});
}
}

delete batch.request.filters;
response = await this.getRecommendations(batch.request as GetRecommendRequestModel);
}

batch.entries?.forEach((entry, index) => {
Expand All @@ -128,7 +155,7 @@ export class RecommendAPI extends API {
return deferred.promise;
}

async getRecommendations(queryParameters: RecommendRequestModel): Promise<RecommendResponseModel> {
async getRecommendations(queryParameters: GetRecommendRequestModel): Promise<RecommendResponseModel> {
const headerParameters: HTTPHeaders = {};

const siteId = queryParameters.siteId;
Expand All @@ -147,7 +174,7 @@ export class RecommendAPI extends API {
return response as unknown as RecommendResponseModel;
}

async postRecommendations(requestParameters: RecommendRequestModel): Promise<RecommendResponseModel> {
async postRecommendations(requestParameters: PostRecommendRequestModel): Promise<RecommendResponseModel> {
const headerParameters: HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';

Expand Down
2 changes: 2 additions & 0 deletions packages/snap-client/src/Client/transforms/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export * from './searchRequest';
export * from './searchResponse';
export * from './suggestResponse';
export * from './recommendationFiltersGet';
export * from './recommendationFiltersPost';
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { transformRecommendationFiltersGet } from './recommendationFiltersGet';

describe('transformRecommendationFiltersGet', () => {
it('transformRecommendationFiltersGet works', async () => {
const filters = [
{ type: 'value' as const, field: 'color', value: 'blue' },
{ type: 'value' as const, field: 'color', value: 'red' },
{ type: 'value' as const, field: 'color', value: 'green' },
{ type: 'range' as const, field: 'price', value: { high: 20, low: 0 } },
];
const tranformedFilters = transformRecommendationFiltersGet(filters);
expect(tranformedFilters).toStrictEqual({ 'filter.color': ['blue', 'red', 'green'], 'filter.price.high': [20], 'filter.price.low': [0] });
});

it('transformRecommendationFiltersGet works with single high or low range value', async () => {
const filterHigh = [{ type: 'range' as const, field: 'price', value: { high: 20 } }];
const filterLow = [
//also works with 0
{ type: 'range' as const, field: 'price', value: { low: 0 } },
];

const tranformedFilterHigh = transformRecommendationFiltersGet(filterHigh);
expect(tranformedFilterHigh).toStrictEqual({ 'filter.price.high': [20] });

const tranformedFilterLow = transformRecommendationFiltersGet(filterLow);
expect(tranformedFilterLow).toStrictEqual({ 'filter.price.low': [0] });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { RecommendationRequestFilterModel } from '../../types';

export const transformRecommendationFiltersGet = (filters: RecommendationRequestFilterModel[]) => {
const filterArray: {
[filter: `filter.${string}`]: (string | number)[];
} = {};

filters.map((filter) => {
if (filter.type == 'value') {
//check if filterArray contains a filter for this value already
if (filterArray[`filter.${filter.field}`]) {
filterArray[`filter.${filter.field}`].push(filter.value);
} else {
//else create a new one
filterArray[`filter.${filter.field}`] = [filter.value];
}
} else if (filter.type == 'range') {
if (typeof filter.value.low == 'number') {
filterArray[`filter.${filter.field}.low`] = [filter.value.low];
}
if (typeof filter.value.high == 'number') {
filterArray[`filter.${filter.field}.high`] = [filter.value.high];
}
}
});
return filterArray;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { transformRecommendationFiltersPost } from './recommendationFiltersPost';

describe('transformRecommendationFiltersPost', () => {
it('transformRecommendationFiltersPost works as expected', async () => {
const filters = [
{ type: 'value' as const, field: 'color', value: 'blue' },
{ type: 'value' as const, field: 'color', value: 'red' },
{ type: 'value' as const, field: 'color', value: 'green' },
{ type: 'range' as const, field: 'price', value: { high: 20, low: 0 } },
];

const tranformedFilters = transformRecommendationFiltersPost(filters);
expect(tranformedFilters).toStrictEqual([
{ field: 'color', type: '=', values: ['blue', 'red', 'green'] },
{ field: 'price', type: '>=', values: [0] },
{ field: 'price', type: '<=', values: [20] },
]);
});

it('transformRecommendationFiltersPost works with single high or low range value', async () => {
const filterHigh = [{ type: 'range' as const, field: 'price', value: { high: 20 } }];
const filterLow = [{ type: 'range' as const, field: 'price', value: { low: 0 } }];

const tranformedFilterHigh = transformRecommendationFiltersPost(filterHigh);
expect(tranformedFilterHigh).toStrictEqual([{ field: 'price', type: '<=', values: [20] }]);

const tranformedFilterLow = transformRecommendationFiltersPost(filterLow);
expect(tranformedFilterLow).toStrictEqual([{ field: 'price', type: '>=', values: [0] }]);
});
});
Loading
Loading