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

LYNX-671: Personalisation implementation in boilerplate #288

Merged
merged 2 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions blocks/dynamic-block/dynamic-block.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.dynamic-block > div:not(:last-child) {
display: none;
}
61 changes: 61 additions & 0 deletions blocks/dynamic-block/dynamic-block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { events } from '@dropins/tools/event-bus.js';
import * as Cart from '@dropins/storefront-cart/api.js';
import { readBlockConfig } from '../../scripts/aem.js';
import { getConfigValue } from '../../scripts/configs.js';

const blocks = [];

const executeQuery = async (query, variables) => {
const apiCall = new URL(await getConfigValue('commerce-core-endpoint'));

apiCall.searchParams.append('query', query.replace(/(?:\r\n|\r|\n|\t|[\s]{4})/g, ' ').replace(/\s\s+/g, ' '));
apiCall.searchParams.append('variables', variables ? JSON.stringify(variables) : null);

const response = await fetch(apiCall, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
});

return response.ok ? (await response.json()).data : null;
};

const getCustomerSegments = async () => {
const query = `
query CUSTOMER_SEGMENTS($cartId: String!){
customerSegments(cartId: $cartId) {
name
}
}
`;
try {
const segments = await executeQuery(
query,
{ cartId: Cart.getCartDataFromCache().id },
);
if (segments === null) {
return [];
}
return segments?.customerSegments?.map((segment) => segment.name);
} catch (error) {
console.error('Could not retrieve customer segments', error);
}
return [];
};

const updateDynamicBlocksVisibility = async () => {
const customerSegments = await getCustomerSegments();
blocks.forEach((blockConfig, index) => {
const { segment } = blockConfig;
const block = document.querySelector(`[data-dynamic-block-key="${index}"]`);
block.style.display = customerSegments.includes(segment) ? '' : 'none';
});
};

export default function decorate(block) {
block.style.display = 'none';
blocks.push(readBlockConfig(block));
block.setAttribute('data-dynamic-block-key', blocks.length - 1);
}

events.on('cart/initialized', () => { updateDynamicBlocksVisibility(); });
events.on('cart/updated', () => { updateDynamicBlocksVisibility(); });