Search in sources :

Example 41 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class PaymentGatewayServices method authOrderPaymentPreference.

/**
 * Authorizes a single order preference with an option to specify an amount. The result map has the Booleans
 * "errors" and "finished" which notify the user if there were any errors and if the authorization was finished.
 * There is also a List "messages" for the authorization response messages and a BigDecimal, "processAmount" as the
 * amount processed.
 *
 * TODO: it might be nice to return the paymentGatewayResponseId
 */
public static Map<String, Object> authOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
    BigDecimal overrideAmount = (BigDecimal) context.get("overrideAmount");
    // validate overrideAmount if its available
    if (overrideAmount != null) {
        if (overrideAmount.compareTo(BigDecimal.ZERO) < 0) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentAmountIsNegative", UtilMisc.toMap("overrideAmount", overrideAmount), locale));
        }
        if (overrideAmount.compareTo(BigDecimal.ZERO) == 0) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentAmountIsZero", UtilMisc.toMap("overrideAmount", overrideAmount), locale));
        }
    }
    GenericValue orderHeader = null;
    GenericValue orderPaymentPreference = null;
    try {
        orderPaymentPreference = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
        orderHeader = orderPaymentPreference.getRelatedOne("OrderHeader", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    // get the total remaining
    BigDecimal totalRemaining = orh.getOrderGrandTotal();
    // get the process attempts so far
    Long procAttempt = orderPaymentPreference.getLong("processAttempt");
    if (procAttempt == null) {
        procAttempt = Long.valueOf(0);
    }
    // update the process attempt count
    orderPaymentPreference.set("processAttempt", Long.valueOf(procAttempt.longValue() + 1));
    try {
        orderPaymentPreference.store();
        orderPaymentPreference.refresh();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale));
    }
    // if we are already authorized, then this is a re-auth request
    boolean reAuth = false;
    if (orderPaymentPreference.get("statusId") != null && "PAYMENT_AUTHORIZED".equals(orderPaymentPreference.getString("statusId"))) {
        reAuth = true;
    }
    // use overrideAmount or maxAmount
    BigDecimal transAmount = null;
    if (overrideAmount != null) {
        transAmount = overrideAmount;
    } else {
        transAmount = orderPaymentPreference.getBigDecimal("maxAmount");
    }
    // round this before moving on just in case a funny number made it this far
    transAmount = transAmount.setScale(decimals, rounding);
    // if our transaction amount exists and is zero, there's nothing to process, so return
    if ((transAmount != null) && (transAmount.compareTo(BigDecimal.ZERO) <= 0)) {
        Map<String, Object> results = ServiceUtil.returnSuccess();
        // finished is true since there is nothing to do
        results.put("finished", Boolean.TRUE);
        // errors is false since no error occurred
        results.put("errors", Boolean.FALSE);
        return results;
    }
    try {
        // call the authPayment method
        Map<String, Object> authPaymentResult = authPayment(dispatcher, userLogin, orh, orderPaymentPreference, totalRemaining, reAuth, transAmount);
        // handle the response
        if (authPaymentResult != null) {
            // not null result means either an approval or decline; null would mean error
            BigDecimal thisAmount = (BigDecimal) authPaymentResult.get("processAmount");
            // process the auth results
            try {
                boolean processResult = processResult(dctx, authPaymentResult, userLogin, orderPaymentPreference, locale);
                if (processResult) {
                    Map<String, Object> results = ServiceUtil.returnSuccess();
                    results.put("messages", authPaymentResult.get("customerRespMsgs"));
                    results.put("processAmount", thisAmount);
                    results.put("finished", Boolean.TRUE);
                    results.put("errors", Boolean.FALSE);
                    results.put("authCode", authPaymentResult.get("authCode"));
                    return results;
                } else {
                    boolean needsNsfRetry = needsNsfRetry(orderPaymentPreference, authPaymentResult, delegator);
                    // if we are doing an NSF retry then also...
                    if (needsNsfRetry) {
                    // TODO: what do we do with this? we need to fail the auth but still allow the order through so it can be fixed later
                    // NOTE: this is called through a different path for auto re-orders, so it should be good to go... will leave this comment here just in case...
                    }
                    // if we have a failure at this point and no NSF retry is needed, then try other credit cards on file, if the user has any
                    if (!needsNsfRetry) {
                        // is this an auto-order?
                        if (UtilValidate.isNotEmpty(orderHeader.getString("autoOrderShoppingListId"))) {
                            GenericValue productStore = orderHeader.getRelatedOne("ProductStore", false);
                            // according to the store should we try other cards?
                            if ("Y".equals(productStore.getString("autoOrderCcTryOtherCards"))) {
                                // get other credit cards for the bill to party
                                List<GenericValue> otherPaymentMethodAndCreditCardList = null;
                                String billToPartyId = null;
                                GenericValue billToParty = orh.getBillToParty();
                                if (billToParty != null) {
                                    billToPartyId = billToParty.getString("partyId");
                                } else {
                                // TODO optional: any other ways to find the bill to party? perhaps look at info from OrderPaymentPreference, ie search back from other PaymentMethod...
                                }
                                if (UtilValidate.isNotEmpty(billToPartyId)) {
                                    otherPaymentMethodAndCreditCardList = EntityQuery.use(delegator).from("PaymentMethodAndCreditCard").where("partyId", billToPartyId, "paymentMethodTypeId", "CREDIT_CARD").filterByDate().queryList();
                                }
                                if (UtilValidate.isNotEmpty(otherPaymentMethodAndCreditCardList)) {
                                    for (GenericValue otherPaymentMethodAndCreditCard : otherPaymentMethodAndCreditCardList) {
                                        // change OrderPaymentPreference in memory only and call auth service
                                        orderPaymentPreference.set("paymentMethodId", otherPaymentMethodAndCreditCard.getString("paymentMethodId"));
                                        Map<String, Object> authRetryResult = authPayment(dispatcher, userLogin, orh, orderPaymentPreference, totalRemaining, reAuth, transAmount);
                                        try {
                                            boolean processRetryResult = processResult(dctx, authPaymentResult, userLogin, orderPaymentPreference, locale);
                                            if (processRetryResult) {
                                                // wow, we got here that means the other card was successful...
                                                // on success save the OrderPaymentPreference, and then return finished (which will break from loop)
                                                orderPaymentPreference.store();
                                                Map<String, Object> results = ServiceUtil.returnSuccess();
                                                results.put("messages", authRetryResult.get("customerRespMsgs"));
                                                results.put("processAmount", thisAmount);
                                                results.put("finished", Boolean.TRUE);
                                                results.put("errors", Boolean.FALSE);
                                                return results;
                                            }
                                        } catch (GeneralException e) {
                                            String errMsg = "Error saving and processing payment authorization results: " + e.toString();
                                            Debug.logError(e, errMsg + "; authRetryResult: " + authRetryResult, module);
                                            Map<String, Object> results = ServiceUtil.returnSuccess();
                                            results.put(ModelService.ERROR_MESSAGE, errMsg);
                                            results.put("finished", Boolean.FALSE);
                                            results.put("errors", Boolean.TRUE);
                                            return results;
                                        }
                                    // if no sucess, fall through to return not finished
                                    }
                                }
                            }
                        }
                    }
                    Map<String, Object> results = ServiceUtil.returnSuccess();
                    results.put("messages", authPaymentResult.get("customerRespMsgs"));
                    results.put("finished", Boolean.FALSE);
                    results.put("errors", Boolean.FALSE);
                    return results;
                }
            } catch (GeneralException e) {
                String errMsg = "Error saving and processing payment authorization results: " + e.toString();
                Debug.logError(e, errMsg + "; authPaymentResult: " + authPaymentResult, module);
                Map<String, Object> results = ServiceUtil.returnSuccess();
                results.put(ModelService.ERROR_MESSAGE, errMsg);
                results.put("finished", Boolean.FALSE);
                results.put("errors", Boolean.TRUE);
                return results;
            }
        } else {
            // error with payment processor; will try later
            String errMsg = "Invalid Order Payment Preference: maxAmount is 0";
            Debug.logInfo(errMsg, module);
            Map<String, Object> results = ServiceUtil.returnSuccess();
            results.put("finished", Boolean.FALSE);
            results.put("errors", Boolean.TRUE);
            results.put(ModelService.ERROR_MESSAGE, errMsg);
            orderPaymentPreference.set("statusId", "PAYMENT_CANCELLED");
            try {
                orderPaymentPreference.store();
            } catch (GenericEntityException e) {
                Debug.logError(e, "ERROR: Problem setting OrderPaymentPreference status to CANCELLED", module);
            }
            return results;
        }
    } catch (GeneralException e) {
        Debug.logError(e, "Error processing payment authorization", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingPaymentCannotBeAuthorized", UtilMisc.toMap("errroString", e.toString()), locale));
    }
}
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) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 42 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class PaymentGatewayServices method processCaptureSplitPayment.

