mergeCartResponse.setMerged(false); // We no longer merge items, only transition cart states
// We need to make sure that the old, saved customer cart is reconstructed with availability concerns in mind
ReconstructCartResponse reconstructCartResponse = reconstructCart(customer, false);
mergeCartResponse.setRemovedItems(reconstructCartResponse.getRemovedItems());
Order customerCart = reconstructCartResponse.getOrder();
if (anonymousCart != null && customerCart != null && anonymousCart.equals(customerCart)) {
// The carts are the same, use either ensuring it's owned by the current customer
setNewCartOwnership(anonymousCart, customer);
mergeCartResponse.setOrder(anonymousCart);
} else if (anonymousCart == null || anonymousCart.getOrderItems().size() == 0) {
// The anonymous cart is of no use, use the customer cart
mergeCartResponse.setOrder(customerCart);
// The anonymous cart is owned by a different customer, so there is no chance for a single customer to have
// multiple IN_PROCESS carts. We can go ahead and clean up this empty cart anyway since it's empty
if (anonymousCart != null) {
orderService.cancelOrder(anonymousCart);
}
} else if (customerCart == null || customerCart.getOrderItems().size() == 0) {
// Delete the saved customer order since it is completely empty anyway. We do not want 2 IN_PROCESS orders
// hanging around
if (customerCart != null) {
orderService.cancelOrder(customerCart);
}
// The customer cart is of no use, use the anonymous cart
setNewCartOwnership(anonymousCart, customer);
mergeCartResponse.setOrder(anonymousCart);
} else {
// Both carts have some items. The anonymous cart will always be the more recent one by definition
// Save off the old customer cart and use the anonymous cart
setSavedCartAttributes(customerCart);
orderService.save(customerCart, false);
setNewCartOwnership(anonymousCart, customer);
mergeCartResponse.setOrder(anonymousCart);
}
if (mergeCartResponse.getOrder() != null) {
Order savedCart = orderService.save(mergeCartResponse.getOrder(), priceOrder);
mergeCartResponse.setOrder(savedCart);
}
return mergeCartResponse;
}