Search code examples
springsap-commerce-cloud

How to add cart entries in newly-created CartModel?


I used following code to create a cart and add one cartEntry inside this CartModel:

final CartModel cartModel = cartFactory.createCart() ;
OrderEntryModel orderEntryModel = new OrderEntryModel();
List<AbstractOrderEntryModel> entryModel = new ArrayList<>();
final ProductModel product = productService.getProductForCode(productCode); // came from another method
orderEntryModel.setProduct(product);
entryModel.add(orderEntryModel);
cartModel.setEntries(entryModel);
cartModel.setUser(userService.getCurrentUser());
cartService.setSessionCart(cartModel);

When I try to get this cart from session, apply this cart, and pass this cart to next another OOTB method, I get the following exception:

DefultAbstractOrderEntryPreparer@1090ef7e]: unexpected preparer error: null] with root cause
java.lang.NullPointerException
    at de.hybris.platform.order.interceptors.DefaultAbstractOrderEntryPreparer.onPrepare(DefaultAbstractOrderEntryPreparer.java:97)

After debugging, I got to know that this issue occurs because I am adding order entries in a different way than what we used in a normal checkout flow (first code block , third last line) .

So, is there any OOTB method or any other way to create an orderEntry and add it to a newly-created cart?

I checked for normal cart created during Checkout flow, and this issue doesn't happen. So, I came to a conclusion that this occurs because of following code from the first code block:

OrderEntryModel orderEntryModel = new OrderEntryModel();
List<AbstractOrderEntryModel> entryModel = new ArrayList<>();
final ProductModel product = productService.getProductForCode(productCode); // came from another method
orderEntryModel.setProduct(product);
entryModel.add(orderEntryModel);
cartModel.setEntries(entryModel);

Solution

  • There is a standard service called cartService, that as addNewEntry method.

            final CartModel cartModel = cartFactory.createCart();
            final ProductModel product = productService.getProductForCode(productCode); // came from another method
            getCartService().addNewEntry(cartModel, product, 1, null);
            cartModel.setUser(userService.getCurrentUser());
            cartService.setSessionCart(cartModel);