Search in sources :

Example 26 with Security

use of org.apache.ofbiz.security.Security 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 27 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ShoppingCartEvents method initializeOrderEntry.

/**
 * Initialize order entry *
 */
public static String initializeOrderEntry(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    HttpSession session = request.getSession();
    Security security = (Security) request.getAttribute("security");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    Locale locale = UtilHttp.getLocale(request);
    String productStoreId = request.getParameter("productStoreId");
    if (UtilValidate.isNotEmpty(productStoreId)) {
        session.setAttribute("productStoreId", productStoreId);
    }
    ShoppingCart cart = getCartObject(request);
    // TODO: re-factor and move this inside the ShoppingCart constructor
    String orderMode = request.getParameter("orderMode");
    if (orderMode != null) {
        cart.setOrderType(orderMode);
        session.setAttribute("orderMode", orderMode);
    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderPleaseSelectEitherSaleOrPurchaseOrder", locale));
        return "error";
    }
    // check the selected product store
    GenericValue productStore = null;
    if (UtilValidate.isNotEmpty(productStoreId)) {
        productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
        if (productStore != null) {
            // check permission for taking the order
            boolean hasPermission = false;
            if (("PURCHASE_ORDER".equals(cart.getOrderType())) && (security.hasEntityPermission("ORDERMGR", "_PURCHASE_CREATE", session))) {
                hasPermission = true;
            } else if ("SALES_ORDER".equals(cart.getOrderType())) {
                if (security.hasEntityPermission("ORDERMGR", "_SALES_CREATE", session)) {
                    hasPermission = true;
                } else {
                    // if the user is a rep of the store, then he also has permission
                    List<GenericValue> storeReps = null;
                    try {
                        storeReps = EntityQuery.use(delegator).from("ProductStoreRole").where("productStoreId", productStore.getString("productStoreId"), "partyId", userLogin.getString("partyId"), "roleTypeId", "SALES_REP").filterByDate().queryList();
                    } catch (GenericEntityException gee) {
                        request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
                        return "error";
                    }
                    if (UtilValidate.isNotEmpty(storeReps)) {
                        hasPermission = true;
                    }
                }
            }
            if (hasPermission) {
                cart = ShoppingCartEvents.getCartObject(request, null, productStore.getString("defaultCurrencyUomId"));
            } else {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToTakeOrdersForThisStore", locale));
                cart.clear();
                session.removeAttribute("orderMode");
                return "error";
            }
            cart.setProductStoreId(productStoreId);
        } else {
            cart.setProductStoreId(null);
        }
    }
    if ("SALES_ORDER".equals(cart.getOrderType()) && UtilValidate.isEmpty(cart.getProductStoreId())) {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderAProductStoreMustBeSelectedForASalesOrder", locale));
        cart.clear();
        session.removeAttribute("orderMode");
        return "error";
    }
    String salesChannelEnumId = request.getParameter("salesChannelEnumId");
    if (UtilValidate.isNotEmpty(salesChannelEnumId)) {
        cart.setChannelType(salesChannelEnumId);
    }
    // set party info
    String partyId = request.getParameter("supplierPartyId");
    cart.setAttribute("supplierPartyId", partyId);
    String originOrderId = request.getParameter("originOrderId");
    cart.setAttribute("originOrderId", originOrderId);
    if (UtilValidate.isNotEmpty(request.getParameter("partyId"))) {
        partyId = request.getParameter("partyId");
    }
    String userLoginId = request.getParameter("userLoginId");
    if (partyId != null || userLoginId != null) {
        if (UtilValidate.isEmpty(partyId) && UtilValidate.isNotEmpty(userLoginId)) {
            GenericValue thisUserLogin = null;
            try {
                thisUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
            } catch (GenericEntityException gee) {
                request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
                return "error";
            }
            if (thisUserLogin != null) {
                partyId = thisUserLogin.getString("partyId");
            } else {
                partyId = userLoginId;
            }
        }
        if (UtilValidate.isNotEmpty(partyId)) {
            GenericValue thisParty = null;
            try {
                thisParty = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
            } catch (GenericEntityException gee) {
                request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
                return "error";
            }
            if (thisParty == null) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderCouldNotLocateTheSelectedParty", locale));
                return "error";
            }
            cart.setOrderPartyId(partyId);
            if ("PURCHASE_ORDER".equals(cart.getOrderType())) {
                cart.setBillFromVendorPartyId(partyId);
            }
        } else if (partyId != null && partyId.length() == 0) {
            cart.setOrderPartyId("_NA_");
            partyId = null;
        }
    } else {
        partyId = cart.getPartyId();
        if (partyId != null && "_NA_".equals(partyId)) {
            partyId = null;
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HttpSession(javax.servlet.http.HttpSession) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Security(org.apache.ofbiz.security.Security)

Example 28 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ContactMechServices method createTelecomNumber.

// ============================================================================
// ============================================================================
/**
 * Creates a TelecomNumber
 * <b>security check</b>: userLogin partyId must equal partyId, or must have PARTYMGR_CREATE permission
 *@param ctx The DispatchContext that this service is operating in
 *@param context Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> createTelecomNumber(DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<>();
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    Timestamp now = UtilDateTime.nowTimestamp();
    List<GenericValue> toBeStored = new LinkedList<>();
    String partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, result, "PARTYMGR", "_PCM_CREATE");
    if (result.size() > 0) {
        return result;
    }
    String contactMechTypeId = "TELECOM_NUMBER";
    String newCmId = null;
    try {
        newCmId = delegator.getNextSeqId("ContactMech");
    } catch (IllegalArgumentException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "contactmechservices.could_not_create_contact_info_id_generation_failure", locale));
    }
    GenericValue tempContactMech = delegator.makeValue("ContactMech", UtilMisc.toMap("contactMechId", newCmId, "contactMechTypeId", contactMechTypeId));
    toBeStored.add(tempContactMech);
    toBeStored.add(delegator.makeValue("PartyContactMech", UtilMisc.toMap("partyId", partyId, "contactMechId", newCmId, "fromDate", now, "roleTypeId", context.get("roleTypeId"), "allowSolicitation", context.get("allowSolicitation"), "extension", context.get("extension"))));
    toBeStored.add(delegator.makeValue("TelecomNumber", UtilMisc.toMap("contactMechId", newCmId, "countryCode", context.get("countryCode"), "areaCode", context.get("areaCode"), "contactNumber", context.get("contactNumber"))));
    try {
        delegator.storeAll(toBeStored);
    } catch (GenericEntityException e) {
        Debug.logWarning(e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "contactmechservices.could_not_create_contact_info_write", UtilMisc.toMap("errMessage", e.getMessage()), locale));
    }
    result.put("contactMechId", newCmId);
    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 29 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ContactMechServices method createPostalAddress.

// ============================================================================
// ============================================================================
/**
 * Creates a PostalAddress
 * <b>security check</b>: userLogin partyId must equal partyId, or must have PARTYMGR_CREATE permission
 *@param ctx The DispatchContext that this service is operating in
 *@param context Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> createPostalAddress(DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<>();
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    Timestamp now = UtilDateTime.nowTimestamp();
    List<GenericValue> toBeStored = new LinkedList<>();
    String partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, result, "PARTYMGR", "_PCM_CREATE");
    if (result.size() > 0) {
        return result;
    }
    String contactMechTypeId = "POSTAL_ADDRESS";
    String newCmId = null;
    try {
        newCmId = delegator.getNextSeqId("ContactMech");
    } catch (IllegalArgumentException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "contactmechservices.could_not_create_contact_info_id_generation_failure", locale));
    }
    GenericValue tempContactMech = delegator.makeValue("ContactMech", UtilMisc.toMap("contactMechId", newCmId, "contactMechTypeId", contactMechTypeId));
    toBeStored.add(tempContactMech);
    // don't create a PartyContactMech if there is no party; we define no party as sending _NA_ as partyId
    if (!"_NA_".equals(partyId)) {
        toBeStored.add(delegator.makeValue("PartyContactMech", UtilMisc.toMap("partyId", partyId, "contactMechId", newCmId, "fromDate", now, "roleTypeId", context.get("roleTypeId"), "allowSolicitation", context.get("allowSolicitation"), "extension", context.get("extension"))));
    }
    GenericValue newAddr = delegator.makeValue("PostalAddress");
    newAddr.set("contactMechId", newCmId);
    newAddr.set("toName", context.get("toName"));
    newAddr.set("attnName", context.get("attnName"));
    newAddr.set("address1", context.get("address1"));
    newAddr.set("address2", context.get("address2"));
    newAddr.set("directions", context.get("directions"));
    newAddr.set("city", context.get("city"));
    newAddr.set("postalCode", context.get("postalCode"));
    newAddr.set("postalCodeExt", context.get("postalCodeExt"));
    newAddr.set("stateProvinceGeoId", context.get("stateProvinceGeoId"));
    newAddr.set("countryGeoId", context.get("countryGeoId"));
    newAddr.set("postalCodeGeoId", context.get("postalCodeGeoId"));
    toBeStored.add(newAddr);
    try {
        delegator.storeAll(toBeStored);
    } catch (GenericEntityException e) {
        Debug.logWarning(e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "contactmechservices.could_not_create_contact_info_write", UtilMisc.toMap("errMessage", e.getMessage()), locale));
    }
    result.put("contactMechId", newCmId);
    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 30 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class CheckPermissionTransform method getWriter.

@Override
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
    final StringBuilder buf = new StringBuilder();
    final Environment env = Environment.getCurrentEnvironment();
    final Map<String, Object> templateCtx = FreeMarkerWorker.createEnvironmentMap(env);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
    final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    FreeMarkerWorker.getSiteParameters(request, templateCtx);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    final String mode = (String) templateCtx.get("mode");
    final String quickCheckContentId = (String) templateCtx.get("quickCheckContentId");
    final Map<String, Object> savedValues = new HashMap<>();
    return new LoopWriter(out) {

        @Override
        public void write(char[] cbuf, int off, int len) {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public int onStart() throws TemplateModelException, IOException {
            List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
            GenericValue currentContent = null;
            String contentAssocPredicateId = (String) templateCtx.get("contentAssocPredicateId");
            String strNullThruDatesOnly = (String) templateCtx.get("nullThruDatesOnly");
            Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE;
            GenericValue val = null;
            try {
                val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
            } catch (GeneralException e) {
                throw new RuntimeException("Error getting current content. " + e.toString());
            }
            currentContent = val;
            if (currentContent == null) {
                currentContent = delegator.makeValue("Content");
                currentContent.put("ownerContentId", templateCtx.get("ownerContentId"));
            }
            Security security = null;
            if (request != null) {
                security = (Security) request.getAttribute("security");
            }
            String statusId = (String) currentContent.get("statusId");
            String passedStatusId = (String) templateCtx.get("statusId");
            List<String> statusList = StringUtil.split(passedStatusId, "|");
            if (statusList == null) {
                statusList = new LinkedList<>();
            }
            if (UtilValidate.isNotEmpty(statusId) && !statusList.contains(statusId)) {
                statusList.add(statusId);
            }
            String targetPurpose = (String) templateCtx.get("contentPurposeList");
            List<String> purposeList = StringUtil.split(targetPurpose, "|");
            String entityOperation = (String) templateCtx.get("entityOperation");
            String targetOperation = (String) templateCtx.get("targetOperation");
            if (UtilValidate.isEmpty(targetOperation)) {
                if (UtilValidate.isNotEmpty(entityOperation)) {
                    targetOperation = "CONTENT" + entityOperation;
                }
            }
            List<String> targetOperationList = StringUtil.split(targetOperation, "|");
            if (targetOperationList.size() == 0) {
                throw new IOException("targetOperationList has zero size.");
            }
            List<String> roleList = new LinkedList<>();
            String privilegeEnumId = (String) currentContent.get("privilegeEnumId");
            Map<String, Object> results = EntityPermissionChecker.checkPermission(currentContent, statusList, userLogin, purposeList, targetOperationList, roleList, delegator, security, entityOperation, privilegeEnumId, quickCheckContentId);
            boolean isError = ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                throw new IOException(ModelService.RESPONSE_MESSAGE);
            }
            String permissionStatus = (String) results.get("permissionStatus");
            if (UtilValidate.isEmpty(permissionStatus) || !"granted".equals(permissionStatus)) {
                String errorMessage = "Permission to add response is denied (2)";
                PermissionRecorder recorder = (PermissionRecorder) results.get("permissionRecorder");
                if (recorder != null) {
                    String permissionMessage = recorder.toHtml();
                    errorMessage += " \n " + permissionMessage;
                }
                templateCtx.put("permissionErrorMsg", errorMessage);
            }
            if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) {
                FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
                if (mode == null || !"not-equals".equalsIgnoreCase(mode)) {
                    return TransformControl.EVALUATE_BODY;
                }
                return TransformControl.SKIP_BODY;
            }
            if (mode == null || !"not-equals".equalsIgnoreCase(mode)) {
                return TransformControl.SKIP_BODY;
            }
            return TransformControl.EVALUATE_BODY;
        }

        @Override
        public void close() throws IOException {
            FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
            String wrappedContent = buf.toString();
            out.write(wrappedContent);
        }
    };
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) IOException(java.io.IOException) Security(org.apache.ofbiz.security.Security) PermissionRecorder(org.apache.ofbiz.content.content.PermissionRecorder) LinkedList(java.util.LinkedList) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) LoopWriter(org.apache.ofbiz.webapp.ftl.LoopWriter) Environment(freemarker.core.Environment) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Security (org.apache.ofbiz.security.Security)79 GenericValue (org.apache.ofbiz.entity.GenericValue)69 Delegator (org.apache.ofbiz.entity.Delegator)60 Locale (java.util.Locale)56 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)54 HashMap (java.util.HashMap)36 Timestamp (java.sql.Timestamp)27 LinkedList (java.util.LinkedList)27 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)20 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)18 Map (java.util.Map)12 HttpSession (javax.servlet.http.HttpSession)7 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 BigDecimal (java.math.BigDecimal)6 List (java.util.List)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)4 File (java.io.File)3