public static Map<String, Object> processCaptureSplitPayment(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");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal splitAmount = (BigDecimal) context.get("splitAmount");
    String orderId = paymentPref.getString("orderId");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    String statusId = "PAYMENT_NOT_AUTH";
    if ("EXT_BILLACT".equals(paymentPref.getString("paymentMethodTypeId"))) {
        statusId = "PAYMENT_NOT_RECEIVED";
    } else if ("EXT_PAYPAL".equals(paymentPref.get("paymentMethodTypeId"))) {
        statusId = "PAYMENT_AUTHORIZED";
    }
    // create a new payment preference
    Debug.logInfo("Creating payment preference split", module);
    String newPrefId = delegator.getNextSeqId("OrderPaymentPreference");
    GenericValue newPref = delegator.makeValue("OrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", newPrefId));
    newPref.set("orderId", paymentPref.get("orderId"));
    newPref.set("paymentMethodTypeId", paymentPref.get("paymentMethodTypeId"));
    newPref.set("paymentMethodId", paymentPref.get("paymentMethodId"));
    newPref.set("maxAmount", splitAmount);
    newPref.set("statusId", statusId);
    newPref.set("createdDate", UtilDateTime.nowTimestamp());
    if (userLogin != null) {
        newPref.set("createdByUserLogin", userLogin.getString("userLoginId"));
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("New preference : " + newPref, module);
    }
    Map<String, Object> processorResult = null;
    try {
        // create the new payment preference
        delegator.create(newPref);
        // fake it and copy the existing auth with the remaining amount
        if ("EXT_PAYPAL".equals(paymentPref.get("paymentMethodTypeId"))) {
            String newAuthId = delegator.getNextSeqId("PaymentGatewayResponse");
            GenericValue authTrans = getAuthTransaction(paymentPref);
            GenericValue newAuthTrans = delegator.makeValue("PaymentGatewayResponse", authTrans);
            newAuthTrans.set("paymentGatewayResponseId", newAuthId);
            newAuthTrans.set("orderPaymentPreferenceId", newPref.get("orderPaymentPreferenceId"));
            newAuthTrans.set("amount", splitAmount);
            savePgr(dctx, newAuthTrans);
        } else if ("PAYMENT_NOT_AUTH".equals(statusId)) {
            // authorize the new preference
            processorResult = authPayment(dispatcher, userLogin, orh, newPref, splitAmount, false, null);
            if (processorResult != null) {
                // process the auth results
                boolean authResult = processResult(dctx, processorResult, userLogin, newPref, locale);
                if (!authResult) {
                    Debug.logError("Authorization failed : " + newPref + " : " + processorResult, module);
                }
            } else {
                Debug.logError("Payment not authorized : " + newPref + " (no process result)", module);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "ERROR: cannot create new payment preference : " + newPref, module);
    } catch (GeneralException e) {
        if (processorResult != null) {
            Debug.logError(e, "Trouble processing the auth result: " + newPref + " : " + processorResult, module);
        } else {
            Debug.logError(e, "Trouble authorizing the payment: " + newPref, module);
        }
    }
    return ServiceUtil.returnSuccess();
}
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) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper)

