November Happy Hour will be moved to Thursday December 5th.

MigrateCarts: clearing the logged user cart

Vote:
 

Hi,

I use my own version of ProfileMigrator to merge the cart when the user logs in.

We want to clear the cart of the user we want to log in before merging the anonymous user's cart.

With the code bellow, it works but we have a specific problem.

If a user adds items then log in, the cart is merged and everything's fine.

If I go back to an anonymous cart and then try to log in with the same user name, the carts are merged but when I check in the OrderGroup table, the CustomerName field is empty. So we have a couple of records with no CustomerName in our table.

Is this the correct way to clear the cart before merging the anonymous one or is there a cleaner way?

public class OurProfileMigrator: ProfileMigrator
{
private readonly OurCartMigrator _cartMigrator;

public OurProfileMigrator(IOrderRepository orderRepository, ICurrentMarket currentMarket, CartMigrator cartMigrator, ICartService cartService) : base(orderRepository, currentMarket, cartMigrator)
{
_cartMigrator = new OurCartMigrator(orderRepository, cartService);
}

public override void MigrateCarts(Guid anonymousId)
{
CustomerContact customerContact = PrincipalInfo.CurrentPrincipal.GetCustomerContact();
if ((customerContact != null ? (!customerContact.PrimaryKeyId.HasValue ? 1 : 0) : 1) != 0)
return;

//We clear the logged user's cart before merging the anonymous
CartHelper cartHelperGuest = new CartHelper(Cart.DefaultName, anonymousId);

if (cartHelperGuest != null && !cartHelperGuest.IsEmpty)
{
CartHelper cartHelperRegistered = new CartHelper(Cart.DefaultName, customerContact.PrimaryKeyId.Value);

if (cartHelperRegistered != null && cartHelperGuest.Cart != null && cartHelperRegistered.Cart != null && cartHelperGuest.Cart.Id != cartHelperRegistered.Cart.Id)
{
cartHelperRegistered.Cart.Delete();
cartHelperRegistered.Cart.AcceptChanges();
}

_cartMigrator.MigrateCarts(anonymousId, (Guid)customerContact.PrimaryKeyId.Value);
}
}
}
#198606
Oct 31, 2018 21:47
* 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.