Filter your commerce campaigns for access

A customer wanted to have access rights on the campaigns in Commerce, so marketing managers for one market could not make changes to the campaigns for other markets. As this is not possible out of the box, I tried to find another way.

I remembered a post by David Knipe about restricting access to markets for specific users.  So I changed and extended his code a bit to filter the visible campaigns based on the market a user has access to.

NOTE: David used the market name for the usergroup, I needed to use the marketId.

I added another helper method to the MarketAccessRightsHelper, to use the marketId for checking the user role which was needed as a campaign uses the marketId for checking the market it belongs to.

The overview of the campaigns uses a content query, GetSalesCampaignChildrenQuery, so I decided to make a custom implemementation for it. The thing I needed to override was GetChildrenByType, to which I applied a filter, checking on if the user is in a group that has access to the market.

NOTE: It is a bit of a hack, as the facet count is not filtered. So if there are multiple campaigns, the count will be off.

 

protected override IEnumerable GetChildrenByType(
    Type type,
    ContentReference parentLink,
    ILanguageSelector selector)
{
    if (type == typeof(SalesCampaign) && this.marketAccessRightsHelper.IsFilteredMarketsRequest())
    {
        return base.GetChildrenByType(type, parentLink, selector).OfType().Where(
                c => this.marketAccessRightsHelper.UserHasAccessToMarket(c.TargetMarket));
    }

    return base.GetChildrenByType(type, parentLink, selector);
}

I overrode the default implementation in the initializable module like this

context
.StructureMap()
    .Configure(x =>
        {x.ForConcreteType().Configure.InterceptWith(
                    new DecoratorInterceptor(
                        typeof(GetSalesCampaignChildrenQuery),
                        typeof(GetSalesCampaignChildrenQueryFiltered)));
        });

This filters the campaigns in the overview based on the “access rights”. It also filters the the list of markets in the left menu.

The complete code can be found in a gist, which is a fork of David’s gist.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s