Search code examples
sap-commerce-cloud

How to delete CartEntries from hybris?


I need to create a CronJob that deletes Cart Entries of a specific type. I have allready found all entries with the needed PK, but I still cant delete them.

I found on the web that I cant use the FlexibleSearchQuery for that. Also I did not found any method for that in the CartEntryService. Where is the delete logic?


Solution

  • You have to use modelService to remove any model from the database. In your case, all you need to do is pass list of cartEntryModel to getModelService().removeAll(list)

    Look at the DefaultCartService updateQuantities method, basically this method is invoked with 0 quantity for the cart entry which the user tries to remove from the cart.

        final Collection<CartEntryModel> toRemove = new LinkedList<CartEntryModel>();
        final Collection<CartEntryModel> toSave = new LinkedList<CartEntryModel>();
        for (final Map.Entry<CartEntryModel, Long> e : getEntryQuantityMap(cart, quantities).entrySet())
        {
            final CartEntryModel cartEntry = e.getKey();
            final Long quantity = e.getValue();
            if (quantity == null || quantity.longValue() < 1)
            {
                toRemove.add(cartEntry);
            }
            else
            {
                cartEntry.setQuantity(quantity);
                toSave.add(cartEntry);
            }
        }
        getModelService().removeAll(toRemove);
    

    You can achieve the same form using a groovy script. Refer create a Cronjob using Groovy script in SAP Hybris

    Groovy Script example:

    import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
    import de.hybris.platform.servicelayer.model.ModelService;
    import de.hybris.platform.core.model.user.CartEntryModel;
    import de.hybris.platform.servicelayer.search.SearchResult;
    import org.apache.commons.collections.CollectionUtils;
    
    
    
    def removeCartEntries()
    
     {
      final SearchResult<CartEntryModel> searchResults = flexibleSearchService.search("query to get the list of cartentries")
      if (searchResults != null && CollectionUtils.isNotEmpty(searchResults.getResult())) {
          modelService.removeAll(searchResults.getResult());
       }
     }
    removeCartEntries();
    
    println "done";