Search in sources :

Example 1 with QuantityBasedRule

use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method findContainedRuleIfApplicable.

public static Object findContainedRuleIfApplicable(Object rule) {
    Object response = null;
    for (Field field : getAllFields(rule.getClass())) {
        field.setAccessible(true);
        Object test = null;
        try {
            test = field.get(rule);
        } catch (IllegalAccessException e) {
            throw ExceptionHelper.refineException(e);
        }
        if (test != null && (test instanceof SimpleRule || test instanceof QuantityBasedRule)) {
            response = test;
            break;
        }
    }
    return response;
}
Also used : Field(java.lang.reflect.Field) SimpleRule(org.broadleafcommerce.common.rule.SimpleRule) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule)

Example 2 with QuantityBasedRule

use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method convertQuantityBasedRuleToJson.

protected Property convertQuantityBasedRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, Collection<QuantityBasedRule> quantityBasedRules, String jsonProp, String fieldService) {
    int k = 0;
    Entity[] targetItemCriterias = new Entity[quantityBasedRules.size()];
    for (QuantityBasedRule quantityBasedRule : quantityBasedRules) {
        Property[] properties = new Property[4];
        Property mvelProperty = new Property();
        mvelProperty.setName("matchRule");
        mvelProperty.setValue(quantityBasedRule.getMatchRule());
        Property quantityProperty = new Property();
        quantityProperty.setName("quantity");
        quantityProperty.setValue(quantityBasedRule.getQuantity().toString());
        Property idProperty = new Property();
        idProperty.setName("id");
        Long id = quantityBasedRule.getId();
        id = transformId(id, quantityBasedRule);
        idProperty.setValue(String.valueOf(id));
        Object containedRule = findContainedRuleIfApplicable(quantityBasedRule);
        Property containedIdProperty = new Property();
        if (containedRule != null) {
            containedIdProperty.setName("containedId");
            EntityManager em = PersistenceManagerFactory.getDefaultPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
            Long containedId = (Long) em.unwrap(Session.class).getIdentifier(containedRule);
            containedId = transformId(containedId, containedRule);
            containedIdProperty.setValue(String.valueOf(containedId));
        }
        properties[0] = mvelProperty;
        properties[1] = quantityProperty;
        properties[2] = idProperty;
        properties[3] = containedIdProperty;
        Entity criteria = new Entity();
        criteria.setProperties(properties);
        targetItemCriterias[k] = criteria;
        k++;
    }
    String json;
    try {
        DataWrapper oiWrapper = translator.createRuleData(targetItemCriterias, "matchRule", "quantity", "id", "containedId", ruleBuilderFieldServiceFactory.createInstance(fieldService));
        json = mapper.writeValueAsString(oiWrapper);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Property p = new Property();
    p.setName(jsonProp);
    p.setValue(json);
    return p;
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) EntityManager(javax.persistence.EntityManager) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 3 with QuantityBasedRule

use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method updateQuantityRule.

protected boolean updateQuantityRule(EntityManager em, DataDTOToMVELTranslator translator, String entityKey, String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList, Class<?> memberType, Object parent, String mappedBy, Property property) {
    boolean dirty = false;
    if (!StringUtils.isEmpty(jsonPropertyValue)) {
        // avoid lazy init exception on the criteria list for criteria created during an add
        criteriaList.size();
        DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
        if (dw != null && StringUtils.isEmpty(dw.getError())) {
            List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
            for (DataDTO dto : dw.getData()) {
                if (dto.getPk() != null && !CollectionUtils.isEmpty(criteriaList)) {
                    checkId: {
                        // Update Existing Criteria
                        for (QuantityBasedRule quantityBasedRule : criteriaList) {
                            // make compatible with enterprise module
                            boolean isParentRelated = sandBoxHelper.isRelatedToParentCatalogIds(quantityBasedRule, dto.getPk());
                            boolean isMatch = isParentRelated || dto.getPk().equals(quantityBasedRule.getId());
                            if (isMatch) {
                                String mvel;
                                // don't update if the data has not changed
                                if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
                                    dirty = true;
                                }
                                try {
                                    mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService);
                                    if (!quantityBasedRule.getMatchRule().equals(mvel)) {
                                        dirty = true;
                                    }
                                } catch (MVELTranslationException e) {
                                    throw new RuntimeException(e);
                                }
                                if (!dirty && extensionManager != null) {
                                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                                    ExtensionResultStatusType result = extensionManager.getProxy().establishDirtyState(quantityBasedRule, resultHolder);
                                    if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
                                        dirty = resultHolder.getResult();
                                    }
                                }
                                if (dirty) {
                                    // pre-merge (can result in a clone for enterprise)
                                    quantityBasedRule = em.merge(quantityBasedRule);
                                    // update the quantity based rule
                                    quantityBasedRule.setQuantity(dto.getQuantity());
                                    quantityBasedRule.setMatchRule(mvel);
                                    quantityBasedRule = em.merge(quantityBasedRule);
                                }
                                updatedRules.add(quantityBasedRule);
                                break checkId;
                            }
                        }
                        throw new IllegalArgumentException("Unable to update the rule of type (" + memberType.getName() + ") because an update was requested for id (" + dto.getPk() + "), which does not exist.");
                    }
                } else {
                    // Create a new Criteria
                    QuantityBasedRule quantityBasedRule;
                    try {
                        quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
                        quantityBasedRule.setQuantity(dto.getQuantity());
                        quantityBasedRule.setMatchRule(ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService));
                        if (StringUtils.isEmpty(quantityBasedRule.getMatchRule()) && !StringUtils.isEmpty(dw.getRawMvel())) {
                            quantityBasedRule.setMatchRule(dw.getRawMvel());
                        }
                        PropertyUtils.setNestedProperty(quantityBasedRule, mappedBy, parent);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    em.persist(quantityBasedRule);
                    dto.setPk(quantityBasedRule.getId());
                    Object contained = findContainedRuleIfApplicable(quantityBasedRule);
                    if (contained != null) {
                        dto.setContainedPk((Long) em.unwrap(Session.class).getIdentifier(contained));
                    }
                    if (extensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        extensionManager.getProxy().postAdd(quantityBasedRule, resultHolder);
                        if (resultHolder.getResult() != null) {
                            quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
                        }
                    }
                    if (cascadeExtensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        cascadeExtensionManager.getProxy().postCascadeAdd(quantityBasedRule, dto, resultHolder);
                        if (resultHolder.getResult() != null) {
                            quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
                        }
                    }
                    updatedRules.add(quantityBasedRule);
                    dirty = true;
                }
            }
            // if an item was not included in the comprehensive submit from the client, we can assume that the
            // listing was deleted, so we remove it here.
            Iterator<QuantityBasedRule> itr = criteriaList.iterator();
            // Since this class explicitly removes the quantity based rule - we must also preserve the id of the element
            // as the CacheInvalidationProducer will need this in order to remove each collection member cache instance as well.
            BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
            context.getAdditionalProperties().put("deletedQuantityBasedRules", new HashSet<QuantityBasedRule>());
            while (itr.hasNext()) {
                checkForRemove: {
                    QuantityBasedRule original = itr.next();
                    for (QuantityBasedRule quantityBasedRule : updatedRules) {
                        Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                        boolean isMatch = original.getId().equals(id) || original.getId().equals(quantityBasedRule.getId());
                        if (isMatch) {
                            break checkForRemove;
                        }
                    }
                    ((Set<QuantityBasedRule>) context.getAdditionalProperties().get("deletedQuantityBasedRules")).add(original);
                    em.remove(original);
                    itr.remove();
                    dirty = true;
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json;
            try {
                json = mapper.writeValueAsString(dw);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            property.setValue(json);
        }
    }
    return dirty;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) ArrayList(java.util.ArrayList) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Session(org.hibernate.Session)

Example 4 with QuantityBasedRule

use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method extractQuantityRule.

protected void extractQuantityRule(ExtractValueRequest extractValueRequest, ObjectMapper mapper, MVELToDataWrapperTranslator translator) {
    if (extractValueRequest.getRequestedValue() != null) {
        if (extractValueRequest.getRequestedValue() instanceof Collection) {
            // these quantity rules are in a list - this is a special, valid case for quantity rules
            Property jsonProperty = convertQuantityBasedRuleToJson(translator, mapper, (Collection<QuantityBasedRule>) extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getName() + "Json", extractValueRequest.getMetadata().getRuleIdentifier());
            extractValueRequest.getProps().add(jsonProperty);
        } else {
            // TODO support a single quantity based rule
            throw new UnsupportedOperationException("RULE_WITH_QUANTITY type is currently only supported" + "on collection fields. A single field with this type is not currently supported.");
        }
    }
}
Also used : QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) Collection(java.util.Collection) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 5 with QuantityBasedRule

