Skip to content

Commit

Permalink
Optimize recommendations context
Browse files Browse the repository at this point in the history
  • Loading branch information
herzog31 committed Mar 7, 2024
1 parent d0554f4 commit 9b97591
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 15 deletions.
23 changes: 18 additions & 5 deletions blocks/product-recommendations/product-recommendations.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
/* eslint-disable no-underscore-dangle */
import { performCatalogServiceQuery } from '../../scripts/commerce.js';
import { getConfigValue } from '../../scripts/configs.js';

const recommendationsQuery = `query GetRecommendations(
$pageType: PageType!
$category: String
$currentSku: String
$cartSkus: [String]
$userPurchaseHistory: [PurchaseHistory]
$userViewHistory: [ViewHistory]
) {
recommendations(
cartSkus: []
cartSkus: $cartSkus
category: $category
currentSku: $currentSku
pageType: $pageType
userPurchaseHistory: []
userPurchaseHistory: $userPurchaseHistory
userViewHistory: $userViewHistory
) {
results {
Expand Down Expand Up @@ -143,15 +146,25 @@ async function loadRecommendation(block, context) {
return;
}

const storeViewCode = await getConfigValue('commerce-store-view-code');
// Get product view history
try {
const viewHistory = window.sessionStorage.getItem('productViewHistory') || '[]';
context.userViewHistory = JSON.parse(viewHistory).map((sku) => ({ sku }));
const viewHistory = window.localStorage.getItem(`${storeViewCode}:productViewHistory`) || '[]';
context.userViewHistory = JSON.parse(viewHistory);
} catch (e) {
window.sessionStorage.removeItem('productViewHistory');
window.localStorage.removeItem('productViewHistory');
console.error('Error parsing product view history', e);

Check warning on line 156 in blocks/product-recommendations/product-recommendations.js

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}

// Get purchase history
try {
const purchaseHistory = window.localStorage.getItem(`${storeViewCode}:purchaseHistory`) || '[]';
context.userPurchaseHistory = JSON.parse(purchaseHistory);
} catch (e) {
window.localStorage.removeItem('purchaseHistory');
console.error('Error parsing purchase history', e);

Check warning on line 165 in blocks/product-recommendations/product-recommendations.js

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
}

window.adobeDataLayer.push((dl) => {
dl.push({ event: 'recs-api-request-sent', eventInfo: { ...dl.getState() } });
});
Expand Down
33 changes: 23 additions & 10 deletions scripts/commerce.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,17 +335,30 @@ export async function getProduct(sku) {
return productPromise;
}

// TODO: Listen to placeOrder events to store purchase history
// Store product view history in session storage
window.adobeDataLayer.push((dl) => {
dl.addEventListener('adobeDataLayer:change', (event) => {
const viewHistory = JSON.parse(window.sessionStorage.getItem('productViewHistory') || '[]');
if (!viewHistory.includes(event.productContext.sku)) {
viewHistory.push(event.productContext.sku);
window.sessionStorage.setItem('productViewHistory', JSON.stringify(viewHistory.slice(-10)));
}
}, { path: 'productContext' });
});
(async () => {
const storeViewCode = await getConfigValue('commerce-store-view-code');
window.adobeDataLayer.push((dl) => {
dl.addEventListener('adobeDataLayer:change', (event) => {
const key = `${storeViewCode}:productViewHistory`;
let viewHistory = JSON.parse(window.localStorage.getItem(key) || '[]');
viewHistory = viewHistory.filter((item) => item.sku !== event.productContext.sku);
viewHistory.push({ date: new Date().toISOString(), sku: event.productContext.sku });
window.localStorage.setItem(key, JSON.stringify(viewHistory.slice(-10)));
}, { path: 'productContext' });
dl.addEventListener('place-order', () => {
const shoppingCartContext = dl.getState('shoppingCartContext');
if (!shoppingCartContext) {
return;
}
const key = `${storeViewCode}:purchaseHistory`;
const purchasedProducts = shoppingCartContext.items.map((item) => item.product.sku);
const purchaseHistory = JSON.parse(window.localStorage.getItem(key) || '[]');
purchaseHistory.push({ date: new Date().toISOString(), items: purchasedProducts });
window.localStorage.setItem(key, JSON.stringify(purchaseHistory.slice(-5)));
});
});
})();

/* PLP specific functionality */

Expand Down

0 comments on commit 9b97591

Please sign in to comment.