Example 43 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ContentManagementWorker method getPublishedLinks.

public static List<Object[]> getPublishedLinks(Delegator delegator, String targContentId, String rootPubId, GenericValue userLogin, Security security, String permittedAction, String permittedOperations, String passedRoles) throws GeneralException {
    // Set up one map with all the top-level publish points (to which only one sub point can be attached to)
    // and another map (publishPointMapAll) that points to one of the top-level points.
    List<GenericValue> allPublishPointList = getAllPublishPoints(delegator, rootPubId);
    List<String[]> publishPointList = getPermittedPublishPoints(delegator, allPublishPointList, userLogin, security, permittedAction, permittedOperations, passedRoles);
    Map<String, Object> publishPointMap = new HashMap<String, Object>();
    Map<String, Object> publishPointMapAll = new HashMap<String, Object>();
    for (String[] arr : publishPointList) {
        String contentId = arr[0];
        String description = arr[1];
        List<Object[]> subPointList = new LinkedList<Object[]>();
        Object[] subArr = { contentId, subPointList, description, null };
        publishPointMap.put(contentId, subArr);
        publishPointMapAll.put(contentId, contentId);
        List<GenericValue> subPublishPointList = getAllPublishPoints(delegator, contentId);
        for (GenericValue webSitePublishPoint2 : subPublishPointList) {
            String contentId2 = (String) webSitePublishPoint2.get("contentId");
            String description2 = (String) webSitePublishPoint2.get("templateTitle");
            publishPointMapAll.put(contentId2, contentId);
            Object[] subArr2 = { contentId2, description2, null };
            subPointList.add(subArr2);
        }
    }
    List<GenericValue> assocValueList = null;
    try {
        assocValueList = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK").filterByDate().cache().queryList();
    } catch (GenericEntityException e) {
        throw new GeneralException(e.getMessage());
    }
    for (GenericValue contentAssoc : assocValueList) {
        String contentIdTo = contentAssoc.getString("contentIdTo");
        String topContentId = (String) publishPointMapAll.get(contentIdTo);
        Object[] subArr = (Object[]) publishPointMap.get(topContentId);
        if (contentIdTo.equals(topContentId)) {
            subArr[3] = contentAssoc.get("fromDate");
        } else {
            if (subArr != null) {
                List<Object[]> subPointList = UtilGenerics.checkList(subArr[1]);
                Iterator<Object[]> it5 = subPointList.iterator();
                Object[] subArr2 = null;
                while (it5.hasNext()) {
                    subArr2 = it5.next();
                    String contentId5 = (String) subArr2[0];
                    if (contentId5.equals(contentIdTo))
                        break;
                }
                subArr2[2] = contentAssoc.get("fromDate");
            }
        }
    }
    List<Object[]> publishedLinkList = new LinkedList<Object[]>();
    for (Entry<String, Object> entry : publishPointMap.entrySet()) {
        String contentId = entry.getKey();
        Object[] subPointArr = (Object[]) publishPointMap.get(contentId);
        publishedLinkList.add(subPointArr);
    }
    return publishedLinkList;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 44 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ContentManagementWorker method getAllDepartmentContent.

/**
 *     Returns a list of "department" (having ContentAssoc of type "DEPARTMENT")
 *     Content entities that are children of parentPubPt
 *
 *     @param parentPubPt The parent publish point.
 */
public static List<GenericValue> getAllDepartmentContent(Delegator delegator, String parentPubPt) throws GeneralException {
    List<GenericValue> relatedPubPts = null;
    try {
        relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc").where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT").cache().queryList();
    } catch (GenericEntityException e) {
        throw new GeneralException(e.getMessage());
    }
    List<GenericValue> allDepartmentPoints = new LinkedList<GenericValue>();
    GenericValue departmentContent = null;
    for (GenericValue contentAssoc : relatedPubPts) {
        String pub = (String) contentAssoc.get("contentId");
        departmentContent = EntityQuery.use(delegator).from("Content").where("contentId", pub).cache().queryOne();
        allDepartmentPoints.add(departmentContent);
    }
    return allDepartmentPoints;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList)

