sap-commerce-cloudhybris-data-hub

Hybris convert OrderModel to CartModel


I have the following requirement:

Any user should be able to restore from My Account/Order History page the entries of any order to the active cart, so I want to know if there is any OOTB mechanism or a way to convert a OrderModel to CartModel or to merge the entries from an Order to the current cart.


Solution

  • Yes, We can convert Order model to cart model.

    There is an OOB class named DefaultCartService.java

    Call the following method in a custom class or strategy

    CartModel cartModel = cartService.clone(getTypeService().getComposedTypeForClass(CartModel.class),
                getTypeService().getComposedTypeForClass(CartEntryModel.class), order, keyGenerator.generate().toString());
    

    Here is the method in Detail:

    Parameters:

    orderType - type of newly created cart

    entryType - type of cart entry of newly created cart

    original - original order

    code - code of created cart

    @Override
    public CartModel clone(final ComposedTypeModel orderType, final ComposedTypeModel entryType,
                           final AbstractOrderModel original,
                           final String code)
    {
    
        return (CartModel) getCloneAbstractOrderStrategy().clone(orderType, entryType, original, code, CartModel.class,
                CartEntryModel.class);
    }
    

    To get the cart entries (converted) from Order can be achieved using CloneAbstractOrderStrategy.java

    List<CartEntryModel> cartEntries = cloneOrderStrategy.cloneEntries(getTypeService().getComposedTypeForClass(CartEntryModel.class), orderModel)
    

    So, for Cloning Order to cart and its vice versa can be achieved by CloneAbstractOrderStrategy.java.

    Please take a look of the class for better understanding!