Search in sources :

Example 1 with DynamicViewEntity

use of org.apache.ofbiz.entity.model.DynamicViewEntity in project ofbiz-framework by apache.

the class ProductUtilServices method makeStandAloneFromSingleVariantVirtuals.

public static Map<String, Object> makeStandAloneFromSingleVariantVirtuals(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    Debug.logInfo("Starting makeStandAloneFromSingleVariantVirtuals", module);
    DynamicViewEntity dve = new DynamicViewEntity();
    dve.addMemberEntity("PVIRT", "Product");
    dve.addMemberEntity("PVA", "ProductAssoc");
    dve.addViewLink("PVIRT", "PVA", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId")));
    dve.addAlias("PVIRT", "productId", null, null, null, Boolean.TRUE, null);
    dve.addAlias("PVIRT", "salesDiscontinuationDate", null, null, null, null, null);
    dve.addAlias("PVA", "productAssocTypeId", null, null, null, null, null);
    dve.addAlias("PVA", "fromDate", null, null, null, null, null);
    dve.addAlias("PVA", "thruDate", null, null, null, null, null);
    dve.addAlias("PVA", "productIdToCount", "productIdTo", null, null, null, "count-distinct");
    EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_VARIANT"), EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN, nowTimestamp))), EntityOperator.AND);
    EntityCondition havingCond = EntityCondition.makeCondition("productIdToCount", EntityOperator.EQUALS, Long.valueOf(1));
    EntityQuery eq = EntityQuery.use(delegator).select("productId", "productIdToCount").from(dve).where(condition).having(havingCond);
    try (EntityListIterator eliOne = eq.queryIterator()) {
        List<GenericValue> valueList = eliOne.getCompleteList();
        Debug.logInfo("Found " + valueList.size() + " virtual products with one variant to turn into a stand alone product.", module);
        int numWithOneOnly = 0;
        for (GenericValue value : valueList) {
            // has only one variant period, is it valid? should already be discontinued if not
            String productId = value.getString("productId");
            List<GenericValue> paList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
            // verify the query; tested on a bunch, looks good
            if (paList.size() != 1) {
                Debug.logInfo("Virtual product with ID " + productId + " should have 1 assoc, has " + paList.size(), module);
            } else {
                // for all virtuals with one variant move all info from virtual to variant and remove virtual, make variant as not a variant
                dispatcher.runSync("mergeVirtualWithSingleVariant", UtilMisc.<String, Object>toMap("productId", productId, "removeOld", Boolean.TRUE, "userLogin", userLogin));
                numWithOneOnly++;
                if (numWithOneOnly % 100 == 0) {
                    Debug.logInfo("Made " + numWithOneOnly + " virtual products with only one valid variant stand-alone products.", module);
                }
            }
        }
        EntityCondition conditionWithDates = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_VARIANT"), EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN, nowTimestamp)), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
        eq = EntityQuery.use(delegator).select("productId", "productIdToCount").from(dve).where(conditionWithDates).having(havingCond);
        try (EntityListIterator eliMulti = eq.queryIterator()) {
            List<GenericValue> valueMultiList = eliMulti.getCompleteList();
            Debug.logInfo("Found " + valueMultiList.size() + " virtual products with one VALID variant to pull the variant from to make a stand alone product.", module);
            int numWithOneValid = 0;
            for (GenericValue value : valueMultiList) {
                // has only one valid variant
                String productId = value.getString("productId");
                List<GenericValue> paList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
                // verify the query; tested on a bunch, looks good
                if (paList.size() != 1) {
                    Debug.logInfo("Virtual product with ID " + productId + " should have 1 assoc, has " + paList.size(), module);
                } else {
                    // for all virtuals with one valid variant move info from virtual to variant, put variant in categories from virtual, remove virtual from all categories but leave "family" otherwise intact, mark variant as not a variant
                    dispatcher.runSync("mergeVirtualWithSingleVariant", UtilMisc.<String, Object>toMap("productId", productId, "removeOld", Boolean.FALSE, "userLogin", userLogin));
                    numWithOneValid++;
                    if (numWithOneValid % 100 == 0) {
                        Debug.logInfo("Made " + numWithOneValid + " virtual products with one valid variant stand-alone products.", module);
                    }
                }
            }
            Debug.logInfo("Found virtual products with one valid variant: " + numWithOneValid + ", with one variant only: " + numWithOneOnly, module);
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
            errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_makeStandAloneFromSingleVariantVirtuals", messageMap, locale);
            Debug.logError(e, errMsg, module);
            return ServiceUtil.returnError(errMsg);
        }
    } catch (GenericEntityException | GenericServiceException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productutilservices.entity_error_running_makeStandAloneFromSingleVariantVirtuals", messageMap, locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Example 2 with DynamicViewEntity

use of org.apache.ofbiz.entity.model.DynamicViewEntity in project ofbiz-framework by apache.

the class OrderLookupServices method findOrders.

public static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Integer viewIndex = Paginator.getViewIndex(context, "viewIndex", 1);
    Integer viewSize = Paginator.getViewSize(context, "viewSize");
    String showAll = (String) context.get("showAll");
    String useEntryDate = (String) context.get("useEntryDate");
    Locale locale = (Locale) context.get("locale");
    if (showAll == null) {
        showAll = "N";
    }
    // list of fields to select (initial list)
    Set<String> fieldsToSelect = new LinkedHashSet<>();
    fieldsToSelect.add("orderId");
    fieldsToSelect.add("orderName");
    fieldsToSelect.add("statusId");
    fieldsToSelect.add("orderTypeId");
    fieldsToSelect.add("orderDate");
    fieldsToSelect.add("currencyUom");
    fieldsToSelect.add("grandTotal");
    fieldsToSelect.add("remainingSubTotal");
    // sorting by order date newest first
    List<String> orderBy = UtilMisc.toList("-orderDate", "-orderId");
    // list to hold the parameters
    List<String> paramList = new LinkedList<>();
    // list of conditions
    List<EntityCondition> conditions = new LinkedList<>();
    // check security flag for purchase orders
    boolean canViewPo = security.hasEntityPermission("ORDERMGR", "_PURCHASE_VIEW", userLogin);
    if (!canViewPo) {
        conditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.NOT_EQUAL, "PURCHASE_ORDER"));
    }
    // dynamic view entity
    DynamicViewEntity dve = new DynamicViewEntity();
    dve.addMemberEntity("OH", "OrderHeader");
    // no prefix
    dve.addAliasAll("OH", "", null);
    dve.addRelation("one-nofk", "", "OrderType", UtilMisc.toList(new ModelKeyMap("orderTypeId", "orderTypeId")));
    dve.addRelation("one-nofk", "", "StatusItem", UtilMisc.toList(new ModelKeyMap("statusId", "statusId")));
    // start the lookup
    String orderId = (String) context.get("orderId");
    if (UtilValidate.isNotEmpty(orderId)) {
        paramList.add("orderId=" + orderId);
        conditions.add(makeExpr("orderId", orderId));
    }
    // the base order header fields
    List<String> orderTypeList = UtilGenerics.checkList(context.get("orderTypeId"));
    if (orderTypeList != null) {
        List<EntityExpr> orExprs = new LinkedList<>();
        for (String orderTypeId : orderTypeList) {
            paramList.add("orderTypeId=" + orderTypeId);
            if (!("PURCHASE_ORDER".equals(orderTypeId)) || (("PURCHASE_ORDER".equals(orderTypeId) && canViewPo))) {
                orExprs.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId));
            }
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    String orderName = (String) context.get("orderName");
    if (UtilValidate.isNotEmpty(orderName)) {
        paramList.add("orderName=" + orderName);
        conditions.add(makeExpr("orderName", orderName, true));
    }
    List<String> orderStatusList = UtilGenerics.checkList(context.get("orderStatusId"));
    if (orderStatusList != null) {
        List<EntityCondition> orExprs = new LinkedList<>();
        for (String orderStatusId : orderStatusList) {
            paramList.add("orderStatusId=" + orderStatusId);
            if ("PENDING".equals(orderStatusId)) {
                List<EntityExpr> pendExprs = new LinkedList<>();
                pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_CREATED"));
                pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_PROCESSING"));
                pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED"));
                orExprs.add(EntityCondition.makeCondition(pendExprs, EntityOperator.OR));
            } else {
                orExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, orderStatusId));
            }
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    List<String> productStoreList = UtilGenerics.checkList(context.get("productStoreId"));
    if (productStoreList != null) {
        List<EntityExpr> orExprs = new LinkedList<>();
        for (String productStoreId : productStoreList) {
            paramList.add("productStoreId=" + productStoreId);
            orExprs.add(EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, productStoreId));
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    List<String> webSiteList = UtilGenerics.checkList(context.get("orderWebSiteId"));
    if (webSiteList != null) {
        List<EntityExpr> orExprs = new LinkedList<>();
        for (String webSiteId : webSiteList) {
            paramList.add("webSiteId=" + webSiteId);
            orExprs.add(EntityCondition.makeCondition("webSiteId", EntityOperator.EQUALS, webSiteId));
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    List<String> saleChannelList = UtilGenerics.checkList(context.get("salesChannelEnumId"));
    if (saleChannelList != null) {
        List<EntityExpr> orExprs = new LinkedList<>();
        for (String salesChannelEnumId : saleChannelList) {
            paramList.add("salesChannelEnumId=" + salesChannelEnumId);
            orExprs.add(EntityCondition.makeCondition("salesChannelEnumId", EntityOperator.EQUALS, salesChannelEnumId));
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    String createdBy = (String) context.get("createdBy");
    if (UtilValidate.isNotEmpty(createdBy)) {
        paramList.add("createdBy=" + createdBy);
        conditions.add(makeExpr("createdBy", createdBy));
    }
    String terminalId = (String) context.get("terminalId");
    if (UtilValidate.isNotEmpty(terminalId)) {
        paramList.add("terminalId=" + terminalId);
        conditions.add(makeExpr("terminalId", terminalId));
    }
    String transactionId = (String) context.get("transactionId");
    if (UtilValidate.isNotEmpty(transactionId)) {
        paramList.add("transactionId=" + transactionId);
        conditions.add(makeExpr("transactionId", transactionId));
    }
    String externalId = (String) context.get("externalId");
    if (UtilValidate.isNotEmpty(externalId)) {
        paramList.add("externalId=" + externalId);
        conditions.add(makeExpr("externalId", externalId));
    }
    String internalCode = (String) context.get("internalCode");
    if (UtilValidate.isNotEmpty(internalCode)) {
        paramList.add("internalCode=" + internalCode);
        conditions.add(makeExpr("internalCode", internalCode));
    }
    String dateField = "Y".equals(useEntryDate) ? "entryDate" : "orderDate";
    String minDate = (String) context.get("minDate");
    if (UtilValidate.isNotEmpty(minDate) && minDate.length() > 8) {
        minDate = minDate.trim();
        if (minDate.length() < 14) {
            minDate = minDate + " " + "00:00:00.000";
        }
        paramList.add("minDate=" + minDate);
        try {
            Object converted = ObjectType.simpleTypeConvert(minDate, "Timestamp", null, null);
            if (converted != null) {
                conditions.add(EntityCondition.makeCondition(dateField, EntityOperator.GREATER_THAN_EQUAL_TO, converted));
            }
        } catch (GeneralException e) {
            Debug.logWarning(e.getMessage(), module);
        }
    }
    String maxDate = (String) context.get("maxDate");
    if (UtilValidate.isNotEmpty(maxDate) && maxDate.length() > 8) {
        maxDate = maxDate.trim();
        if (maxDate.length() < 14) {
            maxDate = maxDate + " " + "23:59:59.999";
        }
        paramList.add("maxDate=" + maxDate);
        try {
            Object converted = ObjectType.simpleTypeConvert(maxDate, "Timestamp", null, null);
            if (converted != null) {
                conditions.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, converted));
            }
        } catch (GeneralException e) {
            Debug.logWarning(e.getMessage(), module);
        }
    }
    // party (role) fields
    String userLoginId = (String) context.get("userLoginId");
    String partyId = (String) context.get("partyId");
    List<String> roleTypeList = UtilGenerics.checkList(context.get("roleTypeId"));
    if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isEmpty(partyId)) {
        GenericValue ul = null;
        try {
            ul = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).cache().queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
        }
        if (ul != null) {
            partyId = ul.getString("partyId");
        }
    }
    String isViewed = (String) context.get("isViewed");
    if (UtilValidate.isNotEmpty(isViewed)) {
        paramList.add("isViewed=" + isViewed);
        conditions.add(makeExpr("isViewed", isViewed));
    }
    // Shipment Method
    String shipmentMethod = (String) context.get("shipmentMethod");
    if (UtilValidate.isNotEmpty(shipmentMethod)) {
        String carrierPartyId = shipmentMethod.substring(0, shipmentMethod.indexOf('@'));
        String ShippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf('@') + 1);
        dve.addMemberEntity("OISG", "OrderItemShipGroup");
        dve.addAlias("OISG", "shipmentMethodTypeId");
        dve.addAlias("OISG", "carrierPartyId");
        dve.addViewLink("OH", "OISG", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
        if (UtilValidate.isNotEmpty(carrierPartyId)) {
            paramList.add("carrierPartyId=" + carrierPartyId);
            conditions.add(makeExpr("carrierPartyId", carrierPartyId));
        }
        if (UtilValidate.isNotEmpty(ShippingMethodTypeId)) {
            paramList.add("ShippingMethodTypeId=" + ShippingMethodTypeId);
            conditions.add(makeExpr("shipmentMethodTypeId", ShippingMethodTypeId));
        }
    }
    // PaymentGatewayResponse
    String gatewayAvsResult = (String) context.get("gatewayAvsResult");
    String gatewayScoreResult = (String) context.get("gatewayScoreResult");
    if (UtilValidate.isNotEmpty(gatewayAvsResult) || UtilValidate.isNotEmpty(gatewayScoreResult)) {
        dve.addMemberEntity("OPP", "OrderPaymentPreference");
        dve.addMemberEntity("PGR", "PaymentGatewayResponse");
        dve.addAlias("OPP", "orderPaymentPreferenceId");
        dve.addAlias("PGR", "gatewayAvsResult");
        dve.addAlias("PGR", "gatewayScoreResult");
        dve.addViewLink("OH", "OPP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
        dve.addViewLink("OPP", "PGR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderPaymentPreferenceId", "orderPaymentPreferenceId")));
    }
    if (UtilValidate.isNotEmpty(gatewayAvsResult)) {
        paramList.add("gatewayAvsResult=" + gatewayAvsResult);
        conditions.add(EntityCondition.makeCondition("gatewayAvsResult", gatewayAvsResult));
    }
    if (UtilValidate.isNotEmpty(gatewayScoreResult)) {
        paramList.add("gatewayScoreResult=" + gatewayScoreResult);
        conditions.add(EntityCondition.makeCondition("gatewayScoreResult", gatewayScoreResult));
    }
    // add the role data to the view
    if (roleTypeList != null || partyId != null) {
        dve.addMemberEntity("OT", "OrderRole");
        dve.addAlias("OT", "partyId");
        dve.addAlias("OT", "roleTypeId");
        dve.addViewLink("OH", "OT", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
    }
    if (UtilValidate.isNotEmpty(partyId)) {
        paramList.add("partyId=" + partyId);
        fieldsToSelect.add("partyId");
        conditions.add(makeExpr("partyId", partyId));
    }
    if (roleTypeList != null) {
        fieldsToSelect.add("roleTypeId");
        List<EntityExpr> orExprs = new LinkedList<>();
        for (String roleTypeId : roleTypeList) {
            paramList.add("roleTypeId=" + roleTypeId);
            orExprs.add(makeExpr("roleTypeId", roleTypeId));
        }
        conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
    }
    // order item fields
    String correspondingPoId = (String) context.get("correspondingPoId");
    String subscriptionId = (String) context.get("subscriptionId");
    String productId = (String) context.get("productId");
    String budgetId = (String) context.get("budgetId");
    String quoteId = (String) context.get("quoteId");
    String goodIdentificationTypeId = (String) context.get("goodIdentificationTypeId");
    String goodIdentificationIdValue = (String) context.get("goodIdentificationIdValue");
    boolean hasGoodIdentification = UtilValidate.isNotEmpty(goodIdentificationTypeId) && UtilValidate.isNotEmpty(goodIdentificationIdValue);
    if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null || hasGoodIdentification) {
        dve.addMemberEntity("OI", "OrderItem");
        dve.addAlias("OI", "correspondingPoId");
        dve.addAlias("OI", "subscriptionId");
        dve.addAlias("OI", "productId");
        dve.addAlias("OI", "budgetId");
        dve.addAlias("OI", "quoteId");
        dve.addViewLink("OH", "OI", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
        if (hasGoodIdentification) {
            dve.addMemberEntity("GOODID", "GoodIdentification");
            dve.addAlias("GOODID", "goodIdentificationTypeId");
            dve.addAlias("GOODID", "idValue");
            dve.addViewLink("OI", "GOODID", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId")));
            paramList.add("goodIdentificationTypeId=" + goodIdentificationTypeId);
            conditions.add(makeExpr("goodIdentificationTypeId", goodIdentificationTypeId));
            paramList.add("goodIdentificationIdValue=" + goodIdentificationIdValue);
            conditions.add(makeExpr("idValue", goodIdentificationIdValue));
        }
    }
    if (UtilValidate.isNotEmpty(correspondingPoId)) {
        paramList.add("correspondingPoId=" + correspondingPoId);
        conditions.add(makeExpr("correspondingPoId", correspondingPoId));
    }
    if (UtilValidate.isNotEmpty(subscriptionId)) {
        paramList.add("subscriptionId=" + subscriptionId);
        conditions.add(makeExpr("subscriptionId", subscriptionId));
    }
    if (UtilValidate.isNotEmpty(productId)) {
        paramList.add("productId=" + productId);
        if (productId.startsWith("%") || productId.startsWith("*") || productId.endsWith("%") || productId.endsWith("*")) {
            conditions.add(makeExpr("productId", productId));
        } else {
            GenericValue product = null;
            try {
                product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
            } catch (GenericEntityException e) {
                Debug.logWarning(e.getMessage(), module);
            }
            if (product != null) {
                String isVirtual = product.getString("isVirtual");
                if (isVirtual != null && "Y".equals(isVirtual)) {
                    List<EntityExpr> orExprs = new LinkedList<>();
                    orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
                    Map<String, Object> varLookup = null;
                    List<GenericValue> variants = null;
                    try {
                        varLookup = dispatcher.runSync("getAllProductVariants", UtilMisc.toMap("productId", productId));
                        if (ServiceUtil.isError(varLookup)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(varLookup));
                        }
                        variants = UtilGenerics.checkList(varLookup.get("assocProducts"));
                    } catch (GenericServiceException e) {
                        Debug.logWarning(e.getMessage(), module);
                    }
                    if (variants != null) {
                        for (GenericValue v : variants) {
                            orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, v.getString("productIdTo")));
                        }
                    }
                    conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
                } else {
                    conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
                }
            } else {
                String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid", UtilMisc.toMap("productId", productId), locale);
                return ServiceUtil.returnFailure(failMsg);
            }
        }
    }
    if (UtilValidate.isNotEmpty(budgetId)) {
        paramList.add("budgetId=" + budgetId);
        conditions.add(makeExpr("budgetId", budgetId));
    }
    if (UtilValidate.isNotEmpty(quoteId)) {
        paramList.add("quoteId=" + quoteId);
        conditions.add(makeExpr("quoteId", quoteId));
    }
    // payment preference fields
    String billingAccountId = (String) context.get("billingAccountId");
    String finAccountId = (String) context.get("finAccountId");
    String cardNumber = (String) context.get("cardNumber");
    String accountNumber = (String) context.get("accountNumber");
    String paymentStatusId = (String) context.get("paymentStatusId");
    if (UtilValidate.isNotEmpty(paymentStatusId)) {
        paramList.add("paymentStatusId=" + paymentStatusId);
        conditions.add(makeExpr("paymentStatusId", paymentStatusId));
    }
    if (finAccountId != null || cardNumber != null || accountNumber != null || paymentStatusId != null) {
        dve.addMemberEntity("OP", "OrderPaymentPreference");
        dve.addAlias("OP", "finAccountId");
        dve.addAlias("OP", "paymentMethodId");
        dve.addAlias("OP", "paymentStatusId", "statusId", null, false, false, null);
        dve.addViewLink("OH", "OP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
    }
    // search by billing account ID
    if (UtilValidate.isNotEmpty(billingAccountId)) {
        paramList.add("billingAccountId=" + billingAccountId);
        conditions.add(makeExpr("billingAccountId", billingAccountId));
    }
    // search by fin account ID
    if (UtilValidate.isNotEmpty(finAccountId)) {
        paramList.add("finAccountId=" + finAccountId);
        conditions.add(makeExpr("finAccountId", finAccountId));
    }
    // search by card number
    if (UtilValidate.isNotEmpty(cardNumber)) {
        dve.addMemberEntity("CC", "CreditCard");
        dve.addAlias("CC", "cardNumber");
        dve.addViewLink("OP", "CC", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId")));
        paramList.add("cardNumber=" + cardNumber);
        conditions.add(makeExpr("cardNumber", cardNumber));
    }
    // search by eft account number
    if (UtilValidate.isNotEmpty(accountNumber)) {
        dve.addMemberEntity("EF", "EftAccount");
        dve.addAlias("EF", "accountNumber");
        dve.addViewLink("OP", "EF", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId")));
        paramList.add("accountNumber=" + accountNumber);
        conditions.add(makeExpr("accountNumber", accountNumber));
    }
    // shipment/inventory item
    String inventoryItemId = (String) context.get("inventoryItemId");
    String softIdentifier = (String) context.get("softIdentifier");
    String serialNumber = (String) context.get("serialNumber");
    String shipmentId = (String) context.get("shipmentId");
    if (shipmentId != null || inventoryItemId != null || softIdentifier != null || serialNumber != null) {
        dve.addMemberEntity("II", "ItemIssuance");
        dve.addAlias("II", "shipmentId");
        dve.addAlias("II", "inventoryItemId");
        dve.addViewLink("OH", "II", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
        if (softIdentifier != null || serialNumber != null) {
            dve.addMemberEntity("IV", "InventoryItem");
            dve.addAlias("IV", "softIdentifier");
            dve.addAlias("IV", "serialNumber");
            dve.addViewLink("II", "IV", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("inventoryItemId", "inventoryItemId")));
        }
    }
    if (UtilValidate.isNotEmpty(inventoryItemId)) {
        paramList.add("inventoryItemId=" + inventoryItemId);
        conditions.add(makeExpr("inventoryItemId", inventoryItemId));
    }
    if (UtilValidate.isNotEmpty(softIdentifier)) {
        paramList.add("softIdentifier=" + softIdentifier);
        conditions.add(makeExpr("softIdentifier", softIdentifier, true));
    }
    if (UtilValidate.isNotEmpty(serialNumber)) {
        paramList.add("serialNumber=" + serialNumber);
        conditions.add(makeExpr("serialNumber", serialNumber, true));
    }
    if (UtilValidate.isNotEmpty(shipmentId)) {
        paramList.add("shipmentId=" + shipmentId);
        conditions.add(makeExpr("shipmentId", shipmentId));
    }
    // back order checking
    String hasBackOrders = (String) context.get("hasBackOrders");
    if (UtilValidate.isNotEmpty(hasBackOrders)) {
        dve.addMemberEntity("IR", "OrderItemShipGrpInvRes");
        dve.addAlias("IR", "quantityNotAvailable");
        dve.addViewLink("OH", "IR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
        paramList.add("hasBackOrders=" + hasBackOrders);
        if ("Y".equals(hasBackOrders)) {
            conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null));
            conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO));
        } else if ("N".equals(hasBackOrders)) {
            List<EntityExpr> orExpr = new LinkedList<>();
            orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, null));
            orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, BigDecimal.ZERO));
            conditions.add(EntityCondition.makeCondition(orExpr, EntityOperator.OR));
        }
    }
    // Get all orders according to specific ship to country with "Only Include" or "Do not Include".
    String countryGeoId = (String) context.get("countryGeoId");
    String includeCountry = (String) context.get("includeCountry");
    if (UtilValidate.isNotEmpty(countryGeoId) && UtilValidate.isNotEmpty(includeCountry)) {
        paramList.add("countryGeoId=" + countryGeoId);
        paramList.add("includeCountry=" + includeCountry);
        // add condition to dynamic view
        dve.addMemberEntity("OCM", "OrderContactMech");
        dve.addMemberEntity("PA", "PostalAddress");
        dve.addAlias("OCM", "contactMechId");
        dve.addAlias("OCM", "contactMechPurposeTypeId");
        dve.addAlias("PA", "countryGeoId");
        dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId"));
        dve.addViewLink("OCM", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
        EntityConditionList<EntityExpr> exprs = null;
        if ("Y".equals(includeCountry)) {
            exprs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", countryGeoId)), EntityOperator.AND);
        } else {
            exprs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"), EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, countryGeoId)), EntityOperator.AND);
        }
        conditions.add(exprs);
    }
    // create the main condition
    EntityCondition cond = null;
    if (conditions.size() > 0 || "Y".equalsIgnoreCase(showAll)) {
        cond = EntityCondition.makeCondition(conditions, EntityOperator.AND);
    }
    if (Debug.verboseOn()) {
        Debug.logInfo("Find order query: " + cond.toString(), module);
    }
    List<GenericValue> orderList = new LinkedList<>();
    int orderCount = 0;
    // get the index for the partial list
    int lowIndex = 0;
    int highIndex = 0;
    if (cond != null) {
        PagedList<GenericValue> pagedOrderList = null;
        try {
            // do the lookup
            pagedOrderList = EntityQuery.use(delegator).select(fieldsToSelect).from(dve).where(cond).orderBy(orderBy).distinct().cursorScrollInsensitive().queryPagedList(viewIndex - 1, viewSize);
            orderCount = pagedOrderList.getSize();
            lowIndex = pagedOrderList.getStartIndex();
            highIndex = pagedOrderList.getEndIndex();
            orderList = pagedOrderList.getData();
        } catch (GenericEntityException e) {
            Debug.logError(e.getMessage(), module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // create the result map
    Map<String, Object> result = ServiceUtil.returnSuccess();
    // filter out requested inventory problems
    filterInventoryProblems(context, result, orderList, paramList);
    // format the param list
    String paramString = StringUtil.join(paramList, "&amp;");
    result.put("highIndex", Integer.valueOf(highIndex));
    result.put("lowIndex", Integer.valueOf(lowIndex));
    result.put("viewIndex", viewIndex);
    result.put("viewSize", viewSize);
    result.put("showAll", showAll);
    result.put("paramList", (paramString != null ? paramString : ""));
    result.put("orderList", orderList);
    result.put("orderListSize", Integer.valueOf(orderCount));
    return result;
}
Also used : Locale(java.util.Locale) LinkedHashSet(java.util.LinkedHashSet) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Security(org.apache.ofbiz.security.Security) EntityConditionList(org.apache.ofbiz.entity.condition.EntityConditionList) LinkedList(java.util.LinkedList) PagedList(org.apache.ofbiz.base.util.collections.PagedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 3 with DynamicViewEntity

use of org.apache.ofbiz.entity.model.DynamicViewEntity in project ofbiz-framework by apache.

the class PartyServices method performFindParty.

public static Map<String, Object> performFindParty(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    String extInfo = (String) context.get("extInfo");
    EntityCondition extCond = (EntityCondition) context.get("extCond");
    EntityListIterator listIt = null;
    // get the lookup flag
    String noConditionFind = (String) context.get("noConditionFind");
    // create the dynamic view entity
    DynamicViewEntity dynamicView = new DynamicViewEntity();
    // default view settings
    dynamicView.addMemberEntity("PT", "Party");
    dynamicView.addAlias("PT", "partyId");
    dynamicView.addAlias("PT", "statusId");
    dynamicView.addAlias("PT", "partyTypeId");
    dynamicView.addAlias("PT", "externalId");
    dynamicView.addAlias("PT", "createdDate");
    dynamicView.addAlias("PT", "lastModifiedDate");
    dynamicView.addRelation("one-nofk", "", "PartyType", ModelKeyMap.makeKeyMapList("partyTypeId"));
    dynamicView.addRelation("many", "", "UserLogin", ModelKeyMap.makeKeyMapList("partyId"));
    // define the main condition & expression list
    List<EntityCondition> andExprs = new ArrayList<>();
    EntityCondition mainCond = null;
    List<String> orderBy = new ArrayList<>();
    String sortField = (String) context.get("sortField");
    if (UtilValidate.isNotEmpty(sortField)) {
        orderBy.add(sortField);
    }
    List<String> fieldsToSelect = new ArrayList<>();
    // fields we need to select; will be used to set distinct
    fieldsToSelect.add("partyId");
    fieldsToSelect.add("statusId");
    fieldsToSelect.add("partyTypeId");
    fieldsToSelect.add("externalId");
    fieldsToSelect.add("createdDate");
    fieldsToSelect.add("lastModifiedDate");
    // filter on parties that have relationship with logged in user
    String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId");
    if (UtilValidate.isNotEmpty(partyRelationshipTypeId)) {
        // add relation to view
        dynamicView.addMemberEntity("PRSHP", "PartyRelationship");
        dynamicView.addAlias("PRSHP", "partyIdTo");
        dynamicView.addAlias("PRSHP", "partyRelationshipTypeId");
        dynamicView.addViewLink("PT", "PRSHP", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId", "partyIdTo"));
        List<String> ownerPartyIds = UtilGenerics.cast(context.get("ownerPartyIds"));
        EntityCondition relationshipCond = null;
        if (UtilValidate.isEmpty(ownerPartyIds)) {
            String partyIdFrom = userLogin.getString("partyId");
            relationshipCond = EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyIdFrom"), EntityOperator.EQUALS, EntityFunction.UPPER(partyIdFrom));
        } else {
            relationshipCond = EntityCondition.makeCondition("partyIdFrom", EntityOperator.IN, ownerPartyIds);
        }
        dynamicView.addAlias("PRSHP", "partyIdFrom");
        // add the expr
        andExprs.add(EntityCondition.makeCondition(relationshipCond, EntityOperator.AND, EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyRelationshipTypeId"), EntityOperator.EQUALS, EntityFunction.UPPER(partyRelationshipTypeId))));
        fieldsToSelect.add("partyIdTo");
    }
    // get the params
    String partyId = (String) context.get("partyId");
    String partyTypeId = (String) context.get("partyTypeId");
    String roleTypeId = (String) context.get("roleTypeId");
    String statusId = (String) context.get("statusId");
    String userLoginId = (String) context.get("userLoginId");
    String externalId = (String) context.get("externalId");
    String firstName = (String) context.get("firstName");
    String lastName = (String) context.get("lastName");
    String groupName = (String) context.get("groupName");
    // check for a partyId
    if (UtilValidate.isNotEmpty(partyId)) {
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + partyId + "%")));
    }
    // now the statusId - send ANY for all statuses; leave null for just enabled; or pass a specific status
    if (UtilValidate.isNotEmpty(statusId)) {
        andExprs.add(EntityCondition.makeCondition("statusId", statusId));
    } else {
        // NOTE: _must_ explicitly allow null as it is not included in a not equal in many databases... odd but true
        andExprs.add(EntityCondition.makeCondition(EntityCondition.makeCondition("statusId", GenericEntity.NULL_FIELD), EntityOperator.OR, EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PARTY_DISABLED")));
    }
    // check for partyTypeId
    if (UtilValidate.isNotEmpty(partyTypeId)) {
        andExprs.add(EntityCondition.makeCondition("partyTypeId", partyTypeId));
    }
    if (UtilValidate.isNotEmpty(externalId)) {
        andExprs.add(EntityCondition.makeCondition("externalId", externalId));
    }
    // filter on user login
    if (UtilValidate.isNotEmpty(userLoginId)) {
        // modify the dynamic view
        dynamicView.addMemberEntity("UL", "UserLogin");
        dynamicView.addAlias("UL", "userLoginId");
        dynamicView.addViewLink("PT", "UL", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        // add the expr
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("userLoginId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + userLoginId + "%")));
        fieldsToSelect.add("userLoginId");
    }
    // filter on groupName
    if (UtilValidate.isNotEmpty(groupName)) {
        // modify the dynamic view
        dynamicView.addMemberEntity("PG", "PartyGroup");
        dynamicView.addAlias("PG", "groupName");
        dynamicView.addViewLink("PT", "PG", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        // add the expr
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("groupName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + groupName + "%")));
        fieldsToSelect.add("groupName");
    }
    // modify the dynamic view
    if (UtilValidate.isNotEmpty(firstName) || UtilValidate.isNotEmpty(lastName)) {
        dynamicView.addMemberEntity("PE", "Person");
        dynamicView.addAlias("PE", "firstName");
        dynamicView.addAlias("PE", "lastName");
        dynamicView.addViewLink("PT", "PE", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        fieldsToSelect.add("firstName");
        fieldsToSelect.add("lastName");
        orderBy.add("lastName");
        orderBy.add("firstName");
    }
    // filter on firstName
    if (UtilValidate.isNotEmpty(firstName)) {
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("firstName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + firstName + "%")));
    }
    // filter on lastName
    if (UtilValidate.isNotEmpty(lastName)) {
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("lastName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + lastName + "%")));
    }
    // filter on role member
    if (UtilValidate.isNotEmpty(roleTypeId)) {
        // add role to view
        dynamicView.addMemberEntity("PR", "PartyRole");
        dynamicView.addAlias("PR", "roleTypeId");
        dynamicView.addViewLink("PT", "PR", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        // add the expr
        andExprs.add(EntityCondition.makeCondition("roleTypeId", roleTypeId));
        fieldsToSelect.add("roleTypeId");
    }
    // ----
    // PartyIdentification Fields
    // ----
    String idValue = (String) context.get("idValue");
    String partyIdentificationTypeId = (String) context.get("partyIdentificationTypeId");
    if ("I".equals(extInfo) || UtilValidate.isNotEmpty(idValue) || UtilValidate.isNotEmpty(partyIdentificationTypeId)) {
        // add role to view
        dynamicView.addMemberEntity("PAI", "PartyIdentification");
        dynamicView.addAlias("PAI", "idValue");
        dynamicView.addAlias("PAI", "partyIdentificationTypeId");
        dynamicView.addViewLink("PT", "PAI", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        fieldsToSelect.add("idValue");
        fieldsToSelect.add("partyIdentificationTypeId");
        if (UtilValidate.isNotEmpty(idValue)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("idValue"), EntityOperator.LIKE, EntityFunction.UPPER("%".concat(idValue).concat("%"))));
        }
        if (UtilValidate.isNotEmpty(partyIdentificationTypeId)) {
            andExprs.add(EntityCondition.makeCondition("partyIdentificationTypeId", partyIdentificationTypeId));
        }
    }
    // ----
    // InventoryItem Fields
    // ----
    // filter on inventory item's fields
    String inventoryItemId = (String) context.get("inventoryItemId");
    String serialNumber = (String) context.get("serialNumber");
    String softIdentifier = (String) context.get("softIdentifier");
    if (UtilValidate.isNotEmpty(inventoryItemId) || UtilValidate.isNotEmpty(serialNumber) || UtilValidate.isNotEmpty(softIdentifier)) {
        // add role to view
        dynamicView.addMemberEntity("II", "InventoryItem");
        dynamicView.addAlias("II", "ownerPartyId");
        dynamicView.addViewLink("PT", "II", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId", "ownerPartyId"));
    }
    if (UtilValidate.isNotEmpty(inventoryItemId)) {
        dynamicView.addAlias("II", "inventoryItemId");
        // add the expr
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("inventoryItemId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + inventoryItemId + "%")));
        fieldsToSelect.add("inventoryItemId");
    }
    if (UtilValidate.isNotEmpty(serialNumber)) {
        dynamicView.addAlias("II", "serialNumber");
        // add the expr
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("serialNumber"), EntityOperator.LIKE, EntityFunction.UPPER("%" + serialNumber + "%")));
        fieldsToSelect.add("serialNumber");
    }
    if (UtilValidate.isNotEmpty(softIdentifier)) {
        dynamicView.addAlias("II", "softIdentifier");
        // add the expr
        andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("softIdentifier"), EntityOperator.LIKE, EntityFunction.UPPER("%" + softIdentifier + "%")));
        fieldsToSelect.add("softIdentifier");
    }
    // ----
    // PostalAddress fields
    // ----
    String stateProvinceGeoId = (String) context.get("stateProvinceGeoId");
    if ("P".equals(extInfo) || UtilValidate.isNotEmpty(context.get("address1")) || UtilValidate.isNotEmpty(context.get("address2")) || UtilValidate.isNotEmpty(context.get("city")) || UtilValidate.isNotEmpty(context.get("postalCode")) || UtilValidate.isNotEmpty(context.get("countryGeoId")) || (UtilValidate.isNotEmpty(stateProvinceGeoId))) {
        // add address to dynamic view
        dynamicView.addMemberEntity("PC", "PartyContactMech");
        dynamicView.addMemberEntity("PA", "PostalAddress");
        dynamicView.addAlias("PC", "contactMechId");
        dynamicView.addAlias("PA", "address1");
        dynamicView.addAlias("PA", "address2");
        dynamicView.addAlias("PA", "city");
        dynamicView.addAlias("PA", "stateProvinceGeoId");
        dynamicView.addAlias("PA", "countryGeoId");
        dynamicView.addAlias("PA", "postalCode");
        dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        dynamicView.addViewLink("PC", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
        // filter on address1
        String address1 = (String) context.get("address1");
        if (UtilValidate.isNotEmpty(address1)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("address1"), EntityOperator.LIKE, EntityFunction.UPPER("%" + address1 + "%")));
        }
        // filter on address2
        String address2 = (String) context.get("address2");
        if (UtilValidate.isNotEmpty(address2)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("address2"), EntityOperator.LIKE, EntityFunction.UPPER("%" + address2 + "%")));
        }
        // filter on city
        String city = (String) context.get("city");
        if (UtilValidate.isNotEmpty(city)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("city"), EntityOperator.LIKE, EntityFunction.UPPER("%" + city + "%")));
        }
        // filter on state geo
        if (UtilValidate.isNotEmpty(stateProvinceGeoId)) {
            andExprs.add(EntityCondition.makeCondition("stateProvinceGeoId", stateProvinceGeoId));
        }
        // filter on postal code
        String postalCode = (String) context.get("postalCode");
        if (UtilValidate.isNotEmpty(postalCode)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("postalCode"), EntityOperator.LIKE, EntityFunction.UPPER("%" + postalCode + "%")));
        }
        fieldsToSelect.add("postalCode");
        fieldsToSelect.add("city");
        fieldsToSelect.add("stateProvinceGeoId");
    }
    // ----
    if ("O".equals(extInfo) || UtilValidate.isNotEmpty(context.get("infoString"))) {
        // add info to dynamic view
        dynamicView.addMemberEntity("PC", "PartyContactMech");
        dynamicView.addMemberEntity("CM", "ContactMech");
        dynamicView.addAlias("PC", "contactMechId");
        dynamicView.addAlias("CM", "infoString");
        dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        dynamicView.addViewLink("PC", "CM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
        // filter on infoString
        String infoString = (String) context.get("infoString");
        if (UtilValidate.isNotEmpty(infoString)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%" + infoString + "%")));
            fieldsToSelect.add("infoString");
        }
    }
    // ----
    if ("T".equals(extInfo) || UtilValidate.isNotEmpty(context.get("countryCode")) || UtilValidate.isNotEmpty(context.get("areaCode")) || UtilValidate.isNotEmpty(context.get("contactNumber"))) {
        // add telecom to dynamic view
        dynamicView.addMemberEntity("PC", "PartyContactMech");
        dynamicView.addMemberEntity("TM", "TelecomNumber");
        dynamicView.addAlias("PC", "contactMechId");
        dynamicView.addAlias("TM", "countryCode");
        dynamicView.addAlias("TM", "areaCode");
        dynamicView.addAlias("TM", "contactNumber");
        dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
        dynamicView.addViewLink("PC", "TM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
        // filter on countryCode
        String countryCode = (String) context.get("countryCode");
        if (UtilValidate.isNotEmpty(countryCode)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("countryCode"), EntityOperator.EQUALS, EntityFunction.UPPER(countryCode)));
        }
        // filter on areaCode
        String areaCode = (String) context.get("areaCode");
        if (UtilValidate.isNotEmpty(areaCode)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("areaCode"), EntityOperator.EQUALS, EntityFunction.UPPER(areaCode)));
        }
        // filter on contact number
        String contactNumber = (String) context.get("contactNumber");
        if (UtilValidate.isNotEmpty(contactNumber)) {
            andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("contactNumber"), EntityOperator.EQUALS, EntityFunction.UPPER(contactNumber)));
        }
        fieldsToSelect.add("contactNumber");
        fieldsToSelect.add("areaCode");
    }
    // build the main condition, add the extend condition is it present
    if (UtilValidate.isNotEmpty(extCond)) {
        andExprs.add(extCond);
    }
    if (UtilValidate.isNotEmpty(andExprs)) {
        mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
    }
    if (Debug.infoOn()) {
        Debug.logInfo("In findParty mainCond=" + mainCond, module);
    }
    // do the lookup
    if (UtilValidate.isNotEmpty(noConditionFind) && ("Y".equals(noConditionFind) || andExprs.size() > 1)) {
        // exclude on condition the status expr
        try {
            // set distinct on so we only get one row per party
            // using list iterator
            listIt = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicView).where(mainCond).orderBy(orderBy).cursorScrollInsensitive().distinct().queryIterator();
        } catch (GenericEntityException e) {
            String errMsg = "Failure in party find operation, rolling back transaction: " + e.toString();
            Debug.logError(e, errMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupPartyError", UtilMisc.toMap("errMessage", e.toString()), locale));
        }
    }
    result.put("listIt", listIt);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ArrayList(java.util.ArrayList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 4 with DynamicViewEntity

use of org.apache.ofbiz.entity.model.DynamicViewEntity in project ofbiz-framework by apache.

the class PartyServices method findParty.

// migration from ftl to widget in process.
@Deprecated
public static Map<String, Object> findParty(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    String extInfo = (String) context.get("extInfo");
    // get the role types
    try {
        List<GenericValue> roleTypes = EntityQuery.use(delegator).from("RoleType").orderBy("description").queryList();
        result.put("roleTypes", roleTypes);
    } catch (GenericEntityException e) {
        String errMsg = "Error looking up RoleTypes: " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupRoleTypeError", UtilMisc.toMap("errMessage", e.toString()), locale));
    }
    // current role type
    String roleTypeId;
    try {
        roleTypeId = (String) context.get("roleTypeId");
        if (UtilValidate.isNotEmpty(roleTypeId)) {
            GenericValue currentRole = EntityQuery.use(delegator).from("RoleType").where("roleTypeId", roleTypeId).cache().queryOne();
            result.put("currentRole", currentRole);
        }
    } catch (GenericEntityException e) {
        String errMsg = "Error looking up current RoleType: " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupRoleTypeError", UtilMisc.toMap("errMessage", e.toString()), locale));
    }
    // get party types
    try {
        List<GenericValue> partyTypes = EntityQuery.use(delegator).from("PartyType").orderBy("description").queryList();
        result.put("partyTypes", partyTypes);
    } catch (GenericEntityException e) {
        String errMsg = "Error looking up PartyTypes: " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupPartyTypeError", UtilMisc.toMap("errMessage", e.toString()), locale));
    }
    // current party type
    String partyTypeId;
    try {
        partyTypeId = (String) context.get("partyTypeId");
        if (UtilValidate.isNotEmpty(partyTypeId)) {
            GenericValue currentPartyType = EntityQuery.use(delegator).from("PartyType").where("partyTypeId", partyTypeId).cache().queryOne();
            result.put("currentPartyType", currentPartyType);
        }
    } catch (GenericEntityException e) {
        String errMsg = "Error looking up current PartyType: " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupPartyTypeError", UtilMisc.toMap("errMessage", e.toString()), locale));
    }
    // current state
    String stateProvinceGeoId;
    try {
        stateProvinceGeoId = (String) context.get("stateProvinceGeoId");
        if (UtilValidate.isNotEmpty(stateProvinceGeoId)) {
            GenericValue currentStateGeo = EntityQuery.use(delegator).from("Geo").where("geoId", stateProvinceGeoId).cache().queryOne();
            result.put("currentStateGeo", currentStateGeo);
        }
    } catch (GenericEntityException e) {
        String errMsg = "Error looking up current stateProvinceGeo: " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupStateProvinceGeoError", UtilMisc.toMap("errMessage", e.toString()), locale));
    }
    // set the page parameters
    int viewIndex = 0;
    try {
        viewIndex = Integer.parseInt((String) context.get("VIEW_INDEX"));
    } catch (Exception e) {
        viewIndex = 0;
    }
    result.put("viewIndex", Integer.valueOf(viewIndex));
    int viewSize = 20;
    try {
        viewSize = Integer.parseInt((String) context.get("VIEW_SIZE"));
    } catch (Exception e) {
        viewSize = 20;
    }
    result.put("viewSize", Integer.valueOf(viewSize));
    // get the lookup flag
    String lookupFlag = (String) context.get("lookupFlag");
    // blank param list
    String paramList = "";
    List<GenericValue> partyList = null;
    int partyListSize = 0;
    int lowIndex = 0;
    int highIndex = 0;
    if ("Y".equals(lookupFlag)) {
        String showAll = (context.get("showAll") != null ? (String) context.get("showAll") : "N");
        paramList = paramList + "&lookupFlag=" + lookupFlag + "&showAll=" + showAll + "&extInfo=" + extInfo;
        // create the dynamic view entity
        DynamicViewEntity dynamicView = new DynamicViewEntity();
        // default view settings
        dynamicView.addMemberEntity("PT", "Party");
        dynamicView.addAlias("PT", "partyId");
        dynamicView.addAlias("PT", "statusId");
        dynamicView.addAlias("PT", "partyTypeId");
        dynamicView.addAlias("PT", "createdDate");
        dynamicView.addAlias("PT", "lastModifiedDate");
        dynamicView.addRelation("one-nofk", "", "PartyType", ModelKeyMap.makeKeyMapList("partyTypeId"));
        dynamicView.addRelation("many", "", "UserLogin", ModelKeyMap.makeKeyMapList("partyId"));
        // define the main condition & expression list
        List<EntityCondition> andExprs = new LinkedList<>();
        EntityCondition mainCond = null;
        List<String> orderBy = new LinkedList<>();
        List<String> fieldsToSelect = new LinkedList<>();
        // fields we need to select; will be used to set distinct
        fieldsToSelect.add("partyId");
        fieldsToSelect.add("statusId");
        fieldsToSelect.add("partyTypeId");
        fieldsToSelect.add("createdDate");
        fieldsToSelect.add("lastModifiedDate");
        // filter on parties that have relationship with logged in user
        String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId");
        if (UtilValidate.isNotEmpty(partyRelationshipTypeId)) {
            // add relation to view
            dynamicView.addMemberEntity("PRSHP", "PartyRelationship");
            dynamicView.addAlias("PRSHP", "partyIdTo");
            dynamicView.addAlias("PRSHP", "partyRelationshipTypeId");
            dynamicView.addViewLink("PT", "PRSHP", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId", "partyIdTo"));
            List<String> ownerPartyIds = UtilGenerics.cast(context.get("ownerPartyIds"));
            EntityCondition relationshipCond = null;
            if (UtilValidate.isEmpty(ownerPartyIds)) {
                String partyIdFrom = userLogin.getString("partyId");
                paramList = paramList + "&partyIdFrom=" + partyIdFrom;
                relationshipCond = EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyIdFrom"), EntityOperator.EQUALS, EntityFunction.UPPER(partyIdFrom));
            } else {
                relationshipCond = EntityCondition.makeCondition("partyIdFrom", EntityOperator.IN, ownerPartyIds);
            }
            dynamicView.addAlias("PRSHP", "partyIdFrom");
            // add the expr
            andExprs.add(EntityCondition.makeCondition(relationshipCond, EntityOperator.AND, EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyRelationshipTypeId"), EntityOperator.EQUALS, EntityFunction.UPPER(partyRelationshipTypeId))));
            fieldsToSelect.add("partyIdTo");
        }
        // get the params
        String partyId = (String) context.get("partyId");
        String statusId = (String) context.get("statusId");
        String userLoginId = (String) context.get("userLoginId");
        String firstName = (String) context.get("firstName");
        String lastName = (String) context.get("lastName");
        String groupName = (String) context.get("groupName");
        if (!"Y".equals(showAll)) {
            // check for a partyId
            if (UtilValidate.isNotEmpty(partyId)) {
                paramList = paramList + "&partyId=" + partyId;
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + partyId + "%")));
            }
            // now the statusId - send ANY for all statuses; leave null for just enabled; or pass a specific status
            if (statusId != null) {
                paramList = paramList + "&statusId=" + statusId;
                if (!"ANY".equalsIgnoreCase(statusId)) {
                    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, statusId));
                }
            } else {
                // NOTE: _must_ explicitly allow null as it is not included in a not equal in many databases... odd but true
                andExprs.add(EntityCondition.makeCondition(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PARTY_DISABLED")));
            }
            // check for partyTypeId
            if (partyTypeId != null && !"ANY".equals(partyTypeId)) {
                paramList = paramList + "&partyTypeId=" + partyTypeId;
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("partyTypeId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + partyTypeId + "%")));
            }
            // filter on user login
            if (UtilValidate.isNotEmpty(userLoginId)) {
                paramList = paramList + "&userLoginId=" + userLoginId;
                // modify the dynamic view
                dynamicView.addMemberEntity("UL", "UserLogin");
                dynamicView.addAlias("UL", "userLoginId");
                dynamicView.addViewLink("PT", "UL", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                // add the expr
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("userLoginId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + userLoginId + "%")));
                fieldsToSelect.add("userLoginId");
            }
            // filter on groupName
            if (UtilValidate.isNotEmpty(groupName)) {
                paramList = paramList + "&groupName=" + groupName;
                // modify the dynamic view
                dynamicView.addMemberEntity("PG", "PartyGroup");
                dynamicView.addAlias("PG", "groupName");
                dynamicView.addViewLink("PT", "PG", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                // add the expr
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("groupName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + groupName + "%")));
                fieldsToSelect.add("groupName");
            }
            // modify the dynamic view
            if (UtilValidate.isNotEmpty(firstName) || UtilValidate.isNotEmpty(lastName)) {
                dynamicView.addMemberEntity("PE", "Person");
                dynamicView.addAlias("PE", "firstName");
                dynamicView.addAlias("PE", "lastName");
                dynamicView.addViewLink("PT", "PE", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                fieldsToSelect.add("firstName");
                fieldsToSelect.add("lastName");
                orderBy.add("lastName");
                orderBy.add("firstName");
            }
            // filter on firstName
            if (UtilValidate.isNotEmpty(firstName)) {
                paramList = paramList + "&firstName=" + firstName;
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("firstName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + firstName + "%")));
            }
            // filter on lastName
            if (UtilValidate.isNotEmpty(lastName)) {
                paramList = paramList + "&lastName=" + lastName;
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("lastName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + lastName + "%")));
            }
            // filter on role member
            if (roleTypeId != null && !"ANY".equals(roleTypeId)) {
                paramList = paramList + "&roleTypeId=" + roleTypeId;
                // add role to view
                dynamicView.addMemberEntity("PR", "PartyRole");
                dynamicView.addAlias("PR", "roleTypeId");
                dynamicView.addViewLink("PT", "PR", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                // add the expr
                andExprs.add(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, roleTypeId));
                fieldsToSelect.add("roleTypeId");
            }
            // ----
            // InventoryItem Fields
            // ----
            // filter on inventory item's fields
            String inventoryItemId = (String) context.get("inventoryItemId");
            String serialNumber = (String) context.get("serialNumber");
            String softIdentifier = (String) context.get("softIdentifier");
            if (UtilValidate.isNotEmpty(inventoryItemId) || UtilValidate.isNotEmpty(serialNumber) || UtilValidate.isNotEmpty(softIdentifier)) {
                // add role to view
                dynamicView.addMemberEntity("II", "InventoryItem");
                dynamicView.addAlias("II", "ownerPartyId");
                dynamicView.addViewLink("PT", "II", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId", "ownerPartyId"));
            }
            if (UtilValidate.isNotEmpty(inventoryItemId)) {
                paramList = paramList + "&inventoryItemId=" + inventoryItemId;
                dynamicView.addAlias("II", "inventoryItemId");
                // add the expr
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("inventoryItemId"), EntityOperator.LIKE, EntityFunction.UPPER("%" + inventoryItemId + "%")));
                fieldsToSelect.add("inventoryItemId");
            }
            if (UtilValidate.isNotEmpty(serialNumber)) {
                paramList = paramList + "&serialNumber=" + serialNumber;
                dynamicView.addAlias("II", "serialNumber");
                // add the expr
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("serialNumber"), EntityOperator.LIKE, EntityFunction.UPPER("%" + serialNumber + "%")));
                fieldsToSelect.add("serialNumber");
            }
            if (UtilValidate.isNotEmpty(softIdentifier)) {
                paramList = paramList + "&softIdentifier=" + softIdentifier;
                dynamicView.addAlias("II", "softIdentifier");
                // add the expr
                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("softIdentifier"), EntityOperator.LIKE, EntityFunction.UPPER("%" + softIdentifier + "%")));
                fieldsToSelect.add("softIdentifier");
            }
            // ----
            if ("P".equals(extInfo)) {
                // add address to dynamic view
                dynamicView.addMemberEntity("PC", "PartyContactMech");
                dynamicView.addMemberEntity("PA", "PostalAddress");
                dynamicView.addAlias("PC", "contactMechId");
                dynamicView.addAlias("PA", "address1");
                dynamicView.addAlias("PA", "address2");
                dynamicView.addAlias("PA", "city");
                dynamicView.addAlias("PA", "stateProvinceGeoId");
                dynamicView.addAlias("PA", "countryGeoId");
                dynamicView.addAlias("PA", "postalCode");
                dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                dynamicView.addViewLink("PC", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
                // filter on address1
                String address1 = (String) context.get("address1");
                if (UtilValidate.isNotEmpty(address1)) {
                    paramList = paramList + "&address1=" + address1;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("address1"), EntityOperator.LIKE, EntityFunction.UPPER("%" + address1 + "%")));
                }
                // filter on address2
                String address2 = (String) context.get("address2");
                if (UtilValidate.isNotEmpty(address2)) {
                    paramList = paramList + "&address2=" + address2;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("address2"), EntityOperator.LIKE, EntityFunction.UPPER("%" + address2 + "%")));
                }
                // filter on city
                String city = (String) context.get("city");
                if (UtilValidate.isNotEmpty(city)) {
                    paramList = paramList + "&city=" + city;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("city"), EntityOperator.LIKE, EntityFunction.UPPER("%" + city + "%")));
                }
                // filter on state geo
                if (stateProvinceGeoId != null && !"ANY".equals(stateProvinceGeoId)) {
                    paramList = paramList + "&stateProvinceGeoId=" + stateProvinceGeoId;
                    andExprs.add(EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, stateProvinceGeoId));
                }
                // filter on postal code
                String postalCode = (String) context.get("postalCode");
                if (UtilValidate.isNotEmpty(postalCode)) {
                    paramList = paramList + "&postalCode=" + postalCode;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("postalCode"), EntityOperator.LIKE, EntityFunction.UPPER("%" + postalCode + "%")));
                }
                fieldsToSelect.add("postalCode");
                fieldsToSelect.add("city");
                fieldsToSelect.add("stateProvinceGeoId");
            }
            // ----
            if ("O".equals(extInfo)) {
                // add info to dynamic view
                dynamicView.addMemberEntity("PC", "PartyContactMech");
                dynamicView.addMemberEntity("CM", "ContactMech");
                dynamicView.addAlias("PC", "contactMechId");
                dynamicView.addAlias("CM", "infoString");
                dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                dynamicView.addViewLink("PC", "CM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
                // filter on infoString
                String infoString = (String) context.get("infoString");
                if (UtilValidate.isNotEmpty(infoString)) {
                    paramList = paramList + "&infoString=" + infoString;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%" + infoString + "%")));
                    fieldsToSelect.add("infoString");
                }
            }
            // ----
            if ("T".equals(extInfo)) {
                // add telecom to dynamic view
                dynamicView.addMemberEntity("PC", "PartyContactMech");
                dynamicView.addMemberEntity("TM", "TelecomNumber");
                dynamicView.addAlias("PC", "contactMechId");
                dynamicView.addAlias("TM", "countryCode");
                dynamicView.addAlias("TM", "areaCode");
                dynamicView.addAlias("TM", "contactNumber");
                dynamicView.addViewLink("PT", "PC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("partyId"));
                dynamicView.addViewLink("PC", "TM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
                // filter on countryCode
                String countryCode = (String) context.get("countryCode");
                if (UtilValidate.isNotEmpty(countryCode)) {
                    paramList = paramList + "&countryCode=" + countryCode;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("countryCode"), EntityOperator.EQUALS, EntityFunction.UPPER(countryCode)));
                }
                // filter on areaCode
                String areaCode = (String) context.get("areaCode");
                if (UtilValidate.isNotEmpty(areaCode)) {
                    paramList = paramList + "&areaCode=" + areaCode;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("areaCode"), EntityOperator.EQUALS, EntityFunction.UPPER(areaCode)));
                }
                // filter on contact number
                String contactNumber = (String) context.get("contactNumber");
                if (UtilValidate.isNotEmpty(contactNumber)) {
                    paramList = paramList + "&contactNumber=" + contactNumber;
                    andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("contactNumber"), EntityOperator.EQUALS, EntityFunction.UPPER(contactNumber)));
                }
                fieldsToSelect.add("contactNumber");
                fieldsToSelect.add("areaCode");
            }
            // build the main condition
            if (andExprs.size() > 0) {
                mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
            }
        }
        Debug.logInfo("In findParty mainCond=" + mainCond, module);
        String sortField = (String) context.get("sortField");
        if (UtilValidate.isNotEmpty(sortField)) {
            orderBy.add(sortField);
        }
        // do the lookup
        if (mainCond != null || "Y".equals(showAll)) {
            lowIndex = viewIndex * viewSize + 1;
            highIndex = (viewIndex + 1) * viewSize;
            // set distinct on so we only get one row per order
            // using list iterator
            EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicView).where(mainCond).orderBy(orderBy).cursorScrollInsensitive().fetchSize(highIndex).distinct();
            try (EntityListIterator pli = eq.queryIterator()) {
                // get the partial list for this page
                partyList = pli.getPartialList(lowIndex, viewSize);
                // attempt to get the full size
                partyListSize = pli.getResultsSizeAfterPartialList();
                if (highIndex > partyListSize) {
                    highIndex = partyListSize;
                }
            } catch (GenericEntityException e) {
                String errMsg = "Failure in party find operation, rolling back transaction: " + e.toString();
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "PartyLookupPartyError", UtilMisc.toMap("errMessage", e.toString()), locale));
            }
        } else {
            partyListSize = 0;
        }
    }
    if (partyList == null) {
        partyList = new LinkedList<>();
    }
    result.put("partyList", partyList);
    result.put("partyListSize", Integer.valueOf(partyListSize));
    result.put("paramList", paramList);
    result.put("highIndex", Integer.valueOf(highIndex));
    result.put("lowIndex", Integer.valueOf(lowIndex));
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IOException(java.io.IOException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 5 with DynamicViewEntity

use of org.apache.ofbiz.entity.model.DynamicViewEntity in project ofbiz-framework by apache.

the class ProductSearchSession method getCountForProductCategory.

/**
 * This method returns count of products in a given category (including all sub categories), the constraint being
 * applied on current ProductSearchConstraint list in session.
 * @param productCategoryId productCategoryId for which the count should be returned.
 * @param session Current session.
 * @param delegator The delegator object.
 * @return The long value of count of products.
 */
public static long getCountForProductCategory(String productCategoryId, HttpSession session, Delegator delegator) {
    String visitId = VisitHandler.getVisitId(session);
    ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
        productSearchContext.addProductSearchConstraints(productSearchConstraintList);
    }
    productSearchContext.finishKeywordConstraints();
    productSearchContext.finishCategoryAndFeatureConstraints();
    DynamicViewEntity dynamicViewEntity = productSearchContext.dynamicViewEntity;
    List<EntityCondition> entityConditionList = productSearchContext.entityConditionList;
    List<String> fieldsToSelect = new LinkedList<>();
    dynamicViewEntity.addMemberEntity("PCMC", "ProductCategoryMember");
    dynamicViewEntity.addAlias("PCMC", "pcmcProductCategoryId", "productCategoryId", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "pcmcFromDate", "fromDate", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "pcmcThruDate", "thruDate", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "categoryCount", "productId", null, null, null, "count-distinct");
    dynamicViewEntity.addViewLink("PROD", "PCMC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productId"));
    fieldsToSelect.add("categoryCount");
    entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("pcmcThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("pcmcThruDate", EntityOperator.GREATER_THAN, productSearchContext.nowTimestamp)));
    entityConditionList.add(EntityCondition.makeCondition("pcmcFromDate", EntityOperator.LESS_THAN, productSearchContext.nowTimestamp));
    Set<String> productCategoryIdSet = new HashSet<>();
    ProductSearch.getAllSubCategoryIds(productCategoryId, productCategoryIdSet, delegator, productSearchContext.nowTimestamp);
    entityConditionList.add(EntityCondition.makeCondition("pcmcProductCategoryId", EntityOperator.IN, productCategoryIdSet));
    Long categoryCount = Long.valueOf(0);
    EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicViewEntity).where(entityConditionList).orderBy(productSearchContext.orderByList).cursorScrollInsensitive();
    try (EntityListIterator eli = eq.queryIterator()) {
        GenericValue searchResult = null;
        while ((searchResult = eli.next()) != null) {
            categoryCount = searchResult.getLong("categoryCount");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error in product search", module);
    }
    return categoryCount;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint) HashSet(java.util.HashSet)

Aggregations

GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)9 GenericValue (org.apache.ofbiz.entity.GenericValue)9 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)9 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)9 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)8 Delegator (org.apache.ofbiz.entity.Delegator)6 Locale (java.util.Locale)5 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)5 HashMap (java.util.HashMap)4 LinkedList (java.util.LinkedList)4 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)4 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4 Timestamp (java.sql.Timestamp)3 Map (java.util.Map)3 ProductSearchConstraint (org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)3 ProductSearchContext (org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext)3 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 IOException (java.io.IOException)1 BigDecimal (java.math.BigDecimal)1