Example 45 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class PayPalServices method getExpressCheckout.

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        encoder.add("TOKEN", token);
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }
    NVPDecoder decoder;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
        cart.addOrderNote(decoder.get("NOTE"));
    }
    if (cart.getUserLogin() == null) {
        try {
            GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "anonymous").queryOne();
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
        // Check nothing has been set on the anon userLogin either
        partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
        cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
        GenericValue party = null;
        try {
            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }
    Map<String, Object> inMap = new HashMap<String, Object>();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
        newParty = true;
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("personalTitle", decoder.get("SALUTATION"));
        inMap.put("firstName", decoder.get("FIRSTNAME"));
        inMap.put("middleName", decoder.get("MIDDLENAME"));
        inMap.put("lastName", decoder.get("LASTNAME"));
        inMap.put("suffix", decoder.get("SUFFIX"));
        try {
            outMap = dispatcher.runSync("createPerson", inMap);
            partyId = (String) outMap.get("partyId");
            cart.setOrderPartyId(partyId);
            cart.getUserLogin().setString("partyId", partyId);
            inMap.clear();
            inMap.put("userLogin", cart.getUserLogin());
            inMap.put("partyId", partyId);
            inMap.put("roleTypeId", "CUSTOMER");
            dispatcher.runSync("createPartyRole", inMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")), EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress))));
        try {
            GenericValue matchingEmail = EntityQuery.use(delegator).from("PartyAndContactMech").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (matchingEmail != null) {
                emailContactMechId = matchingEmail.getString("contactMechId");
            } else {
                // No email found so we'll need to create one but first check if it should be PRIMARY or just BILLING
                long primaryEmails = EntityQuery.use(delegator).from("PartyContactWithPurpose").where("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL").filterByDate("contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate").queryCount();
                if (primaryEmails > 0)
                    emailContactPurposeTypeId = "BILLING_EMAIL";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (emailContactMechId == null) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
        inMap.put("emailAddress", emailAddress);
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        // Going to assume PayPal has taken care of this for us
        inMap.put("verified", "Y");
        inMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
            emailContactMechId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);
    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
        inMap.clear();
        if (phoneNumber.startsWith("+")) {
            // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
            String[] phoneNumbers = phoneNumber.split(" ");
            inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
            inMap.put("contactNumber", phoneNumbers[1]);
        } else {
            // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
            inMap.put("countryCode", "1");
            String[] phoneNumbers = phoneNumber.split("-");
            inMap.put("areaCode", phoneNumbers[0]);
            inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
        }
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        try {
            outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
            phoneContactId = (String) outMap.get("contactMechId");
            cart.addContactMech("PHONE_BILLING", phoneContactId);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = new HashMap<String, Object>();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put("stateProvinceGeoId", parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
        // We want an exact match only
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(postalMap), EntityCondition.makeCondition(UtilMisc.toMap("attnName", null, "directions", null, "postalCodeExt", null, "postalCodeGeoId", null)), EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityQuery.use(delegator).from("PartyAndPostalAddress").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                List<GenericValue> postalPurposes = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyId, "contactMechId", postalContactId).filterByDate().queryList();
                List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList(postalPurposes, "contactMechPurposeTypeId", false);
                if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) {
                    needsShippingPurpose = false;
                }
                if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("BILLING_LOCATION")) {
                    needsBillingPurpose = false;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (postalContactId == null) {
        postalMap.put("userLogin", cart.getUserLogin());
        postalMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
            postalContactId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechId", postalContactId);
        inMap.put("partyId", partyId);
        try {
            if (needsShippingPurpose) {
                inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
            if (needsBillingPurpose) {
                inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
        } catch (GenericServiceException e) {
            // Not the end of the world, we'll carry on
            Debug.logInfo(e.getMessage(), module);
        }
    }
    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
        cart.setAllCarrierPartyId("_NA_");
        cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
        String[] shipMethodSplit = shipMethod.split(" - ");
        cart.setAllCarrierPartyId(shipMethodSplit[0]);
        String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
        try {
            GenericValue shipmentMethod = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where("productStoreId", cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER", "description", shippingMethodTypeDesc).queryFirst();
            cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
        } catch (GenericEntityException e1) {
            Debug.logError(e1, module);
        }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
        Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
        for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
            cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
        }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
        return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }
    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
        shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
        cho.calcAndAddTax();
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));
    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");
    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, RoundingMode.HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) PayPalException(com.paypal.sdk.exceptions.PayPalException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)216 GenericValue (org.apache.ofbiz.entity.GenericValue)133 Delegator (org.apache.ofbiz.entity.Delegator)101 Locale (java.util.Locale)81 HashMap (java.util.HashMap)71 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)68 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)68 IOException (java.io.IOException)65 BigDecimal (java.math.BigDecimal)55 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)54 Writer (java.io.Writer)29 LinkedList (java.util.LinkedList)29 Map (java.util.Map)29 Timestamp (java.sql.Timestamp)26 StringWriter (java.io.StringWriter)19 Environment (freemarker.core.Environment)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)14 HttpSession (javax.servlet.http.HttpSession)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13