Apply order discount for specific user while signed in with another account e.g Customer Service

Vote:
 

Hello

We are using Commerce 12.8.1

I'm looking for how to apply discounts for an order as a specific customer.

We are using built in order discounts at the moment, and the customer can apply for a discount without issues during the normal order flow.

My question is how to handle this when the order is opened by customer service after order completion, and items are changed in the placed order.

Is there a way to recalcualte discounts for the customer who placed the original order, and not use the context of the current signed in user? 

As I understand it, promotions are calcualted using the current user context? 

Best regards,

Ludvig Stenstrom

#202053
Edited, Mar 12, 2019 16:49
Vote:
 

I think you can try to impersonate that user at the time that re-calculateing discount like this:

//Before re-calculating discount

var user = _userManager.FindByEmail([customer's username]);
if (user != null)
{
    var adminUserName = User.Identity.GetUserName();
    _signInManager.SignIn(user, false, false);

    //Do re-calculate discount here

    //Back to customer service's user
        var adminUser = _userManager.FindByEmail(adminUsername);
        if (adminUser != null)
            _signInManager.SignIn(adminUser, false, false);
}

This sample code is referenced in Quicksilver B2B project https://github.com/episerver/QuicksilverB2B/blob/master/Sources/EPiServer.Reference.Commerce.Site/Features/Users/Controllers/UsersPageController.cs

#202062
Edited, Mar 13, 2019 3:02
Vote:
 

Hello Binh and thanks for the info! 

I ended up doing it like this for our project, but your solution helped much on the way!

var currentPrinciapl = PrincipalInfo.CurrentPrincipal;
var coupons = order.GetFirstForm().CouponCodes.ToArray();
try
{					
	IPrincipal cartUser = PrincipalInfo.AnonymousPrincipal;             
	var customer = _customerFacade.Service.GetContactById(order.CustomerId);
	if (customer != null)
	{
		var user = Membership.GetUser(customer.Email);
		var _userImpersonation = ServiceLocator.Current.GetInstance<IUserImpersonation>();
		cartUser = _userImpersonation.CreatePrincipal(user.UserName);
	}                
	PrincipalInfo.CurrentPrincipal = cartUser;                
	foreach (var coupon in coupons)
	{
		AddCouponCode(order, coupon);
	}
	order.ApplyDiscounts(_promotionEngine.Service, new PromotionEngineSettings());
}
catch (Exception e)
{
	_log.Error($"Failed to calcualte discounts for order {order.OrderLink.OrderGroupId}. Message: {e.Message}");
}
PrincipalInfo.CurrentPrincipal = currentPrinciapl;
#202071
Edited, Mar 13, 2019 12:03
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.