Search in sources :

Example 91 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.

the class IdealEvents method idealNotify.

/**
 * iDEAL notification
 */
public static String idealNotify(HttpServletRequest request, HttpServletResponse response) {
    Locale locale = UtilHttp.getLocale(request);
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Map<String, Object> parametersMap = UtilHttp.getParameterMap(request);
    String transactionId = request.getParameter("trxid");
    for (String name : parametersMap.keySet()) {
        String value = request.getParameter(name);
        Debug.logError("### Param: " + name + " => " + value, module);
    }
    String orderId = null;
    String paymentStatus = null;
    try {
        IdealConnector connector = new IdealConnector("payment");
        Transaction transaction = connector.requestTransactionStatus(transactionId);
        orderId = transaction.getPurchaseID();
        if (orderId == null) {
            orderId = (String) request.getSession().getAttribute("purchaseID");
        }
        String payAmount = transaction.getAmount();
        if (payAmount == null) {
            payAmount = (String) request.getSession().getAttribute("payAmount");
        }
        paymentStatus = transaction.getStatus();
        request.setAttribute("transactionId", transactionId);
        request.setAttribute("paymentStatus", paymentStatus);
        request.setAttribute("paymentAmount", payAmount);
    } catch (IdealException ex) {
        Debug.logError(ex.getMessage(), module);
        request.setAttribute("_ERROR_MESSAGE_", ex.getConsumerMessage());
        return "error";
    }
    // get the user
    if (userLogin == null) {
        String userLoginId = "system";
        try {
            userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get UserLogin for: " + userLoginId + "; cannot continue", module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "idealEvents.problemsGettingAuthenticationUser", locale));
            return "error";
        }
    }
    // get the order header
    GenericValue orderHeader = null;
    if (UtilValidate.isNotEmpty(orderId)) {
        try {
            orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get the order header for order: " + orderId, module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "idealEvents.problemsGettingOrderHeader", locale));
            return "error";
        }
    } else {
        Debug.logError("iDEAL did not callback with a valid orderId!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "idealEvents.noValidOrderIdReturned", locale));
        return "error";
    }
    if (orderHeader == null) {
        Debug.logError("Cannot get the order header for order: " + orderId, module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "idealEvents.problemsGettingOrderHeader", locale));
        return "error";
    }
    // attempt to start a transaction
    boolean okay = true;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        // authorized
        if ("Success".equals(paymentStatus)) {
            okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        // cancelled
        } else if ("Cancelled".equals(paymentStatus)) {
            okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
        }
        if (okay) {
            // set the payment preference
            okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request);
        }
    } catch (Exception e) {
        String errMsg = "Error handling iDEAL notification";
        Debug.logError(e, errMsg, module);
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, e);
        } catch (GenericTransactionException gte2) {
            Debug.logError(gte2, "Unable to rollback transaction", module);
        }
    } finally {
        if (!okay) {
            try {
                TransactionUtil.rollback(beganTransaction, "Failure in processing iDEAL callback", null);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to rollback transaction", module);
            }
        } else {
            try {
                TransactionUtil.commit(beganTransaction);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to commit transaction", module);
            }
        }
    }
    if (okay) {
        request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource, "IdealSuccessful", locale));
        // call the email confirm service
        Map<String, String> emailContext = UtilMisc.toMap("orderId", orderId, "userLogin", userLogin);
        try {
            dispatcher.runSync("sendOrderConfirmation", emailContext);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problems sending email confirmation", module);
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) IdealConnector(com.ing.ideal.connector.IdealConnector) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IdealException(com.ing.ideal.connector.IdealException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) IdealException(com.ing.ideal.connector.IdealException) Delegator(org.apache.ofbiz.entity.Delegator) Transaction(com.ing.ideal.connector.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 92 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.

the class GlEvents method createReconcileAccount.

public static String createReconcileAccount(HttpServletRequest request, HttpServletResponse response) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    final Delegator delegator = (Delegator) request.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Map<String, Object> ctx = UtilHttp.getParameterMap(request);
    String acctgTransId;
    String acctgTransEntrySeqId;
    String glAccountId = null;
    String organizationPartyId = null;
    BigDecimal reconciledBalance = BigDecimal.ZERO;
    boolean isSelected;
    String debitCreditFlag;
    // The number of multi form rows is retrieved
    int rowCount = UtilHttp.getMultiFormRowCount(ctx);
    for (int i = 0; i < rowCount; i++) {
        // for calculating amount per glAccountId
        String suffix = UtilHttp.getMultiRowDelimiter() + i;
        isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
        if (!isSelected) {
            continue;
        }
        acctgTransId = (String) ctx.get("acctgTransId" + suffix);
        acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
        organizationPartyId = (String) ctx.get("organizationPartyId" + suffix);
        glAccountId = (String) ctx.get("glAccountId" + suffix);
        try {
            GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
            if (acctgTransEntry != null) {
                // calculate amount for each AcctgTransEntry according to glAccountId based on debit and credit
                debitCreditFlag = acctgTransEntry.getString("debitCreditFlag");
                if ("D".equalsIgnoreCase(debitCreditFlag)) {
                    // total balance per glAccountId
                    reconciledBalance = reconciledBalance.add(acctgTransEntry.getBigDecimal("amount"));
                } else {
                    // total balance per glAccountId
                    reconciledBalance = reconciledBalance.subtract(acctgTransEntry.getBigDecimal("amount"));
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return "error";
        }
    }
    Map<String, Object> fieldMap = UtilMisc.toMap("glReconciliationName", "Reconciliation at date " + UtilDateTime.nowTimestamp(), "glAccountId", glAccountId, "organizationPartyId", organizationPartyId, "reconciledDate", UtilDateTime.nowTimestamp(), "reconciledBalance", reconciledBalance, "userLogin", userLogin);
    Map<String, Object> glReconResult = null;
    try {
        // create GlReconciliation for the glAccountId
        glReconResult = dispatcher.runSync("createGlReconciliation", fieldMap);
        if (ServiceUtil.isError(glReconResult)) {
            return "error";
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return "error";
    }
    String glReconciliationId = (String) glReconResult.get("glReconciliationId");
    String reconciledAmount;
    for (int i = 0; i < rowCount; i++) {
        String suffix = UtilHttp.getMultiRowDelimiter() + i;
        isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
        if (!isSelected) {
            continue;
        }
        acctgTransId = (String) ctx.get("acctgTransId" + suffix);
        acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
        try {
            GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
            if (acctgTransEntry != null) {
                reconciledAmount = acctgTransEntry.getString("amount");
                acctgTransId = acctgTransEntry.getString("acctgTransId");
                acctgTransEntrySeqId = acctgTransEntry.getString("acctgTransEntrySeqId");
                Map<String, Object> glReconEntryMap = UtilMisc.toMap("glReconciliationId", glReconciliationId, "acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId, "reconciledAmount", reconciledAmount, "userLogin", userLogin);
                Map<String, Object> glReconEntryResult = null;
                try {
                    glReconEntryResult = dispatcher.runSync("createGlReconciliationEntry", glReconEntryMap);
                    if (ServiceUtil.isError(glReconEntryResult)) {
                        return "error";
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, module);
                    return "error";
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return "error";
        }
    }
    ctx.put("glReconciliationId", glReconciliationId);
    request.setAttribute("glReconciliationId", glReconciliationId);
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

Example 93 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.

the class FinAccountPaymentServices method finAccountPreAuth.

// base payment integration services
public static Map<String, Object> finAccountPreAuth(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    String finAccountCode = (String) context.get("finAccountCode");
    String finAccountPin = (String) context.get("finAccountPin");
    String finAccountId = (String) context.get("finAccountId");
    String orderId = (String) context.get("orderId");
    BigDecimal amount = (BigDecimal) context.get("processAmount");
    if (paymentPref != null) {
        // check for an existing auth trans and cancel it
        GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
        if (authTrans != null) {
            Map<String, Object> input = UtilMisc.toMap("userLogin", userLogin, "finAccountAuthId", authTrans.get("referenceNum"));
            try {
                Map<String, Object> result = dispatcher.runSync("expireFinAccountAuth", input);
                if (ServiceUtil.isError(result)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        }
        if (finAccountId == null) {
            finAccountId = paymentPref.getString("finAccountId");
        }
    }
    // obtain the order information
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    // NOTE DEJ20070808: this means that we want store related settings for where
    // the item is being purchased,
    // NOT where the account was setup; should this be changed to use settings from
    // the store where the account was setup?
    String productStoreId = orh.getProductStoreId();
    // TODO, NOTE DEJ20070808: why is this setup this way anyway? for the
    // allowAuthToNegative wouldn't that be better setup
    // on the FinAccount and not on the ProductStoreFinActSetting? maybe an override
    // on the FinAccount would be good...
    // get the financial account
    GenericValue finAccount;
    if (finAccountId != null) {
        try {
            finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    } else {
        if (finAccountCode != null) {
            try {
                finAccount = FinAccountHelper.getFinAccountFromCode(finAccountCode, delegator);
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotLocateItFromAccountCode", locale));
            }
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountIdAndFinAccountCodeAreNull", locale));
        }
    }
    if (finAccount == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountIdInvalid", locale));
    }
    String finAccountTypeId = finAccount.getString("finAccountTypeId");
    finAccountId = finAccount.getString("finAccountId");
    String statusId = finAccount.getString("statusId");
    try {
        // fin the store requires a pin number; validate the PIN with the code
        Map<String, Object> findProductStoreFinActSettingMap = UtilMisc.<String, Object>toMap("productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId);
        GenericValue finAccountSettings = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where(findProductStoreFinActSettingMap).cache().queryOne();
        if (finAccountSettings == null) {
            Debug.logWarning("In finAccountPreAuth could not find ProductStoreFinActSetting record, values searched by: " + findProductStoreFinActSettingMap, module);
        }
        if (Debug.verboseOn()) {
            Debug.logVerbose("In finAccountPreAuth finAccountSettings=" + finAccountSettings, module);
        }
        BigDecimal minBalance = FinAccountHelper.ZERO;
        String allowAuthToNegative = "N";
        if (finAccountSettings != null) {
            allowAuthToNegative = finAccountSettings.getString("allowAuthToNegative");
            minBalance = finAccountSettings.getBigDecimal("minBalance");
            if (minBalance == null) {
                minBalance = FinAccountHelper.ZERO;
            }
            // validate the PIN if the store requires it
            if ("Y".equals(finAccountSettings.getString("requirePinCode"))) {
                if (!FinAccountHelper.validatePin(delegator, finAccountCode, finAccountPin)) {
                    Map<String, Object> result = ServiceUtil.returnSuccess();
                    result.put("authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountPinCodeCombinatorNotFound", locale));
                    result.put("authResult", Boolean.FALSE);
                    result.put("processAmount", amount);
                    result.put("authFlag", "0");
                    result.put("authCode", "A");
                    result.put("authRefNum", "0");
                    Debug.logWarning("Unable to auth FinAccount: " + result, module);
                    return result;
                }
            }
        }
        // check for expiration date
        if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
            Map<String, Object> result = ServiceUtil.returnSuccess();
            result.put("authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale));
            result.put("authResult", Boolean.FALSE);
            result.put("processAmount", amount);
            result.put("authFlag", "0");
            result.put("authCode", "A");
            result.put("authRefNum", "0");
            Debug.logWarning("Unable to auth FinAccount: " + result, module);
            return result;
        }
        // check for account being in bad standing somehow
        if ("FNACT_NEGPENDREPL".equals(statusId) || "FNACT_MANFROZEN".equals(statusId) || "FNACT_CANCELLED".equals(statusId)) {
            // refresh the finaccount
            finAccount.refresh();
            statusId = finAccount.getString("statusId");
            if ("FNACT_NEGPENDREPL".equals(statusId) || "FNACT_MANFROZEN".equals(statusId) || "FNACT_CANCELLED".equals(statusId)) {
                Map<String, Object> result = ServiceUtil.returnSuccess();
                if ("FNACT_NEGPENDREPL".equals(statusId)) {
                    result.put("authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountNegative", locale));
                } else if ("FNACT_MANFROZEN".equals(statusId)) {
                    result.put("authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountFrozen", locale));
                } else if ("FNACT_CANCELLED".equals(statusId)) {
                    result.put("authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountCancelled", locale));
                }
                result.put("authResult", Boolean.FALSE);
                result.put("processAmount", amount);
                result.put("authFlag", "0");
                result.put("authCode", "A");
                result.put("authRefNum", "0");
                Debug.logWarning("Unable to auth FinAccount: " + result, module);
                return result;
            }
        }
        // check the amount to authorize against the available balance of fin account,
        // which includes active authorizations as well as transactions
        BigDecimal availableBalance = finAccount.getBigDecimal("availableBalance");
        if (availableBalance == null) {
            availableBalance = FinAccountHelper.ZERO;
        } else {
            BigDecimal availableBalanceOriginal = availableBalance;
            availableBalance = availableBalance.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);
            if (availableBalance.compareTo(availableBalanceOriginal) != 0) {
                Debug.logWarning("In finAccountPreAuth for finAccountId [" + finAccountId + "] availableBalance [" + availableBalanceOriginal + "] was different after rounding [" + availableBalance + "]; it should never have made it into the database this way, so check whatever put it there.", module);
            }
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        String authMessage = null;
        Boolean processResult;
        String refNum;
        // make sure to round and scale it to the same as availableBalance
        amount = amount.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);
        Debug.logInfo("Allow auth to negative: " + allowAuthToNegative + " :: available: " + availableBalance + " comp: " + minBalance + " = " + availableBalance.compareTo(minBalance) + " :: req: " + amount, module);
        // check the available balance to see if we can auth this tx
        if (("Y".equals(allowAuthToNegative) && availableBalance.compareTo(minBalance) > -1) || (availableBalance.compareTo(amount) > -1)) {
            Timestamp thruDate;
            if (finAccountSettings != null && finAccountSettings.getLong("authValidDays") != null) {
                thruDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), finAccountSettings.getLong("authValidDays"));
            } else {
                // default 30 days for an auth
                thruDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), Long.valueOf(30));
            }
            Map<String, Object> tmpResult = dispatcher.runSync("createFinAccountAuth", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "amount", amount, "thruDate", thruDate, "userLogin", userLogin));
            if (ServiceUtil.isError(tmpResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
            }
            refNum = (String) tmpResult.get("finAccountAuthId");
            processResult = Boolean.TRUE;
            // refresh the account
            finAccount.refresh();
        } else {
            Debug.logWarning("Attempted to authorize [" + amount + "] against a balance of only [" + availableBalance + "] for finAccountId [" + finAccountId + "]", module);
            // a refNum is always required from authorization
            refNum = "0";
            authMessage = "Insufficient funds";
            processResult = Boolean.FALSE;
        }
        result.put("processAmount", amount);
        result.put("authMessage", authMessage);
        result.put("authResult", processResult);
        result.put("processAmount", amount);
        result.put("authFlag", "1");
        result.put("authCode", "A");
        result.put("authRefNum", refNum);
        Debug.logInfo("FinAccont Auth: " + result, module);
        return result;
    } catch (GenericEntityException | GenericServiceException ex) {
        Debug.logError(ex, "Cannot authorize financial account", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeAuthorized", UtilMisc.toMap("errorString", ex.getMessage()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 94 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.

the class FinAccountPaymentServices method finAccountReplenish.

// auto-replenish service (deposit)
public static Map<String, Object> finAccountReplenish(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productStoreId = (String) context.get("productStoreId");
    String finAccountId = (String) context.get("finAccountId");
    // lookup the FinAccount
    GenericValue finAccount;
    try {
        finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (finAccount == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", finAccountId), locale));
    }
    String currency = finAccount.getString("currencyUomId");
    String statusId = finAccount.getString("statusId");
    // look up the type -- determine auto-replenish is active
    GenericValue finAccountType;
    try {
        finAccountType = finAccount.getRelatedOne("FinAccountType", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String replenishEnumId = finAccountType.getString("replenishEnumId");
    if (!"FARP_AUTOMATIC".equals(replenishEnumId)) {
        // type does not support auto-replenish
        return ServiceUtil.returnSuccess();
    }
    // attempt to lookup the product store from a previous deposit
    if (productStoreId == null) {
        productStoreId = getLastProductStoreId(delegator, finAccountId);
        if (productStoreId == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeReplenish", locale));
        }
    }
    // get the product store settings
    GenericValue finAccountSettings;
    Map<String, Object> psfasFindMap = UtilMisc.<String, Object>toMap("productStoreId", productStoreId, "finAccountTypeId", finAccount.getString("finAccountTypeId"));
    try {
        finAccountSettings = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where(psfasFindMap).cache().queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (finAccountSettings == null) {
        Debug.logWarning("finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because no ProductStoreFinActSetting record found for: " + psfasFindMap, module);
        // no settings; don't replenish
        return ServiceUtil.returnSuccess();
    }
    BigDecimal replenishThreshold = finAccountSettings.getBigDecimal("replenishThreshold");
    if (replenishThreshold == null) {
        Debug.logWarning("finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because ProductStoreFinActSetting.replenishThreshold field was null for: " + psfasFindMap, module);
        return ServiceUtil.returnSuccess();
    }
    BigDecimal replenishLevel = finAccount.getBigDecimal("replenishLevel");
    if (replenishLevel == null || replenishLevel.compareTo(BigDecimal.ZERO) == 0) {
        Debug.logWarning("finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because FinAccount.replenishLevel field was null or 0", module);
        // no replenish level set; this account goes not support auto-replenish
        return ServiceUtil.returnSuccess();
    }
    // get the current balance
    BigDecimal balance = finAccount.getBigDecimal("actualBalance");
    // see if we are within the threshold for replenishment
    if (balance.compareTo(replenishThreshold) > -1) {
        Debug.logInfo("finAccountReplenish Info: Not replenishing FinAccount [" + finAccountId + "] because balance [" + balance + "] is greater than the replenishThreshold [" + replenishThreshold + "]", module);
        // not ready
        return ServiceUtil.returnSuccess();
    }
    // configure rollback service to set status to Negative Pending Replenishment
    if ("FNACT_NEGPENDREPL".equals(statusId)) {
        try {
            Map<String, Object> rollbackCtx = UtilMisc.toMap("userLogin", userLogin, "finAccountId", finAccountId, "statusId", "FNACT_NEGPENDREPL");
            dispatcher.addRollbackService("updateFinAccount", rollbackCtx, true);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    String replenishMethod = finAccountSettings.getString("replenishMethodEnumId");
    BigDecimal depositAmount;
    if (replenishMethod == null || "FARP_TOP_OFF".equals(replenishMethod)) {
        // the deposit is level - balance (500 - (-10) = 510 || 500 - (10) = 490)
        depositAmount = replenishLevel.subtract(balance);
    } else if ("FARP_REPLENISH_LEVEL".equals(replenishMethod)) {
        // the deposit is replenish-level itself
        depositAmount = replenishLevel;
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountUnknownReplenishMethod", locale));
    }
    // get the owner party
    String ownerPartyId = finAccount.getString("ownerPartyId");
    if (ownerPartyId == null) {
        // no owner cannot replenish; (not fatal, just not supported by this account)
        Debug.logWarning("finAccountReplenish Warning: No owner attached to financial account [" + finAccountId + "] cannot auto-replenish", module);
        return ServiceUtil.returnSuccess();
    }
    // get the payment method to use to replenish
    String paymentMethodId = finAccount.getString("replenishPaymentId");
    if (paymentMethodId == null) {
        Debug.logWarning("finAccountReplenish Warning: No payment method (replenishPaymentId) attached to financial account [" + finAccountId + "] cannot auto-replenish", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountNoPaymentMethodAssociatedWithReplenishAccount", locale));
    }
    GenericValue paymentMethod;
    try {
        paymentMethod = EntityQuery.use(delegator).from("PaymentMethod").where("paymentMethodId", paymentMethodId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (paymentMethod == null) {
        // no payment methods on file; cannot replenish
        Debug.logWarning("finAccountReplenish Warning: No payment method found for ID [" + paymentMethodId + "] for party [" + ownerPartyId + "] cannot auto-replenish", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountNoPaymentMethodAssociatedWithReplenishAccount", locale));
    }
    // hit the payment method for the amount to replenish
    Map<String, BigDecimal> orderItemMap = UtilMisc.toMap("Auto-Replenishment FA #" + finAccountId, depositAmount);
    Map<String, Object> replOrderCtx = new HashMap<>();
    replOrderCtx.put("productStoreId", productStoreId);
    replOrderCtx.put("paymentMethodId", paymentMethod.getString("paymentMethodId"));
    replOrderCtx.put("currency", currency);
    replOrderCtx.put("partyId", ownerPartyId);
    replOrderCtx.put("itemMap", orderItemMap);
    replOrderCtx.put("userLogin", userLogin);
    Map<String, Object> replResp;
    try {
        replResp = dispatcher.runSync("createSimpleNonProductSalesOrder", replOrderCtx);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(replResp)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(replResp));
    }
    String orderId = (String) replResp.get("orderId");
    // create the deposit
    Map<String, Object> depositCtx = new HashMap<>();
    depositCtx.put("productStoreId", productStoreId);
    depositCtx.put("finAccountId", finAccountId);
    depositCtx.put("currency", currency);
    depositCtx.put("partyId", ownerPartyId);
    depositCtx.put("orderId", orderId);
    // always one item on a replish order
    depositCtx.put("orderItemSeqId", "00001");
    depositCtx.put("amount", depositAmount);
    depositCtx.put("reasonEnumId", "FATR_REPLENISH");
    depositCtx.put("userLogin", userLogin);
    try {
        Map<String, Object> depositResp = dispatcher.runSync("finAccountDeposit", depositCtx);
        if (ServiceUtil.isError(depositResp)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(depositResp));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // say we are in good standing again
    if ("FNACT_NEGPENDREPL".equals(statusId)) {
        try {
            Map<String, Object> ufaResp = dispatcher.runSync("updateFinAccount", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "statusId", "FNACT_ACTIVE", "userLogin", userLogin));
            if (ServiceUtil.isError(ufaResp)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(ufaResp));
            }
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

Example 95 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.

the class FinAccountPaymentServices method finAccountReleaseAuth.

public static Map<String, Object> finAccountReleaseAuth(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    Locale locale = (Locale) context.get("locale");
    String err = UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeExpired", locale);
    try {
        // expire the related financial authorization transaction
        GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
        if (authTransaction == null) {
            return ServiceUtil.returnError(err + UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotFindAuthorization", locale));
        }
        Map<String, Object> input = UtilMisc.toMap("userLogin", userLogin, "finAccountAuthId", authTransaction.get("referenceNum"));
        Map<String, Object> serviceResults = dispatcher.runSync("expireFinAccountAuth", input);
        // if there's an error, don't release
        if (ServiceUtil.isError(serviceResults)) {
            return ServiceUtil.returnError(err + ServiceUtil.getErrorMessage(serviceResults));
        }
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("releaseRefNum", authTransaction.getString("referenceNum"));
        result.put("releaseAmount", authTransaction.getBigDecimal("amount"));
        result.put("releaseResult", Boolean.TRUE);
        return result;
    } catch (GenericServiceException e) {
        Debug.logError(e, e.getMessage(), module);
        return ServiceUtil.returnError(err + e.getMessage());
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

GenericServiceException (org.apache.ofbiz.service.GenericServiceException)417 GenericValue (org.apache.ofbiz.entity.GenericValue)339 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)303 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)251 Delegator (org.apache.ofbiz.entity.Delegator)250 Locale (java.util.Locale)246 HashMap (java.util.HashMap)221 BigDecimal (java.math.BigDecimal)139 LinkedList (java.util.LinkedList)79 GeneralException (org.apache.ofbiz.base.util.GeneralException)68 Timestamp (java.sql.Timestamp)66 Map (java.util.Map)54 IOException (java.io.IOException)43 HttpSession (javax.servlet.http.HttpSession)36 ModelService (org.apache.ofbiz.service.ModelService)33 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)24 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)22 ArrayList (java.util.ArrayList)21 LinkedHashMap (java.util.LinkedHashMap)20 List (java.util.List)20