Search in sources :

Example 56 with GenericServiceException

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

the class GiftCertificateServices method createGiftCertificate.

// Base Gift Certificate Services
public static Map<String, Object> createGiftCertificate(DispatchContext dctx, Map<String, ? extends 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");
    BigDecimal initialAmount = (BigDecimal) context.get("initialAmount");
    String currency = (String) context.get("currency");
    String partyId = (String) context.get("partyId");
    if (UtilValidate.isEmpty(partyId)) {
        partyId = "_NA_";
    }
    String currencyUom = (String) context.get("currency");
    if (UtilValidate.isEmpty(currencyUom)) {
        currencyUom = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
    }
    String cardNumber = null;
    String pinNumber = null;
    String refNum = null;
    String finAccountId = null;
    try {
        final String accountName = "Gift Certificate Account";
        final String deposit = "DEPOSIT";
        GenericValue giftCertSettings = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where("productStoreId", productStoreId, "finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId).cache().queryOne();
        Map<String, Object> acctResult = null;
        if ("Y".equals(giftCertSettings.getString("requirePinCode"))) {
            // TODO: move this code to createFinAccountForStore as well
            int cardNumberLength = CARD_NUMBER_LENGTH;
            int pinNumberLength = PIN_NUMBER_LENGTH;
            if (giftCertSettings.getLong("accountCodeLength") != null) {
                cardNumberLength = giftCertSettings.getLong("accountCodeLength").intValue();
            }
            if (giftCertSettings.getLong("pinCodeLength") != null) {
                pinNumberLength = giftCertSettings.getLong("pinCodeLength").intValue();
            }
            cardNumber = generateNumber(delegator, cardNumberLength, true);
            pinNumber = generateNumber(delegator, pinNumberLength, false);
            // in this case, the card number is the finAccountId
            finAccountId = cardNumber;
            // create the FinAccount
            Map<String, Object> acctCtx = UtilMisc.<String, Object>toMap("finAccountId", finAccountId);
            acctCtx.put("finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId);
            acctCtx.put("finAccountName", accountName);
            acctCtx.put("finAccountCode", pinNumber);
            acctCtx.put("userLogin", userLogin);
            acctResult = dispatcher.runSync("createFinAccount", acctCtx);
            if (ServiceUtil.isError(acctResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(acctResult));
            }
        } else {
            Map<String, Object> createAccountCtx = new HashMap<>();
            createAccountCtx.put("ownerPartyId", partyId);
            createAccountCtx.put("finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId);
            createAccountCtx.put("productStoreId", productStoreId);
            createAccountCtx.put("currencyUomId", currency);
            createAccountCtx.put("finAccountName", accountName + "for party [" + partyId + "]");
            createAccountCtx.put("userLogin", userLogin);
            acctResult = dispatcher.runSync("createFinAccountForStore", createAccountCtx);
            if (ServiceUtil.isError(acctResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(acctResult));
            }
            if (acctResult.get("finAccountId") != null) {
                finAccountId = cardNumber = (String) acctResult.get("finAccountId");
            }
            if (acctResult.get("finAccountCode") != null) {
                cardNumber = (String) acctResult.get("finAccountCode");
            }
        }
        // create the initial (deposit) transaction
        // do something tricky here: run as the "system" user
        // that can actually create a financial account transaction
        GenericValue permUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").cache().queryOne();
        refNum = createTransaction(delegator, dispatcher, permUserLogin, initialAmount, productStoreId, partyId, currencyUom, deposit, finAccountId, locale);
    } catch (GenericEntityException | GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCreationError", locale));
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("cardNumber", cardNumber);
    result.put("pinNumber", pinNumber);
    result.put("initialAmount", initialAmount);
    result.put("processResult", Boolean.TRUE);
    result.put("responseCode", "1");
    result.put("referenceNum", refNum);
    Debug.logInfo("Create GC Result - " + result, module);
    return result;
}
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) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 57 with GenericServiceException

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

the class GiftCertificateServices method giftCertificateReload.

public static Map<String, Object> giftCertificateReload(DispatchContext dctx, Map<String, ? extends Object> context) {
    // this service should always be called via FULFILLMENT_EXTSYNC
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue orderItem = (GenericValue) context.get("orderItem");
    Locale locale = (Locale) context.get("locale");
    // order ID for tracking
    String orderId = orderItem.getString("orderId");
    // the order header for store info
    GenericValue orderHeader = null;
    try {
        orderHeader = orderItem.getRelatedOne("OrderHeader", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Unable to get OrderHeader from OrderItem", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderCannotGetOrderHeader", UtilMisc.toMap("orderId", orderId), locale));
    }
    // get the order read helper
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    // get the currency
    String currency = orh.getCurrency();
    // make sure we have a currency
    if (currency == null) {
        currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
    }
    // get the product store
    String productStoreId = null;
    if (orderHeader != null) {
        productStoreId = orh.getProductStoreId();
    }
    if (productStoreId == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "AccountingGiftCerticateNumberCannotReload", UtilMisc.toMap("orderId", orderId), locale));
    }
    // payment config
    GenericValue paymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "GIFT_CARD", null, true);
    String paymentConfig = null;
    if (paymentSetting != null) {
        paymentConfig = paymentSetting.getString("paymentPropertiesPath");
    }
    if (paymentConfig == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "AccountingGiftCerticateNumberCannotGetPaymentConfiguration", locale));
    }
    // party ID for tracking
    GenericValue placingParty = orh.getPlacingParty();
    String partyId = null;
    if (placingParty != null) {
        partyId = placingParty.getString("partyId");
    }
    // amount of the gift card reload
    BigDecimal amount = orderItem.getBigDecimal("unitPrice");
    // survey information
    String surveyId = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.surveyId", delegator);
    // get the survey response
    GenericValue surveyResponse = null;
    try {
        // there should be only one
        surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId).orderBy("-responseDate").queryFirst();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "AccountingGiftCerticateNumberCannotReload", locale));
    }
    // get the response answers
    List<GenericValue> responseAnswers = null;
    try {
        responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "AccountingGiftCerticateNumberCannotReloadFromSurveyAnswers", locale));
    }
    // make a map of answer info
    Map<String, Object> answerMap = new HashMap<>();
    if (responseAnswers != null) {
        for (GenericValue answer : responseAnswers) {
            GenericValue question = null;
            try {
                question = answer.getRelatedOne("SurveyQuestion", false);
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "AccountingGiftCerticateNumberCannotReloadFromSurveyAnswers", locale));
            }
            if (question != null) {
                String desc = question.getString("description");
                // only support text response types for now
                String ans = answer.getString("textResponse");
                answerMap.put(desc, ans);
            }
        }
    }
    String cardNumberKey = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.cardNumber", delegator);
    String pinNumberKey = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.pinNumber", delegator);
    String cardNumber = (String) answerMap.get(cardNumberKey);
    String pinNumber = (String) answerMap.get(pinNumberKey);
    // reload the gift card
    Map<String, Object> reloadCtx = new HashMap<>();
    reloadCtx.put("productStoreId", productStoreId);
    reloadCtx.put("currency", currency);
    reloadCtx.put("partyId", partyId);
    reloadCtx.put("cardNumber", cardNumber);
    reloadCtx.put("pinNumber", pinNumber);
    reloadCtx.put("amount", amount);
    reloadCtx.put("userLogin", userLogin);
    String errorMessage = null;
    Map<String, Object> reloadGcResult = null;
    try {
        reloadGcResult = dispatcher.runSync("addFundsToGiftCertificate", reloadCtx);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        errorMessage = "Unable to call reload service!";
    }
    if (ServiceUtil.isError(reloadGcResult)) {
        errorMessage = ServiceUtil.getErrorMessage(reloadGcResult);
    }
    // create the fulfillment record
    Map<String, Object> gcFulFill = new HashMap<>();
    gcFulFill.put("typeEnumId", "GC_RELOAD");
    gcFulFill.put("userLogin", userLogin);
    gcFulFill.put("partyId", partyId);
    gcFulFill.put("orderId", orderId);
    gcFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
    gcFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
    gcFulFill.put("cardNumber", cardNumber);
    gcFulFill.put("pinNumber", pinNumber);
    gcFulFill.put("amount", amount);
    if (reloadGcResult != null) {
        gcFulFill.put("responseCode", reloadGcResult.get("responseCode"));
        gcFulFill.put("referenceNum", reloadGcResult.get("referenceNum"));
    }
    try {
        dispatcher.runAsync("createGcFulFillmentRecord", gcFulFill, true);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotStoreFulfillmentInfo", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    if (errorMessage != null) {
        // there was a problem
        Debug.logError("Reload Failed Need to Refund : " + reloadGcResult, module);
        // process the return
        try {
            Map<String, Object> refundCtx = UtilMisc.toMap("orderItem", orderItem, "partyId", partyId, "userLogin", userLogin);
            dispatcher.runAsync("refundGcPurchase", refundCtx, null, true, 300, true);
        } catch (GenericServiceException e) {
            Debug.logError(e, "ERROR! Unable to call create refund service; this failed reload will NOT be refunded", module);
        }
        return ServiceUtil.returnError(errorMessage);
    }
    // add some information to the answerMap for the email
    answerMap.put("processResult", reloadGcResult.get("processResult"));
    answerMap.put("responseCode", reloadGcResult.get("responseCode"));
    answerMap.put("previousAmount", reloadGcResult.get("previousBalance"));
    answerMap.put("amount", reloadGcResult.get("amount"));
    // get the email setting for this email type
    GenericValue productStoreEmail = null;
    String emailType = "PRDS_GC_RELOAD";
    try {
        productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", productStoreId, "emailType", emailType).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
    }
    if (productStoreEmail == null) {
        Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
    } else {
        answerMap.put("locale", locale);
        Map<String, Object> emailCtx = new HashMap<>();
        String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
        if (UtilValidate.isEmpty(bodyScreenLocation)) {
            bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
        }
        emailCtx.put("bodyScreenUri", bodyScreenLocation);
        emailCtx.put("bodyParameters", answerMap);
        emailCtx.put("sendTo", orh.getOrderEmailString());
        emailCtx.put("contentType", productStoreEmail.get("contentType"));
        emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
        emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
        emailCtx.put("sendBcc", productStoreEmail.get("bccAddress"));
        emailCtx.put("subject", productStoreEmail.getString("subject"));
        emailCtx.put("userLogin", userLogin);
        // send off the email async so we will retry on failed attempts
        try {
            dispatcher.runAsync("sendMailFromScreen", emailCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problem sending mail", module);
            // this is fatal; we will rollback and try again later
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotSendEmailNotice", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 58 with GenericServiceException

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

the class GiftCertificateServices method refundGcPurchase.

// Refund Service
public static Map<String, Object> refundGcPurchase(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue orderItem = (GenericValue) context.get("orderItem");
    String partyId = (String) context.get("partyId");
    Locale locale = (Locale) context.get("locale");
    // refresh the item object for status changes
    try {
        orderItem.refresh();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    Map<String, Object> returnableInfo = null;
    try {
        returnableInfo = dispatcher.runSync("getReturnableQuantity", UtilMisc.toMap("orderItem", orderItem, "userLogin", userLogin));
        if (ServiceUtil.isError(returnableInfo)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(returnableInfo));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorUnableToGetReturnItemInformation", locale));
    }
    if (returnableInfo != null) {
        BigDecimal returnableQuantity = (BigDecimal) returnableInfo.get("returnableQuantity");
        BigDecimal returnablePrice = (BigDecimal) returnableInfo.get("returnablePrice");
        Debug.logInfo("Returnable INFO : " + returnableQuantity + " @ " + returnablePrice + " :: " + orderItem, module);
        // create the return header
        Map<String, Object> returnHeaderInfo = new HashMap<>();
        returnHeaderInfo.put("fromPartyId", partyId);
        returnHeaderInfo.put("userLogin", userLogin);
        Map<String, Object> returnHeaderResp = null;
        try {
            returnHeaderResp = dispatcher.runSync("createReturnHeader", returnHeaderInfo);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorUnableToCreateReturnHeader", locale));
        }
        if (ServiceUtil.isError(returnHeaderResp)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(returnHeaderResp));
        }
        String returnId = (String) returnHeaderResp.get("returnId");
        if (UtilValidate.isEmpty(returnId)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorCreateReturnHeaderWithoutId", locale));
        }
        // create the return item
        Map<String, Object> returnItemInfo = new HashMap<>();
        returnItemInfo.put("returnId", returnId);
        returnItemInfo.put("returnReasonId", "RTN_DIG_FILL_FAIL");
        returnItemInfo.put("returnTypeId", "RTN_REFUND");
        returnItemInfo.put("returnItemType", "ITEM");
        returnItemInfo.put("description", orderItem.get("itemDescription"));
        returnItemInfo.put("orderId", orderItem.get("orderId"));
        returnItemInfo.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
        returnItemInfo.put("returnQuantity", returnableQuantity);
        returnItemInfo.put("returnPrice", returnablePrice);
        returnItemInfo.put("userLogin", userLogin);
        Map<String, Object> returnItemResp = null;
        try {
            returnItemResp = dispatcher.runSync("createReturnItem", returnItemInfo);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorUnableToCreateReturnItem", locale));
        }
        if (ServiceUtil.isError(returnItemResp)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(returnItemResp));
        }
        String returnItemSeqId = (String) returnItemResp.get("returnItemSeqId");
        if (returnItemSeqId == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorCreateReturnItemWithoutId", locale));
        }
        if (Debug.verboseOn()) {
            Debug.logVerbose("Created return item : " + returnId + " / " + returnItemSeqId, module);
        }
        // need the system userLogin to "fake" out the update service
        GenericValue admin = null;
        try {
            admin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorUnableToUpdateReturnHeaderStatusWithoutUserLogin", locale));
        }
        // update the status to received so it can process
        Map<String, Object> updateReturnInfo = new HashMap<>();
        updateReturnInfo.put("returnId", returnId);
        updateReturnInfo.put("statusId", "RETURN_RECEIVED");
        updateReturnInfo.put("currentStatusId", "RETURN_REQUESTED");
        updateReturnInfo.put("userLogin", admin);
        Map<String, Object> updateReturnResp = null;
        try {
            updateReturnResp = dispatcher.runSync("updateReturnHeader", updateReturnInfo);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderErrorUnableToUpdateReturnHeaderStatus", locale));
        }
        if (ServiceUtil.isError(updateReturnResp)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(updateReturnResp));
        }
    }
    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 59 with GenericServiceException

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

the class GiftCertificateServices method giftCertificateAuthorize.

public static Map<String, Object> giftCertificateAuthorize(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    GenericValue giftCard = (GenericValue) context.get("giftCard");
    String currency = (String) context.get("currency");
    String orderId = (String) context.get("orderId");
    BigDecimal amount = (BigDecimal) context.get("processAmount");
    // make sure we have a currency
    if (currency == null) {
        currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
    }
    // obtain the order information
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    String productStoreId = orh.getProductStoreId();
    try {
        // if the store requires pin codes, then validate pin code against card number, and the gift certificate's finAccountId is the gift card's card number
        // otherwise, the gift card's card number is an ecrypted string, which must be decoded to find the FinAccount
        GenericValue giftCertSettings = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where("productStoreId", productStoreId, "finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId).cache().queryOne();
        GenericValue finAccount = null;
        String finAccountId = null;
        if (UtilValidate.isNotEmpty(giftCertSettings)) {
            if ("Y".equals(giftCertSettings.getString("requirePinCode"))) {
                if (validatePin(delegator, giftCard.getString("cardNumber"), giftCard.getString("pinNumber"))) {
                    finAccountId = giftCard.getString("cardNumber");
                    finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
                }
            } else {
                finAccount = FinAccountHelper.getFinAccountFromCode(giftCard.getString("cardNumber"), delegator);
                if (finAccount == null) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberNotFound", UtilMisc.toMap("finAccountId", ""), locale));
                }
                finAccountId = finAccount.getString("finAccountId");
            }
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountSetting", UtilMisc.toMap("productStoreId", productStoreId, "finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId), locale));
        }
        if (finAccountId == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberPinNotValid", locale));
        }
        // check for expiration date
        if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale));
        }
        // 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");
        Boolean processResult = null;
        String refNum = null;
        Map<String, Object> result = ServiceUtil.returnSuccess();
        // make sure to round and scale it to the same as availableBalance
        amount = amount.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);
        // if availableBalance equal to or greater than amount, then auth
        if (UtilValidate.isNotEmpty(availableBalance) && availableBalance.compareTo(amount) >= 0) {
            Timestamp thruDate = null;
            if (giftCertSettings.getLong("authValidDays") != null) {
                thruDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), giftCertSettings.getLong("authValidDays"));
            }
            Map<String, Object> tmpResult = dispatcher.runSync("createFinAccountAuth", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "amount", amount, "currencyUomId", currency, "thruDate", thruDate, "userLogin", userLogin));
            if (ServiceUtil.isError(tmpResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
            } else {
                refNum = (String) tmpResult.get("finAccountAuthId");
                processResult = Boolean.TRUE;
            }
        } else {
            Debug.logError("Attempted to authorize [" + amount + "] against a balance of only [" + availableBalance + "]", module);
            // a refNum is always required from authorization
            refNum = "N/A";
            processResult = Boolean.FALSE;
        }
        result.put("processAmount", amount);
        result.put("authResult", processResult);
        result.put("processAmount", amount);
        result.put("authFlag", "2");
        result.put("authCode", "A");
        result.put("captureCode", "C");
        result.put("authRefNum", refNum);
        return result;
    } catch (GenericEntityException | GenericServiceException ex) {
        Debug.logError(ex, "Cannot authorize gift certificate", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotAuthorize", 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 60 with GenericServiceException

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

the class PaymentGatewayServices method verifyCreditCard.

// Verify Credit Card (Manually) Service
public static Map<String, Object> verifyCreditCard(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    String productStoreId = (String) context.get("productStoreId");
    String mode = (String) context.get("mode");
    String paymentMethodId = (String) context.get("paymentMethodId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    if (Debug.infoOn()) {
        Debug.logInfo("Running verifyCreditCard [ " + paymentMethodId + "] for store: " + productStoreId, module);
    }
    GenericValue productStore = null;
    productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
    String productStorePaymentProperties = "payment.properties";
    if (productStore != null) {
        productStorePaymentProperties = ProductStoreWorker.getProductStorePaymentProperties(delegator, productStoreId, "CREDIT_CARD", "PRDS_PAY_AUTH", false);
    }
    String amount = null;
    if ("CREATE".equalsIgnoreCase(mode)) {
        amount = EntityUtilProperties.getPropertyValue(productStorePaymentProperties, "payment.general.cc_create.auth", delegator);
    } else if ("UPDATE".equalsIgnoreCase(mode)) {
        amount = EntityUtilProperties.getPropertyValue(productStorePaymentProperties, "payment.general.cc_update.auth", delegator);
    }
    if (Debug.infoOn()) {
        Debug.logInfo("Running credit card verification [" + paymentMethodId + "] (" + amount + ") : " + productStorePaymentProperties + " : " + mode, module);
    }
    if (UtilValidate.isNotEmpty(amount)) {
        BigDecimal authAmount = new BigDecimal(amount);
        if (authAmount.compareTo(BigDecimal.ZERO) > 0) {
            Map<String, Object> ccAuthContext = new HashMap<>();
            ccAuthContext.put("paymentMethodId", paymentMethodId);
            ccAuthContext.put("productStoreId", productStoreId);
            ccAuthContext.put("amount", authAmount);
            ccAuthContext.put("userLogin", userLogin);
            Map<String, Object> results;
            try {
                results = dispatcher.runSync("manualForcedCcAuthTransaction", ccAuthContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
            if (ServiceUtil.isError(results)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingCreditCardManualAuthFailedError", locale));
            }
        }
    }
    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) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

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