use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method populateQuantityRule.

protected boolean populateQuantityRule(PopulateValueRequest populateValueRequest, Serializable instance) throws FieldNotAvailableException, IllegalAccessException {
    String prop = populateValueRequest.getProperty().getName();
    Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop);
    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
    if (oneToMany == null) {
        throw new UnsupportedOperationException("RuleFieldPersistenceProvider is currently only compatible with collection fields when modelled using @OneToMany");
    }
    // currently, this only works with Collection fields
    boolean dirty;
    Class<?> valueType = getListFieldType(instance, populateValueRequest.getFieldManager(), populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager());
    if (valueType == null) {
        throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")");
    }
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    Collection<QuantityBasedRule> rules;
    rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
    Object parent = extractParent(populateValueRequest, instance);
    // AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
    EntityManager entityManager = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
    String fieldService = populateValueRequest.getMetadata().getRuleIdentifier();
    String entityKey = RuleIdentifier.ENTITY_KEY_MAP.get(fieldService);
    Property ruleProperty = populateValueRequest.getProperty();
    String jsonPropertyValue = ruleProperty.getUnHtmlEncodedValue();
    String mappedByEntity = oneToMany.mappedBy();
    dirty = updateQuantityRule(entityManager, translator, entityKey, fieldService, jsonPropertyValue, rules, valueType, parent, mappedByEntity, ruleProperty);
    return dirty;
}
Also used : OneToMany(javax.persistence.OneToMany) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) Field(java.lang.reflect.Field) EntityManager(javax.persistence.EntityManager) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) Property(org.broadleafcommerce.openadmin.dto.Property)

Aggregations

QuantityBasedRule (org.broadleafcommerce.common.rule.QuantityBasedRule)6 EntityManager (javax.persistence.EntityManager)3 Property (org.broadleafcommerce.openadmin.dto.Property)3 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)3 MVELTranslationException (org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException)3 DataWrapper (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper)3 Field (java.lang.reflect.Field)2 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)2 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)2 DataDTOToMVELTranslator (org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator)2 DataDTO (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 OneToMany (javax.persistence.OneToMany)1 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)1 ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)1 SimpleRule (org.broadleafcommerce.common.rule.SimpleRule)1