Skip to content

Instantly share code, notes, and snippets.

@hnestmann
Created March 28, 2023 09:31
Show Gist options
  • Save hnestmann/a41a6de3cb802a1e26654c2871cf6508 to your computer and use it in GitHub Desktop.
Save hnestmann/a41a6de3cb802a1e26654c2871cf6508 to your computer and use it in GitHub Desktop.
'use strict';
exports.setApplicablePriceBooks = function () {
var CacheMgr = require('dw/system/CacheMgr');
var Site = require('dw/system/Site');
var cache = CacheMgr.getCache('customer-groups-with-pricebooks');
var cacheKey = Site.getCurrent().ID + '-customer-groups-with-pricebooks';
var customerGroupsWithPricebooks = cache.get(cacheKey, function () {
var CustomerMgr = require('dw/customer/CustomerMgr');
var groups = [];
try {
groups = CustomerMgr.getCustomerGroups();
} catch (e) {
// here we are in business manager
}
var groupsWithPricebooks = [];
for (var i = 0; i < groups.length; i += 1) {
if (groups[i].custom && groups[i].custom.pricebooks && groups[i].custom.pricebooks.length > 0) {
groupsWithPricebooks.push({
pricebookIds: groups[i].custom.pricebooks,
groupId: groups[i].ID
});
}
}
return groupsWithPricebooks;
});
var groupsWithPricebooks = [];
var sessionKey = [];
var applicablePricebooks = [];
for (var i = 0; i < customerGroupsWithPricebooks.length; i += 1) {
var isMember = customer.isMemberOfCustomerGroup(customerGroupsWithPricebooks[i].groupId);
if (isMember) {
groupsWithPricebooks.push(customerGroupsWithPricebooks[i]);
sessionKey.push(customerGroupsWithPricebooks[i].groupId);
}
}
var PriceBookMgr = require('dw/catalog/PriceBookMgr');
if (session.privacy.pricesActivatedForGroupIDsCommaSeparated !== sessionKey.join(',')) {
var Logger = require('dw/system/Logger');
// fetch pricebook
if (groupsWithPricebooks) {
for (var j = 0; j < groupsWithPricebooks.length; j += 1) {
var group = groupsWithPricebooks[j];
for (var k = 0; k < group.pricebookIds.length; k += 1) {
var pricebook = PriceBookMgr.getPriceBook(group.pricebookIds[k]);
if (pricebook) {
applicablePricebooks.push(pricebook);
} else {
Logger.warn(
'Tried to apply "{0}" based on customer group "{1}" assignment, but pricebook doesn`t exist.',
group.pricebookIds[k],
group.groupId
);
}
}
}
PriceBookMgr.setApplicablePriceBooks(applicablePricebooks);
// remember the groups for which the prices got activated to avoid executing this multiple times
session.privacy.pricesActivatedForGroupIDsCommaSeparated = sessionKey.join(',');
} else {
// on single country sites there is no group with the custom pricebook attribute, stick to the BM assigment and clear applicable pricebooks set for the session
// setting the session attribute again to avoid checking again
PriceBookMgr.setApplicablePriceBooks();
session.privacy.pricesActivatedForGroupIDsCommaSeparated = sessionKey.join(',');
}
}
};
/**
* The onRequest hook function.
*/
exports.onRequest = function () {
exports.setApplicablePriceBooks();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment