Search in sources :

Example 51 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class OrderReturnServices method processRefundReturn.

// refund (cash/charge) return
public static Map<String, Object> processRefundReturn(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String returnId = (String) context.get("returnId");
    String returnTypeId = (String) context.get("returnTypeId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    GenericValue returnHeader = null;
    List<GenericValue> returnItems = null;
    try {
        returnHeader = EntityQuery.use(delegator).from("ReturnHeader").where("returnId", returnId).queryOne();
        if (returnHeader != null) {
            returnItems = returnHeader.getRelated("ReturnItem", UtilMisc.toMap("returnTypeId", returnTypeId), null, false);
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems looking up return information", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorGettingReturnHeaderItemInformation", locale));
    }
    BigDecimal adjustments = getReturnAdjustmentTotal(delegator, UtilMisc.toMap("returnId", returnId, "returnTypeId", returnTypeId));
    if (returnHeader != null && (UtilValidate.isNotEmpty(returnItems) || adjustments.compareTo(ZERO) > 0)) {
        Map<String, List<GenericValue>> itemsByOrder = new HashMap<>();
        Map<String, BigDecimal> totalByOrder = new HashMap<>();
        // make sure total refunds on a return don't exceed amount of returned orders
        Map<String, Object> serviceResult = null;
        try {
            serviceResult = dispatcher.runSync("checkPaymentAmountForRefund", UtilMisc.toMap("returnId", returnId));
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problem running the checkPaymentAmountForRefund service", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsWithCheckPaymentAmountForRefund", locale));
        }
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
        groupReturnItemsByOrder(returnItems, itemsByOrder, totalByOrder, delegator, returnId, returnTypeId);
        // process each one by order
        for (Map.Entry<String, List<GenericValue>> entry : itemsByOrder.entrySet()) {
            String orderId = entry.getKey();
            List<GenericValue> items = entry.getValue();
            BigDecimal orderTotal = totalByOrder.get(orderId);
            // get order header & payment prefs
            GenericValue orderHeader = null;
            List<GenericValue> orderPayPrefs = null;
            try {
                orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
                // sort these desending by maxAmount
                orderPayPrefs = orderHeader.getRelated("OrderPaymentPreference", null, UtilMisc.toList("-maxAmount"), false);
                List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_SETTLED"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_RECEIVED"));
                orderPayPrefs = EntityUtil.filterByOr(orderPayPrefs, exprs);
                // Check for replacement order
                if (UtilValidate.isEmpty(orderPayPrefs)) {
                    GenericValue orderItemAssoc = EntityQuery.use(delegator).from("OrderItemAssoc").where("toOrderId", orderId, "orderItemAssocTypeId", "REPLACEMENT").queryFirst();
                    if (orderItemAssoc != null) {
                        String originalOrderId = orderItemAssoc.getString("orderId");
                        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", originalOrderId).queryOne();
                        orderPayPrefs = orderHeader.getRelated("OrderPaymentPreference", null, UtilMisc.toList("-maxAmount"), false);
                        orderPayPrefs = EntityUtil.filterByOr(orderPayPrefs, exprs);
                        orderId = originalOrderId;
                    }
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot get Order details for #" + orderId, module);
                continue;
            }
            OrderReadHelper orderReadHelper = new OrderReadHelper(delegator, orderId);
            // Determine the fall-through refund paymentMethodId from the PartyAcctgPreference of the owner of the productStore for the order
            GenericValue productStore = orderReadHelper.getProductStore();
            if (UtilValidate.isEmpty(productStore) || UtilValidate.isEmpty(productStore.get("payToPartyId"))) {
                Debug.logError("No payToPartyId found for orderId " + orderId, module);
            } else {
                GenericValue orgAcctgPref = null;
                Map<String, Object> acctgPreferencesResult = null;
                try {
                    acctgPreferencesResult = dispatcher.runSync("getPartyAccountingPreferences", UtilMisc.toMap("organizationPartyId", productStore.get("payToPartyId"), "userLogin", userLogin));
                    if (ServiceUtil.isError(acctgPreferencesResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(acctgPreferencesResult));
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, "Error retrieving PartyAcctgPreference for partyId " + productStore.get("payToPartyId"), module);
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsWithGetPartyAcctgPreferences", locale));
                }
                orgAcctgPref = (GenericValue) acctgPreferencesResult.get("partyAccountingPreference");
                if (orgAcctgPref != null) {
                    try {
                        orgAcctgPref.getRelatedOne("PaymentMethod", false);
                    } catch (GenericEntityException e) {
                        Debug.logError("Error retrieving related refundPaymentMethod from PartyAcctgPreference for partyId " + productStore.get("payToPartyId"), module);
                    }
                }
            }
            // now; for all timestamps
            Timestamp now = UtilDateTime.nowTimestamp();
            // Assemble a map of orderPaymentPreferenceId -> list of maps of (OPP and availableAmountForRefunding)
            // where availableAmountForRefunding = receivedAmount - alreadyRefundedAmount
            // We break the OPPs down this way because we need to process the refunds to payment methods in a particular order
            Map<String, BigDecimal> receivedPaymentTotalsByPaymentMethod = orderReadHelper.getReceivedPaymentTotalsByPaymentMethod();
            Map<String, BigDecimal> refundedTotalsByPaymentMethod = orderReadHelper.getReturnedTotalsByPaymentMethod();
            // getOrderPaymentPreferenceTotalByType has been called because getReceivedPaymentTotalsByPaymentMethod does not
            // return payments captured from Billing Account.This is because when payment is captured from Billing Account
            // then no entry is maintained in Payment entity.
            BigDecimal receivedPaymentTotalsByBillingAccount = orderReadHelper.getOrderPaymentPreferenceTotalByType("EXT_BILLACT");
            /*
                 * Go through the OrderPaymentPreferences and determine how much remains to be refunded for each.
                 * Then group these refund amounts and orderPaymentPreferences by paymentMethodTypeId.  That is,
                 * the intent is to get the refundable amounts per orderPaymentPreference, grouped by payment method type.
                 */
            Map<String, List<Map<String, Object>>> prefSplitMap = new HashMap<>();
            for (GenericValue orderPayPref : orderPayPrefs) {
                String paymentMethodTypeId = orderPayPref.getString("paymentMethodTypeId");
                String orderPayPrefKey = orderPayPref.getString("paymentMethodId") != null ? orderPayPref.getString("paymentMethodId") : orderPayPref.getString("paymentMethodTypeId");
                // See how much we can refund to the payment method
                BigDecimal orderPayPrefReceivedTotal = ZERO;
                if (receivedPaymentTotalsByPaymentMethod.containsKey(orderPayPrefKey)) {
                    orderPayPrefReceivedTotal = orderPayPrefReceivedTotal.add(receivedPaymentTotalsByPaymentMethod.get(orderPayPrefKey)).setScale(decimals, rounding);
                }
                if (receivedPaymentTotalsByBillingAccount != null) {
                    orderPayPrefReceivedTotal = orderPayPrefReceivedTotal.add(receivedPaymentTotalsByBillingAccount);
                }
                BigDecimal orderPayPrefRefundedTotal = ZERO;
                if (refundedTotalsByPaymentMethod.containsKey(orderPayPrefKey)) {
                    orderPayPrefRefundedTotal = orderPayPrefRefundedTotal.add(refundedTotalsByPaymentMethod.get(orderPayPrefKey)).setScale(decimals, rounding);
                }
                BigDecimal orderPayPrefAvailableTotal = orderPayPrefReceivedTotal.subtract(orderPayPrefRefundedTotal);
                // add the refundable amount and orderPaymentPreference to the paymentMethodTypeId map
                if (orderPayPrefAvailableTotal.compareTo(ZERO) > 0) {
                    Map<String, Object> orderPayPrefDetails = new HashMap<>();
                    orderPayPrefDetails.put("orderPaymentPreference", orderPayPref);
                    orderPayPrefDetails.put("availableTotal", orderPayPrefAvailableTotal);
                    if (prefSplitMap.containsKey(paymentMethodTypeId)) {
                        (prefSplitMap.get(paymentMethodTypeId)).add(orderPayPrefDetails);
                    } else {
                        prefSplitMap.put(paymentMethodTypeId, UtilMisc.toList(orderPayPrefDetails));
                    }
                }
            }
            // Keep a decreasing total of the amount remaining to refund
            BigDecimal amountLeftToRefund = orderTotal.setScale(decimals, rounding);
            // This can be extended to support additional electronic types
            List<String> electronicTypes = UtilMisc.<String>toList("CREDIT_CARD", "EFT_ACCOUNT", "FIN_ACCOUNT", "GIFT_CARD");
            // Figure out if EXT_PAYPAL should be considered as an electronic type
            if (productStore != null) {
                ExpressCheckoutEvents.CheckoutType payPalType = ExpressCheckoutEvents.determineCheckoutType(delegator, productStore.getString("productStoreId"));
                if (!payPalType.equals(ExpressCheckoutEvents.CheckoutType.NONE)) {
                    electronicTypes.add("EXT_PAYPAL");
                }
            }
            // This defines the ordered part of the sequence of refund processing
            List<String> orderedRefundPaymentMethodTypes = new LinkedList<>();
            orderedRefundPaymentMethodTypes.add("EXT_BILLACT");
            orderedRefundPaymentMethodTypes.add("FIN_ACCOUNT");
            orderedRefundPaymentMethodTypes.add("GIFT_CARD");
            orderedRefundPaymentMethodTypes.add("CREDIT_CARD");
            orderedRefundPaymentMethodTypes.add("EFT_ACCOUNT");
            // Add all the other paymentMethodTypes, in no particular order
            List<GenericValue> otherPaymentMethodTypes;
            try {
                otherPaymentMethodTypes = EntityQuery.use(delegator).from("PaymentMethodType").where(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.NOT_IN, orderedRefundPaymentMethodTypes)).cache(true).queryList();
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot get PaymentMethodTypes", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderOrderPaymentPreferencesCannotGetPaymentMethodTypes", UtilMisc.toMap("errorString", e.toString()), locale));
            }
            List<String> fieldList = EntityUtil.getFieldListFromEntityList(otherPaymentMethodTypes, "paymentMethodTypeId", true);
            orderedRefundPaymentMethodTypes.addAll(fieldList);
            // Iterate through the specified sequence of paymentMethodTypes, refunding to the correct OrderPaymentPreferences
            // as long as there's a positive amount remaining to refund
            Iterator<String> orpmtit = orderedRefundPaymentMethodTypes.iterator();
            while (orpmtit.hasNext() && amountLeftToRefund.compareTo(ZERO) == 1) {
                String paymentMethodTypeId = orpmtit.next();
                if (prefSplitMap.containsKey(paymentMethodTypeId)) {
                    List<Map<String, Object>> paymentMethodDetails = prefSplitMap.get(paymentMethodTypeId);
                    // Iterate through the OrderPaymentPreferences of this type
                    Iterator<Map<String, Object>> pmtppit = paymentMethodDetails.iterator();
                    while (pmtppit.hasNext() && amountLeftToRefund.compareTo(ZERO) == 1) {
                        Map<String, Object> orderPaymentPrefDetails = pmtppit.next();
                        GenericValue orderPaymentPreference = (GenericValue) orderPaymentPrefDetails.get("orderPaymentPreference");
                        BigDecimal orderPaymentPreferenceAvailable = (BigDecimal) orderPaymentPrefDetails.get("availableTotal");
                        GenericValue refundOrderPaymentPreference = null;
                        // Refund up to the maxAmount for the paymentPref, or whatever is left to refund if that's less than the maxAmount
                        BigDecimal amountToRefund = orderPaymentPreferenceAvailable.min(amountLeftToRefund);
                        // The amount actually refunded for the paymentPref, default to requested amount
                        BigDecimal amountRefunded = amountToRefund;
                        String paymentId = null;
                        // generally, the return item will be considered complete after this
                        String returnItemStatusId = "RETURN_COMPLETED";
                        // Call the refund service to refund the payment
                        if (electronicTypes.contains(paymentMethodTypeId)) {
                            try {
                                Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "userLogin", context.get("userLogin"));
                                serviceContext.put("paymentMethodId", orderPaymentPreference.getString("paymentMethodId"));
                                serviceContext.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId"));
                                serviceContext.put("statusId", orderPaymentPreference.getString("statusId"));
                                serviceContext.put("maxAmount", amountToRefund.setScale(decimals, rounding));
                                String orderPaymentPreferenceNewId = null;
                                Map<String, Object> result = dispatcher.runSync("createOrderPaymentPreference", serviceContext);
                                if (ServiceUtil.isError(result)) {
                                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                                }
                                orderPaymentPreferenceNewId = (String) result.get("orderPaymentPreferenceId");
                                try {
                                    refundOrderPaymentPreference = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceNewId).queryOne();
                                } catch (GenericEntityException e) {
                                    return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsWithTheRefundSeeLogs", locale));
                                }
                                serviceResult = dispatcher.runSync("refundPayment", UtilMisc.<String, Object>toMap("orderPaymentPreference", refundOrderPaymentPreference, "refundAmount", amountToRefund.setScale(decimals, rounding), "userLogin", userLogin));
                                if (ServiceUtil.isError(serviceResult) || ServiceUtil.isFailure(serviceResult)) {
                                    Debug.logError("Error in refund payment: " + ServiceUtil.getErrorMessage(serviceResult), module);
                                    continue;
                                }
                                // for electronic types such as CREDIT_CARD and EFT_ACCOUNT, use refundPayment service
                                paymentId = (String) serviceResult.get("paymentId");
                                amountRefunded = (BigDecimal) serviceResult.get("refundAmount");
                            } catch (GenericServiceException e) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsWithTheRefundSeeLogs", locale));
                            }
                        } else if ("EXT_BILLACT".equals(paymentMethodTypeId)) {
                            try {
                                // for Billing Account refunds
                                serviceResult = dispatcher.runSync("refundBillingAccountPayment", UtilMisc.<String, Object>toMap("orderPaymentPreference", orderPaymentPreference, "refundAmount", amountToRefund.setScale(decimals, rounding), "userLogin", userLogin));
                                if (ServiceUtil.isError(serviceResult) || ServiceUtil.isFailure(serviceResult)) {
                                    Debug.logError("Error in refund payment: " + ServiceUtil.getErrorMessage(serviceResult), module);
                                    continue;
                                }
                                paymentId = (String) serviceResult.get("paymentId");
                            } catch (GenericServiceException e) {
                                Debug.logError(e, "Problem running the refundPayment service", module);
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsWithTheRefundSeeLogs", locale));
                            }
                        } else {
                            // handle manual refunds
                            try {
                                Map<String, Object> input = UtilMisc.<String, Object>toMap("userLogin", userLogin, "amount", amountLeftToRefund, "statusId", "PMNT_NOT_PAID");
                                input.put("partyIdTo", returnHeader.get("fromPartyId"));
                                input.put("partyIdFrom", returnHeader.get("toPartyId"));
                                input.put("paymentTypeId", "CUSTOMER_REFUND");
                                input.put("paymentMethodId", orderPaymentPreference.get("paymentMethodId"));
                                input.put("paymentMethodTypeId", orderPaymentPreference.get("paymentMethodTypeId"));
                                input.put("paymentPreferenceId", orderPaymentPreference.get("orderPaymentPreferenceId"));
                                serviceResult = dispatcher.runSync("createPayment", input);
                                if (ServiceUtil.isError(serviceResult) || ServiceUtil.isFailure(serviceResult)) {
                                    Debug.logError("Error in refund payment: " + ServiceUtil.getErrorMessage(serviceResult), module);
                                    continue;
                                }
                                paymentId = (String) serviceResult.get("paymentId");
                                // however, in this case we should flag it as a manual refund
                                returnItemStatusId = "RETURN_MAN_REFUND";
                            } catch (GenericServiceException e) {
                                return ServiceUtil.returnError(e.getMessage());
                            }
                        }
                        // Fill out the data for the new ReturnItemResponse
                        Map<String, Object> response = new HashMap<>();
                        if (refundOrderPaymentPreference != null) {
                            response.put("orderPaymentPreferenceId", refundOrderPaymentPreference.getString("orderPaymentPreferenceId"));
                        } else {
                            response.put("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"));
                        }
                        response.put("responseAmount", amountRefunded.setScale(decimals, rounding));
                        response.put("responseDate", now);
                        response.put("userLogin", userLogin);
                        response.put("paymentId", paymentId);
                        if ("EXT_BILLACT".equals(paymentMethodTypeId)) {
                            response.put("billingAccountId", orderReadHelper.getBillingAccount().getString("billingAccountId"));
                        }
                        Map<String, Object> serviceResults = null;
                        try {
                            serviceResults = dispatcher.runSync("createReturnItemResponse", response);
                            if (ServiceUtil.isError(serviceResults)) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsCreatingReturnItemResponseEntity", locale), null, null, serviceResults);
                            }
                        } catch (GenericServiceException e) {
                            Debug.logError(e, "Problems creating new ReturnItemResponse entity", module);
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemsCreatingReturnItemResponseEntity", locale));
                        }
                        String responseId = (String) serviceResults.get("returnItemResponseId");
                        // Set the response on each item
                        for (GenericValue item : items) {
                            Map<String, Object> returnItemMap = UtilMisc.<String, Object>toMap("returnItemResponseId", responseId, "returnId", item.get("returnId"), "returnItemSeqId", item.get("returnItemSeqId"), "statusId", returnItemStatusId, "userLogin", userLogin);
                            try {
                                serviceResults = dispatcher.runSync("updateReturnItem", returnItemMap);
                                if (ServiceUtil.isError(serviceResults)) {
                                    return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemUpdatingReturnItemReturnItemResponseId", locale), null, null, serviceResults);
                                }
                            } catch (GenericServiceException e) {
                                Debug.logError("Problem updating the ReturnItem entity", module);
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemUpdatingReturnItemReturnItemResponseId", locale));
                            }
                        }
                        // Create the payment applications for the return invoice
                        try {
                            serviceResults = dispatcher.runSync("createPaymentApplicationsFromReturnItemResponse", UtilMisc.<String, Object>toMap("returnItemResponseId", responseId, "userLogin", userLogin));
                            if (ServiceUtil.isError(serviceResults)) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemUpdatingReturnItemReturnItemResponseId", locale), null, null, serviceResults);
                            }
                        } catch (GenericServiceException e) {
                            Debug.logError(e, "Problem creating PaymentApplication records for return invoice", module);
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemUpdatingReturnItemReturnItemResponseId", locale));
                        }
                        // Update the amount necessary to refund
                        amountLeftToRefund = amountLeftToRefund.subtract(amountRefunded);
                    }
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Timestamp(java.sql.Timestamp) EntityConditionList(org.apache.ofbiz.entity.condition.EntityConditionList) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) ExpressCheckoutEvents(org.apache.ofbiz.order.thirdparty.paypal.ExpressCheckoutEvents) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 52 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class ShoppingCartItem method getFeatureSet.

/**
 * Returns a Set of the item's features
 */
public Set<String> getFeatureSet() {
    Set<String> featureSet = new LinkedHashSet<>();
    GenericValue product = this.getProduct();
    if (product != null) {
        List<GenericValue> featureAppls = null;
        try {
            featureAppls = product.getRelated("ProductFeatureAppl", null, null, false);
            List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
            filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
            featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Unable to get features from product : " + product.get("productId"), module);
        }
        if (featureAppls != null) {
            for (GenericValue appl : featureAppls) {
                featureSet.add(appl.getString("productFeatureId"));
            }
        }
    }
    if (this.additionalProductFeatureAndAppls != null) {
        for (GenericValue appl : this.additionalProductFeatureAndAppls.values()) {
            featureSet.add(appl.getString("productFeatureId"));
        }
    }
    return featureSet;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 53 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class OrderManagerEvents method receiveOfflinePayment.

public static String receiveOfflinePayment(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    Locale locale = UtilHttp.getLocale(request);
    String orderId = request.getParameter("orderId");
    String partyId = request.getParameter("partyId");
    // get the order header & payment preferences
    GenericValue orderHeader = null;
    try {
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems reading order header from datasource.", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsReadingOrderHeaderInformation", locale));
        return "error";
    }
    BigDecimal grandTotal = BigDecimal.ZERO;
    if (orderHeader != null) {
        grandTotal = orderHeader.getBigDecimal("grandTotal");
    }
    // get the payment types to receive
    List<GenericValue> paymentMethodTypes = null;
    try {
        paymentMethodTypes = EntityQuery.use(delegator).from("PaymentMethodType").where(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.NOT_EQUAL, "EXT_OFFLINE")).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems getting payment types", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsWithPaymentTypeLookup", locale));
        return "error";
    }
    if (paymentMethodTypes == null) {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsWithPaymentTypeLookup", locale));
        return "error";
    }
    // get the payment methods to receive
    List<GenericValue> paymentMethods = null;
    try {
        paymentMethods = EntityQuery.use(delegator).from("PaymentMethod").where("partyId", partyId).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems getting payment methods", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsWithPaymentMethodLookup", locale));
        return "error";
    }
    GenericValue placingCustomer = null;
    try {
        placingCustomer = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", "PLACING_CUSTOMER").queryFirst();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems looking up order payment preferences", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderErrorProcessingOfflinePayments", locale));
        return "error";
    }
    for (GenericValue paymentMethod : paymentMethods) {
        String paymentMethodId = paymentMethod.getString("paymentMethodId");
        String paymentMethodAmountStr = request.getParameter(paymentMethodId + "_amount");
        String paymentMethodReference = request.getParameter(paymentMethodId + "_reference");
        if (UtilValidate.isNotEmpty(paymentMethodAmountStr)) {
            BigDecimal paymentMethodAmount = BigDecimal.ZERO;
            try {
                paymentMethodAmount = (BigDecimal) ObjectType.simpleTypeConvert(paymentMethodAmountStr, "BigDecimal", null, locale);
            } catch (GeneralException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsPaymentParsingAmount", locale));
                return "error";
            }
            if (paymentMethodAmount.compareTo(BigDecimal.ZERO) > 0) {
                // create a payment, payment reference and payment appl record, when not exist yet.
                Map<String, Object> results = null;
                try {
                    results = dispatcher.runSync("createPaymentFromOrder", UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId, "paymentRefNum", paymentMethodReference, "comments", "Payment received offline and manually entered.", "userLogin", userLogin));
                    if (ServiceUtil.isError(results)) {
                        String errorMessage = ServiceUtil.getErrorMessage(results);
                        request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                        Debug.logError(errorMessage, module);
                        return "error";
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, "Failed to execute service createPaymentFromOrder", module);
                    request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
                    return "error";
                }
            }
            OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
            return "success";
        }
    }
    List<GenericValue> toBeStored = new LinkedList<GenericValue>();
    for (GenericValue paymentMethodType : paymentMethodTypes) {
        String paymentMethodTypeId = paymentMethodType.getString("paymentMethodTypeId");
        String amountStr = request.getParameter(paymentMethodTypeId + "_amount");
        String paymentReference = request.getParameter(paymentMethodTypeId + "_reference");
        if (UtilValidate.isNotEmpty(amountStr)) {
            BigDecimal paymentTypeAmount = BigDecimal.ZERO;
            try {
                paymentTypeAmount = (BigDecimal) ObjectType.simpleTypeConvert(amountStr, "BigDecimal", null, locale);
            } catch (GeneralException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemsPaymentParsingAmount", locale));
                return "error";
            }
            if (paymentTypeAmount.compareTo(BigDecimal.ZERO) > 0) {
                // create the OrderPaymentPreference
                // TODO: this should be done with a service
                Map<String, String> prefFields = UtilMisc.<String, String>toMap("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference"));
                GenericValue paymentPreference = delegator.makeValue("OrderPaymentPreference", prefFields);
                paymentPreference.set("paymentMethodTypeId", paymentMethodType.getString("paymentMethodTypeId"));
                paymentPreference.set("maxAmount", paymentTypeAmount);
                paymentPreference.set("statusId", "PAYMENT_RECEIVED");
                paymentPreference.set("orderId", orderId);
                paymentPreference.set("createdDate", UtilDateTime.nowTimestamp());
                if (userLogin != null) {
                    paymentPreference.set("createdByUserLogin", userLogin.getString("userLoginId"));
                }
                try {
                    delegator.create(paymentPreference);
                } catch (GenericEntityException ex) {
                    Debug.logError(ex, "Cannot create a new OrderPaymentPreference", module);
                    request.setAttribute("_ERROR_MESSAGE_", ex.getMessage());
                    return "error";
                }
                // create a payment record
                Map<String, Object> results = null;
                try {
                    results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "paymentRefNum", paymentReference, "paymentFromId", placingCustomer.getString("partyId"), "comments", "Payment received offline and manually entered."));
                    if (ServiceUtil.isError(results)) {
                        String errorMessage = ServiceUtil.getErrorMessage(results);
                        request.setAttribute("_ERROR_MESSAGE_", errorMessage);
                        Debug.logError(errorMessage, module);
                        return "error";
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, "Failed to execute service createPaymentFromPreference", module);
                    request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
                    return "error";
                }
            }
        }
    }
    // get the current payment prefs
    GenericValue offlineValue = null;
    List<GenericValue> currentPrefs = null;
    BigDecimal paymentTally = BigDecimal.ZERO;
    try {
        EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED")), EntityOperator.AND);
        currentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(ecl).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "ERROR: Unable to get existing payment preferences from order", module);
    }
    if (UtilValidate.isNotEmpty(currentPrefs)) {
        for (GenericValue cp : currentPrefs) {
            String paymentMethodType = cp.getString("paymentMethodTypeId");
            if ("EXT_OFFLINE".equals(paymentMethodType)) {
                offlineValue = cp;
            } else {
                BigDecimal cpAmt = cp.getBigDecimal("maxAmount");
                if (cpAmt != null) {
                    paymentTally = paymentTally.add(cpAmt);
                }
            }
        }
    }
    // now finish up
    boolean okayToApprove = false;
    if (paymentTally.compareTo(grandTotal) >= 0) {
        // cancel the offline preference
        okayToApprove = true;
        if (offlineValue != null) {
            offlineValue.set("statusId", "PAYMENT_CANCELLED");
            toBeStored.add(offlineValue);
        }
    }
    // TODO: updating order payment preference should be done with a service
    try {
        delegator.storeAll(toBeStored);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems storing payment information", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderProblemStoringReceivedPaymentInformation", locale));
        return "error";
    }
    if (okayToApprove) {
        // update the status of the order and items
        OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpSession(javax.servlet.http.HttpSession) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) 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 54 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class WorkEffortServices method getWorkEffortAssignedActivities.

public static Map<String, Object> getWorkEffortAssignedActivities(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<GenericValue> validWorkEfforts = null;
    if (userLogin != null && userLogin.get("partyId") != null) {
        try {
            List<EntityExpr> constraints = new LinkedList<>();
            constraints.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, userLogin.get("partyId")));
            constraints.add(EntityCondition.makeCondition("workEffortTypeId", EntityOperator.EQUALS, "ACTIVITY"));
            constraints.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "CAL_DECLINED"));
            constraints.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "CAL_DELEGATED"));
            constraints.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "CAL_COMPLETED"));
            constraints.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "CAL_CANCELLED"));
            constraints.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PRTYASGN_UNASSIGNED"));
            constraints.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "WF_COMPLETED"));
            constraints.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "WF_TERMINATED"));
            constraints.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "WF_ABORTED"));
            validWorkEfforts = EntityQuery.use(delegator).from("WorkEffortAndPartyAssign").where(constraints).orderBy("priority").filterByDate().queryList();
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortNotFound", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    Map<String, Object> result = new HashMap<>();
    if (validWorkEfforts == null) {
        validWorkEfforts = new LinkedList<>();
    }
    result.put("activities", validWorkEfforts);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 55 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class WorkEffortServices method getWorkEffortAssignedTasks.

public static Map<String, Object> getWorkEffortAssignedTasks(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<GenericValue> validWorkEfforts = null;
    if (userLogin != null && userLogin.get("partyId") != null) {
        try {
            EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, userLogin.get("partyId")), EntityCondition.makeCondition("workEffortTypeId", EntityOperator.EQUALS, "TASK"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_DECLINED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_DELEGATED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_COMPLETED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_CANCELLED"), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PRTYASGN_UNASSIGNED"));
            validWorkEfforts = EntityQuery.use(delegator).from("WorkEffortAndPartyAssign").where(ecl).orderBy("priority").filterByDate().queryList();
            ecl = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, userLogin.get("partyId")), EntityCondition.makeCondition("workEffortTypeId", EntityOperator.EQUALS, "PROD_ORDER_TASK"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED "), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_COMPLETED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CLOSED"));
            validWorkEfforts.addAll(EntityQuery.use(delegator).from("WorkEffortAndPartyAssign").where(ecl).orderBy("createdDate DESC").filterByDate().queryList());
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortNotFound", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    Map<String, Object> result = new HashMap<>();
    if (validWorkEfforts == null) {
        validWorkEfforts = new LinkedList<>();
    }
    validWorkEfforts = WorkEffortWorker.removeDuplicateWorkEfforts(validWorkEfforts);
    result.put("tasks", validWorkEfforts);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Aggregations

EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)57 GenericValue (org.apache.ofbiz.entity.GenericValue)51 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)47 Delegator (org.apache.ofbiz.entity.Delegator)29 LinkedList (java.util.LinkedList)27 HashMap (java.util.HashMap)24 Locale (java.util.Locale)23 BigDecimal (java.math.BigDecimal)19 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)18 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)16 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)15 Timestamp (java.sql.Timestamp)13 ArrayList (java.util.ArrayList)11 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 List (java.util.List)6 Map (java.util.Map)6 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)6 Calendar (com.ibm.icu.util.Calendar)4 LinkedHashSet (java.util.LinkedHashSet)4 EntityConditionList (org.apache.ofbiz.entity.condition.EntityConditionList)4