Search in sources :

Example 6 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class PaymentGatewayServices method retryFailedAuths.

public static Map<String, Object> retryFailedAuths(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    EntityQuery eq = EntityQuery.use(delegator).from("OrderPaymentPreference").where(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_NOT_AUTH"), EntityCondition.makeCondition("processAttempt", EntityOperator.GREATER_THAN, Long.valueOf(0))).orderBy("orderId");
    try (EntityListIterator eli = eq.queryIterator()) {
        List<String> processList = new LinkedList<>();
        if (eli != null) {
            Debug.logInfo("Processing failed order re-auth(s)", module);
            GenericValue value = null;
            while (((value = eli.next()) != null)) {
                String orderId = value.getString("orderId");
                if (!processList.contains(orderId)) {
                    // just try each order once
                    try {
                        // each re-try is independent of each other; if one fails it should not effect the others
                        dispatcher.runAsync("retryFailedOrderAuth", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
                        processList.add(orderId);
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) 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) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList)

Example 7 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery 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 8 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class ContentEvents method updateAllContentKeywords.

/**
 * Updates/adds keywords for all contents
 *
 * @param request HTTPRequest object for the current request
 * @param response HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 */
public static String updateAllContentKeywords(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");
    String updateMode = "CREATE";
    String errMsg = null;
    String doAll = request.getParameter("doAll");
    // check permissions before moving on...
    if (!security.hasEntityPermission("CONTENTMGR", "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "contentevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    int numConts = 0;
    int errConts = 0;
    boolean beganTx = false;
    EntityQuery contentQuery = EntityQuery.use(delegator).from("Content");
    try {
        // begin the transaction
        beganTx = TransactionUtil.begin(7200);
        if (Debug.infoOn()) {
            long count = contentQuery.queryCount();
            Debug.logInfo("========== Found " + count + " contents to index ==========", module);
        }
        GenericValue content;
        try (EntityListIterator entityListIterator = contentQuery.queryIterator()) {
            while ((content = entityListIterator.next()) != null) {
                ContentKeywordIndex.indexKeywords(content, "Y".equals(doAll));
                numConts++;
                if (numConts % 500 == 0) {
                    Debug.logInfo("Keywords indexed for " + numConts + " so far", module);
                }
            }
        } catch (GenericEntityException e) {
            errMsg = "[ContentEvents.updateAllContentKeywords] Could not create content-keyword (write error); message: " + e.getMessage();
            Debug.logWarning(errMsg, module);
            errConts++;
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
        }
    } catch (GenericEntityException gee) {
        Debug.logWarning(gee, gee.getMessage(), module);
        Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
        errMsg = UtilProperties.getMessage(resource, "contentevents.error_getting_content_list", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        try {
            TransactionUtil.rollback(beganTx, gee.getMessage(), gee);
        } catch (GenericTransactionException e1) {
            Debug.logError(e1, module);
        }
        return "error";
    }
    // commit the transaction
    try {
        TransactionUtil.commit(beganTx);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    if (errConts == 0) {
        Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
        errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
        return "success";
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
        messageMap.put("errConts", Integer.toString(errConts));
        errMsg = UtilProperties.getMessage(resource, "contentevents.keyword_creation_complete_for_contents_with_errors", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Security(org.apache.ofbiz.security.Security) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) Map(java.util.Map)

Example 9 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class ContentMapFacade method get.

// implemented get method
public Object get(Object obj) {
    if (!(obj instanceof String)) {
        Debug.logWarning("Key parameters must be a string", module);
        return null;
    }
    String name = (String) obj;
    if ("fields".equalsIgnoreCase(name)) {
        // fields key, returns value object
        if (this.fields != null) {
            return fields;
        }
        try {
            EntityQuery contentQuery = EntityQuery.use(delegator).from("Content").where("contentId", contentId);
            if (cache) {
                contentQuery.cache();
            }
            this.fields = contentQuery.queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        return this.fields;
    } else if ("link".equalsIgnoreCase(name)) {
        // link to this content
        RequestHandler rh = (RequestHandler) this.context.get("_REQUEST_HANDLER_");
        HttpServletRequest request = (HttpServletRequest) this.context.get("request");
        HttpServletResponse response = (HttpServletResponse) this.context.get("response");
        if (rh != null && request != null && response != null) {
            String webSiteId = WebSiteWorker.getWebSiteId(request);
            Delegator delegator = (Delegator) request.getAttribute("delegator");
            String contentUri = this.contentId;
            // so we're only looking for a direct alias using contentId
            if (webSiteId != null && delegator != null) {
                try {
                    GenericValue webSitePathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("mapKey", null, "webSiteId", webSiteId, "contentId", this.contentId).orderBy("-fromDate").cache().filterByDate().queryFirst();
                    if (webSitePathAlias != null) {
                        contentUri = webSitePathAlias.getString("pathAlias");
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
            String contextLink = rh.makeLink(request, response, contentUri, true, false, true);
            return contextLink;
        } else {
            return this.contentId;
        }
    } else if ("data".equalsIgnoreCase(name) || "dataresource".equalsIgnoreCase(name)) {
        // data (resource) object
        return dataResource;
    } else if ("subcontent_all".equalsIgnoreCase(name)) {
        // subcontent list of ordered subcontent
        List<ContentMapFacade> subContent = new LinkedList<ContentMapFacade>();
        List<GenericValue> subs = null;
        try {
            Map<String, Object> expressions = new HashMap<String, Object>();
            expressions.put("contentIdStart", contentId);
            if (!this.mapKeyFilter.equals("")) {
                expressions.put("caMapKey", this.mapKeyFilter);
            }
            if (!this.statusFilter.equals("")) {
                expressions.put("statusId", this.statusFilter);
            }
            subs = EntityQuery.use(delegator).from("ContentAssocViewTo").where(expressions).orderBy(this.sortOrder).filterByDate().cache(cache).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (subs != null) {
            for (GenericValue v : subs) {
                subContent.add(new ContentMapFacade(dispatcher, v.getString("contentId"), context, locale, mimeType, cache));
            }
        }
        return subContent;
    } else if ("subcontent".equalsIgnoreCase(name)) {
        // return the subcontent object
        return this.subContent;
    } else if ("metadata".equalsIgnoreCase(name)) {
        // return list of metaData by predicate ID
        return this.metaData;
    } else if ("content".equalsIgnoreCase(name)) {
        // content; returns object from contentId
        return content;
    } else if ("render".equalsIgnoreCase(name)) {
        // render this content
        return this.renderThis();
    }
    return null;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HttpServletResponse(javax.servlet.http.HttpServletResponse) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with EntityQuery

use of org.apache.ofbiz.entity.util.EntityQuery in project ofbiz-framework by apache.

the class InvoiceServices method createCommissionInvoices.

// Service for creating commission invoices
public static Map<String, Object> createCommissionInvoices(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
    List<Map<String, String>> invoicesCreated = new LinkedList<>();
    Map<String, List<Map<String, Object>>> commissionParties = new HashMap<>();
    for (String salesInvoiceId : salesInvoiceIds) {
        List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
        BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
        if (amountTotal.signum() == 0) {
            Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
        }
        BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
        GenericValue invoice = null;
        boolean isReturn = false;
        List<String> billFromVendorInvoiceRoles;
        List<GenericValue> invoiceItems;
        try {
            List<EntityExpr> invoiceRoleConds = UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
            EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole").where(invoiceRoleConds);
            billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId", true);
            invoiceRoleConds = UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP"));
            // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice.
            if (UtilValidate.isEmpty(salesRepPartyIds)) {
                salesRepPartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isEmpty(salesRepPartyIds)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "No party found with role sales representative for sales invoice " + salesInvoiceId, locale));
                }
            } else {
                List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                    salesRepPartyIds = UtilGenerics.checkList(CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                }
            }
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne();
            String invoiceTypeId = invoice.getString("invoiceTypeId");
            if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) {
                isReturn = true;
            } else if (!"SALES_INVOICE".equals(invoiceTypeId)) {
                Debug.logWarning("This type of invoice has no commission; returning success", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale));
            }
            invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId).queryList();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        // Determine commissions for various parties.
        for (GenericValue invoiceItem : invoiceItems) {
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal quantity = invoiceItem.getBigDecimal("quantity");
            amount = invoiceItem.getBigDecimal("amount");
            amount = isReturn ? amount.negate() : amount;
            String productId = invoiceItem.getString("productId");
            String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
            String invoiceId = invoiceItem.getString("invoiceId");
            // Determine commission parties for this invoiceItem
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> resultMap = null;
                try {
                    resultMap = dispatcher.runSync("getCommissionForProduct", UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId", invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity", quantity, "userLogin", userLogin));
                    if (ServiceUtil.isError(resultMap)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultMap));
                    }
                } catch (GenericServiceException e) {
                    return ServiceUtil.returnError(e.getMessage());
                }
                // build a Map of partyIds (both to and from) in a commission and the amounts
                // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
                List<Map<String, Object>> itemCommissions = UtilGenerics.checkList(resultMap.get("commissions"));
                if (UtilValidate.isNotEmpty(itemCommissions)) {
                    for (Map<String, Object> commissionMap : itemCommissions) {
                        commissionMap.put("invoice", invoice);
                        commissionMap.put("appliedFraction", appliedFraction);
                        if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
                            continue;
                        }
                        String partyIdFromTo = (String) commissionMap.get("partyIdFrom") + (String) commissionMap.get("partyIdTo");
                        if (!commissionParties.containsKey(partyIdFromTo)) {
                            commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                        } else {
                            (commissionParties.get(partyIdFromTo)).add(commissionMap);
                        }
                    }
                }
            }
        }
    }
    Timestamp now = UtilDateTime.nowTimestamp();
    // Create invoice for each commission receiving party
    for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
        List<GenericValue> toStore = new LinkedList<>();
        List<Map<String, Object>> commList = commissionParty.getValue();
        // get the billing parties
        if (UtilValidate.isEmpty(commList)) {
            continue;
        }
        // From and To are reversed between commission and invoice
        String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom");
        String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo");
        GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice");
        BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction");
        Long days = (Long) (commList.get(0)).get("days");
        // create the invoice record
        // To and From are in commission's sense, opposite for invoice
        Map<String, Object> createInvoiceMap = new HashMap<>();
        createInvoiceMap.put("partyId", partyIdBillTo);
        createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
        createInvoiceMap.put("invoiceDate", now);
        // if there were days associated with the commission agreement, then set a dueDate for the invoice.
        if (days != null) {
            createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days));
        }
        createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE");
        // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
        createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS");
        createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
        createInvoiceMap.put("userLogin", userLogin);
        // store the invoice first
        Map<String, Object> createInvoiceResult;
        try {
            createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
            if (ServiceUtil.isError(createInvoiceResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, null);
            }
        } catch (GenericServiceException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, null);
        }
        String invoiceId = (String) createInvoiceResult.get("invoiceId");
        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue partyContactMechPurpose = null;
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION").queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION").queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        // create the item records
        for (Map<String, Object> commissionMap : commList) {
            BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction);
            BigDecimal quantity = (BigDecimal) commissionMap.get("quantity");
            String invoiceIdFrom = (String) commissionMap.get("invoiceId");
            String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId");
            elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
            Map<String, Object> resMap = null;
            try {
                resMap = dispatcher.runSync("createInvoiceItem", UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"), "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount", elemAmount, "userLogin", userLogin));
                if (ServiceUtil.isError(resMap)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale), null, null, resMap);
                }
                resMap = dispatcher.runSync("createInvoiceItemAssoc", UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom", invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo", resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE", "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity", quantity, "amount", elemAmount, "userLogin", userLogin));
                if (ServiceUtil.isError(resMap)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resMap));
                }
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
        }
        // store value objects
        try {
            delegator.storeAll(toStore);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem", UtilMisc.toMap("reason", e.toString()), locale));
        }
        invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId, "salesRepresentative ", partyIdBillFrom));
    }
    String invCreated = Integer.toString(invoicesCreated.size());
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale));
    Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module);
    result.put("invoicesCreated", invoicesCreated);
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) LinkedList(java.util.LinkedList) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)22 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)22 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)20 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)19 LinkedList (java.util.LinkedList)15 Delegator (org.apache.ofbiz.entity.Delegator)15 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)14 Timestamp (java.sql.Timestamp)11 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 HashMap (java.util.HashMap)10 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)10 Locale (java.util.Locale)9 Map (java.util.Map)7 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)5 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 ProductSearchConstraint (org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)4 ProductSearchContext (org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext)4 GeneralException (org.apache.ofbiz.base.util.GeneralException)3