public void renderPortalPagePortletBody( Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException { String portalPortletId = portalPortlet.getString("portalPortletId"); String screenName = portalPortlet.getString("screenName"); String screenLocation = portalPortlet.getString("screenLocation"); ModelScreen modelScreen = null; if (UtilValidate.isNotEmpty(screenName) && UtilValidate.isNotEmpty(screenLocation)) { try { modelScreen = ScreenFactory.getScreenFromLocation(screenLocation, screenName); } catch (IOException e) { String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString(); Debug.logError(e, errMsg, module); throw new RuntimeException(errMsg); } catch (SAXException e) { String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString(); Debug.logError(e, errMsg, module); throw new RuntimeException(errMsg); } catch (ParserConfigurationException e) { String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString(); Debug.logError(e, errMsg, module); throw new RuntimeException(errMsg); } } modelScreen.renderScreenString(writer, context, this); }
private static NVPDecoder sendNVPRequest(GenericValue payPalConfig, NVPEncoder encoder) throws PayPalException { NVPCallerServices caller = new NVPCallerServices(); try { APIProfile profile = ProfileFactory.createSignatureAPIProfile(); profile.setAPIUsername(payPalConfig.getString("apiUserName")); profile.setAPIPassword(payPalConfig.getString("apiPassword")); profile.setSignature(payPalConfig.getString("apiSignature")); profile.setEnvironment(payPalConfig.getString("apiEnvironment")); caller.setAPIProfile(profile); } catch (PayPalException e) { Debug.logError(e.getMessage(), module); } String requestMessage = encoder.encode(); String responseMessage = caller.call(requestMessage); NVPDecoder decoder = new NVPDecoder(); decoder.decode(responseMessage); if (!"Success".equals(decoder.get("ACK"))) { Debug.logError( "A response other than success was received from PayPal: " + responseMessage, module); } return decoder; }
private static String getLastProductStoreId(Delegator delegator, String finAccountId) { GenericValue trans = null; try { trans = EntityQuery.use(delegator) .from("FinAccountTrans") .where( EntityCondition.makeCondition( "finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"), EntityCondition.makeCondition( "finAccountId", EntityOperator.EQUALS, finAccountId), EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null)) .orderBy("-transactionDate") .queryFirst(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (trans != null) { String orderId = trans.getString("orderId"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); return orh.getProductStoreId(); } // none found; pick one from our set stores try { GenericValue store = EntityQuery.use(delegator).from("ProductStore").orderBy("productStoreId").queryFirst(); if (store != null) return store.getString("productStoreId"); } catch (GenericEntityException e) { Debug.logError(e, module); } return null; }
public static List<Map<String, GenericValue>> getPartyPaymentMethodValueMaps( Delegator delegator, String partyId, Boolean showOld) { List<Map<String, GenericValue>> paymentMethodValueMaps = FastList.newInstance(); try { List<GenericValue> paymentMethods = delegator.findByAnd("PaymentMethod", UtilMisc.toMap("partyId", partyId)); if (!showOld) paymentMethods = EntityUtil.filterByDate(paymentMethods, true); for (GenericValue paymentMethod : paymentMethods) { Map<String, GenericValue> valueMap = FastMap.newInstance(); paymentMethodValueMaps.add(valueMap); valueMap.put("paymentMethod", paymentMethod); if ("CREDIT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) { GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard"); if (creditCard != null) valueMap.put("creditCard", creditCard); } else if ("GIFT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) { GenericValue giftCard = paymentMethod.getRelatedOne("GiftCard"); if (giftCard != null) valueMap.put("giftCard", giftCard); } else if ("EFT_ACCOUNT".equals(paymentMethod.getString("paymentMethodTypeId"))) { GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount"); if (eftAccount != null) valueMap.put("eftAccount", eftAccount); } } } catch (GenericEntityException e) { Debug.logWarning(e, module); } return paymentMethodValueMaps; }
public static String[] findFirstMatchingPartyAndContactMechId( Delegator delegator, String address1, String address2, String city, String stateProvinceGeoId, String postalCode, String postalCodeExt, String countryGeoId, String firstName, String middleName, String lastName) throws GeneralException { List<GenericValue> matching = findMatchingPersonPostalAddresses( delegator, address1, address2, city, stateProvinceGeoId, postalCode, postalCodeExt, countryGeoId, firstName, middleName, lastName); GenericValue v = EntityUtil.getFirst(matching); if (v != null) { return new String[] {v.getString("partyId"), v.getString("contactMechId")}; } return null; }
/** * Finds all matching PartyAndPostalAddress records based on the values provided. Excludes party * records with a statusId of PARTY_DISABLED. Results are ordered by descending * PartyContactMech.fromDate. The matching process is as follows: 1. Calls {@link * #findMatchingPartyPostalAddress(Delegator, String, String, String, String, String, String, * String, String)} to retrieve a list of address matched PartyAndPostalAddress records. Results * are limited to Parties of type PERSON. 2. For each matching PartyAndPostalAddress record, the * Person record for the Party is then retrieved and an upper case comparison is performed against * the supplied firstName, lastName and if provided, middleName. * * @param delegator Delegator instance * @param address1 PostalAddress.address1 to match against (Required). * @param address2 Optional PostalAddress.address2 to match against. * @param city PostalAddress.city value to match against (Required). * @param stateProvinceGeoId Optional PostalAddress.stateProvinceGeoId value to match against. If * null or "**" is passed then the value will be ignored during matching. "NA" can be passed * in place of "_NA_". * @param postalCode PostalAddress.postalCode value to match against. Cannot be null but can be * skipped by passing a value starting with an "*". If the length of the supplied string is 10 * characters and the string contains a "-" then the postal code will be split at the "-" and * the second half will be used as the postalCodeExt. * @param postalCodeExt Optional PostalAddress.postalCodeExt value to match against. Will be * overridden if a postalCodeExt value is retrieved from postalCode as described above. * @param countryGeoId Optional PostalAddress.countryGeoId value to match against. * @param firstName Person.firstName to match against (Required). * @param middleName Optional Person.middleName to match against. * @param lastName Person.lastName to match against (Required). * @return List of PartyAndPostalAddress GenericValue objects that match the supplied criteria. * @throws GeneralException */ public static List<GenericValue> findMatchingPersonPostalAddresses( Delegator delegator, String address1, String address2, String city, String stateProvinceGeoId, String postalCode, String postalCodeExt, String countryGeoId, String firstName, String middleName, String lastName) throws GeneralException { // return list List<GenericValue> returnList = FastList.newInstance(); // address information if (firstName == null || lastName == null) { throw new IllegalArgumentException(); } List<GenericValue> validFound = findMatchingPartyPostalAddress( delegator, address1, address2, city, stateProvinceGeoId, postalCode, postalCodeExt, countryGeoId, "PERSON"); if (UtilValidate.isNotEmpty(validFound)) { for (GenericValue partyAndAddr : validFound) { String partyId = partyAndAddr.getString("partyId"); if (UtilValidate.isNotEmpty(partyId)) { GenericValue p = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId)); if (p != null) { String fName = p.getString("firstName"); String lName = p.getString("lastName"); String mName = p.getString("middleName"); if (lName.toUpperCase().equals(lastName.toUpperCase())) { if (fName.toUpperCase().equals(firstName.toUpperCase())) { if (mName != null && middleName != null) { if (mName.toUpperCase().equals(middleName.toUpperCase())) { returnList.add(partyAndAddr); } } else if (middleName == null) { returnList.add(partyAndAddr); } } } } } } } return returnList; }
/** * Method to return the amount applied converted to the currency of payment * * @param paymentApplicationId the payment application id * @return appliedAmount the applied amount as BigDecimal */ public static BigDecimal getPaymentAppliedAmount( Delegator delegator, String paymentApplicationId) { GenericValue paymentApplication = null; BigDecimal appliedAmount = BigDecimal.ZERO; try { paymentApplication = delegator.findByPrimaryKey( "PaymentApplication", UtilMisc.toMap("paymentApplicationId", paymentApplicationId)); appliedAmount = paymentApplication.getBigDecimal("amountApplied"); if (paymentApplication.get("paymentId") != null) { GenericValue payment = paymentApplication.getRelatedOne("Payment"); if (paymentApplication.get("invoiceId") != null && payment.get("actualCurrencyAmount") != null && payment.get("actualCurrencyUomId") != null) { GenericValue invoice = paymentApplication.getRelatedOne("Invoice"); if (payment.getString("actualCurrencyUomId").equals(invoice.getString("currencyUomId"))) { appliedAmount = appliedAmount .multiply(payment.getBigDecimal("amount")) .divide(payment.getBigDecimal("actualCurrencyAmount"), new MathContext(100)); } } } } catch (GenericEntityException e) { Debug.logError(e, "Problem getting Payment", module); } return appliedAmount; }
public static GenericValue getPaymentAddress(Delegator delegator, String partyId) { List<GenericValue> paymentAddresses = null; try { paymentAddresses = delegator.findByAnd( "PartyContactMechPurpose", UtilMisc.toMap("partyId", partyId, "contactMechPurposeTypeId", "PAYMENT_LOCATION"), UtilMisc.toList("-fromDate")); paymentAddresses = EntityUtil.filterByDate(paymentAddresses); } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting PartyContactMechPurpose entity list", module); } // get the address for the primary contact mech GenericValue purpose = EntityUtil.getFirst(paymentAddresses); GenericValue postalAddress = null; if (purpose != null) { try { postalAddress = delegator.findByPrimaryKey( "PostalAddress", UtilMisc.toMap("contactMechId", purpose.getString("contactMechId"))); } catch (GenericEntityException e) { Debug.logError( e, "Trouble getting PostalAddress record for contactMechId: " + purpose.getString("contactMechId"), module); } } return postalAddress; }
/** * Converts the supplied String into a String suitable for address line matching. Performs the * following transformations on the supplied String: - Converts to upper case - Retrieves all * records from the AddressMatchMap table and replaces all occurrences of addressMatchMap.mapKey * with addressMatchMap.mapValue using upper case matching. - Removes all non-word characters from * the String i.e. everything except A-Z, 0-9 and _ * * @param delegator A Delegator instance * @param address The address String to convert * @return The converted Address */ public static String makeMatchingString(Delegator delegator, String address) { if (address == null) { return null; } // upper case the address String str = address.trim().toUpperCase(); // replace mapped words List<GenericValue> addressMap = null; try { addressMap = delegator.findList( "AddressMatchMap", null, null, UtilMisc.toList("sequenceNum"), null, false); } catch (GenericEntityException e) { Debug.logError(e, module); } if (addressMap != null) { for (GenericValue v : addressMap) { str = str.replaceAll( v.getString("mapKey").toUpperCase(), v.getString("mapValue").toUpperCase()); } } // remove all non-word characters return str.replaceAll("\\W", ""); }
/** * Finds or creates a specialized (auto-save) shopping list used to record shopping bag contents * between user visits. */ public static String getAutoSaveListId( Delegator delegator, LocalDispatcher dispatcher, String partyId, GenericValue userLogin, String productStoreId) throws GenericEntityException, GenericServiceException { if (partyId == null && userLogin != null) { partyId = userLogin.getString("partyId"); } String autoSaveListId = null; GenericValue list = null; // TODO: add sorting, just in case there are multiple... if (partyId != null) { Map<String, Object> findMap = UtilMisc.<String, Object>toMap( "partyId", partyId, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME); List<GenericValue> existingLists = EntityQuery.use(delegator).from("ShoppingList").where(findMap).queryList(); Debug.logInfo( "Finding existing auto-save shopping list with: \nfindMap: " + findMap + "\nlists: " + existingLists, module); if (UtilValidate.isNotEmpty(existingLists)) { list = EntityUtil.getFirst(existingLists); autoSaveListId = list.getString("shoppingListId"); } } if (list == null && dispatcher != null) { Map<String, Object> listFields = UtilMisc.<String, Object>toMap( "userLogin", userLogin, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME); Map<String, Object> newListResult = dispatcher.runSync("createShoppingList", listFields); if (newListResult != null) { autoSaveListId = (String) newListResult.get("shoppingListId"); } } return autoSaveListId; }
public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) { GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); GenericValue authTrans = (GenericValue) context.get("authTrans"); Locale locale = (Locale) context.get("locale"); if (authTrans == null) { authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref); } NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoCapture"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId")); encoder.add("COMPLETETYPE", "NotComplete"); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("captureResult", false); result.put("captureRefNum", "N/A"); result.put("captureAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("captureCode", error.getKey()); result.put("captureMessage", error.getValue()); } else { result.put( "captureMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("captureResult", true); result.put("captureAmount", new BigDecimal(decoder.get("AMT"))); result.put("captureRefNum", decoder.get("TRANSACTIONID")); } // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what // should be checked for this type of transaction return result; }
private static boolean hasChildrenAttr( List<GenericValue> monitors, String parentAttr, String id) { if (id == null) return false; if (parentAttr == null) return true; for (GenericValue val : monitors) { if (!id.equals(val.getString("id"))) continue; if (parentAttr.equals(val.getString("parentAttrName"))) return true; } return false; }
public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) { Locale locale = (Locale) context.get("locale"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); } GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference); BigDecimal refundAmount = (BigDecimal) context.get("refundAmount"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "RefundTransaction"); encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum")); encoder.add("REFUNDTYPE", "Partial"); encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId")); encoder.add("AMT", refundAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId")); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("refundResult", false); result.put("refundRefNum", captureTrans.getString("referenceNum")); result.put("refundAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("refundCode", error.getKey()); result.put("refundMessage", error.getValue()); } else { result.put( "refundMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("refundResult", true); result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT"))); result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID")); } return result; }
public static void checkPathAlias( ServletRequest request, ServletResponse response, Delegator delegator, String pathInfo) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String webSiteId = WebSiteWorker.getWebSiteId(request); // check path alias GenericValue pathAlias = null; try { pathAlias = EntityQuery.use(delegator) .from("WebSitePathAlias") .where("webSiteId", webSiteId, "pathAlias", pathInfo) .cache() .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (pathAlias != null) { String alias = pathAlias.getString("aliasTo"); String contentId = pathAlias.getString("contentId"); if (contentId == null && UtilValidate.isNotEmpty(alias)) { if (!alias.startsWith("/")) { alias = "/" + alias; } RequestDispatcher rd = request.getRequestDispatcher(alias); try { rd.forward(request, response); return; } catch (ServletException e) { Debug.logWarning(e, module); } catch (IOException e) { Debug.logWarning(e, module); } } } else { // send 404 error if a URI is alias TO try { List<GenericValue> aliasTos = EntityQuery.use(delegator) .from("WebSitePathAlias") .where("webSiteId", webSiteId, "aliasTo", httpRequest.getRequestURI()) .queryList(); if (UtilValidate.isNotEmpty(aliasTos)) { httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found"); return; } } catch (GenericEntityException e) { Debug.logError(e, module); } catch (IOException e) { Debug.logError(e, module); } } }
public static Map<String, Object> doVoid(DispatchContext dctx, Map<String, Object> context) { GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); Locale locale = (Locale) context.get("locale"); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); } GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoVoid"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("releaseResult", false); result.put("releaseRefNum", authTrans.getString("referenceNum")); result.put("releaseAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("releaseCode", error.getKey()); result.put("releaseMessage", error.getValue()); } else { result.put( "releaseMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("releaseResult", true); // PayPal voids the entire order amount minus any captures, that's a little difficult to // figure out here // so until further testing proves we should do otherwise I'm just going to return requested // void amount result.put("releaseAmount", context.get("releaseAmount")); result.put("releaseRefNum", decoder.get("AUTHORIZATIONID")); } return result; }
/** Returns Map keyed on item sequence ID containing a list of survey response IDs */ public static Map<String, List<String>> getItemSurveyInfos(List<GenericValue> items) { Map<String, List<String>> surveyInfos = FastMap.newInstance(); if (UtilValidate.isNotEmpty(items)) { for (GenericValue item : items) { String listId = item.getString("shoppingListId"); String itemId = item.getString("shoppingListItemSeqId"); surveyInfos.put(listId + "." + itemId, getItemSurveyInfo(item)); } } return surveyInfos; }
public static String formatPartyNameObject(GenericValue partyValue, boolean lastNameFirst) { if (partyValue == null) { return ""; } StringBuilder result = new StringBuilder(); ModelEntity modelEntity = partyValue.getModelEntity(); if (modelEntity.isField("firstName") && modelEntity.isField("middleName") && modelEntity.isField("lastName")) { if (lastNameFirst) { if (UtilFormatOut.checkNull(partyValue.getString("lastName")) != null) { result.append(UtilFormatOut.checkNull(partyValue.getString("lastName"))); if (partyValue.getString("firstName") != null) { result.append(", "); } } result.append(UtilFormatOut.checkNull(partyValue.getString("firstName"))); } else { result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("firstName"), "", " ")); result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("middleName"), "", " ")); result.append(UtilFormatOut.checkNull(partyValue.getString("lastName"))); } } if (modelEntity.isField("groupName") && partyValue.get("groupName") != null) { result.append(partyValue.getString("groupName")); } return result.toString(); }
public static String getGroupName(String groupId) throws Exception { EntityCondition whereCondition = EntityCondition.makeCondition("groupId", EntityOperator.LIKE, groupId + "%"); List<GenericValue> list = getDelegator().findList("SvGroupValue", whereCondition, null, null, null, false); for (GenericValue val : list) { if ("_name".equals(val.getString("attrName"))) { return val.getString("attrValue"); } } return ""; }
public static String getPartyName(GenericValue partyObject, boolean lastNameFirst) { if (partyObject == null) { return ""; } if ("PartyGroup".equals(partyObject.getEntityName()) || "Person".equals(partyObject.getEntityName())) { return formatPartyNameObject(partyObject, lastNameFirst); } else { String partyId = null; try { partyId = partyObject.getString("partyId"); } catch (IllegalArgumentException e) { Debug.logError(e, "Party object does not contain a party ID", module); } if (partyId == null) { Debug.logWarning( "No party ID found; cannot get name based on entity: " + partyObject.getEntityName(), module); return ""; } else { return getPartyName(partyObject.getDelegator(), partyId, lastNameFirst); } } }
public static boolean isProductInCategory( Delegator delegator, String productId, String productCategoryId) throws GenericEntityException { if (productCategoryId == null) return false; if (UtilValidate.isEmpty(productId)) return false; List<GenericValue> productCategoryMembers = EntityUtil.filterByDate( delegator.findByAndCache( "ProductCategoryMember", UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId)), true); if (UtilValidate.isEmpty(productCategoryMembers)) { // before giving up see if this is a variant product, and if so look up the virtual product // and check it... GenericValue product = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", productId)); List<GenericValue> productAssocs = ProductWorker.getVariantVirtualAssocs(product); // this does take into account that a product could be a variant of multiple products, but // this shouldn't ever really happen... if (productAssocs != null) { for (GenericValue productAssoc : productAssocs) { if (isProductInCategory( delegator, productAssoc.getString("productId"), productCategoryId)) { return true; } } } return false; } else { return true; } }
/** Creates request fields for a customer, such as email and postal addresses. */ private static Map buildCustomerRequest(Delegator delegator, Map context) throws GenericEntityException { Map request = FastMap.newInstance(); GenericValue customer = (GenericValue) context.get("billToParty"); GenericValue address = (GenericValue) context.get("billingAddress"); GenericValue email = (GenericValue) context.get("billToEmail"); if (customer != null && "Person".equals(customer.getEntityName())) { request.put("x_first_name", customer.get("firstName")); request.put("x_last_name", customer.get("lastName")); } if (customer != null && "PartyGroup".equals(customer.getEntityName())) { request.put("x_company", customer.get("groupName")); } if (address != null) { request.put("x_address", address.get("address1")); request.put("x_city", address.get("city")); request.put("x_zip", address.get("postalCode")); GenericValue country = address.getRelatedOneCache("CountryGeo"); if (country != null) { request.put("x_country", country.get("geoCode")); if ("USA".equals(country.get("geoId"))) { request.put("x_state", address.get("stateProvinceGeoId")); } } } if (email != null && UtilValidate.isNotEmpty(email.getString("infoString"))) { request.put("x_email", email.get("infoString")); } return request; }
/** Checks if the given party with role is assigned to the user login. */ public static boolean isAssignedToUserLogin( String partyId, String roleTypeId, GenericValue userLogin) throws GenericEntityException { Delegator delegator = userLogin.getDelegator(); String roleTypeIdTo = getFirstValidTeamMemberRoleTypeId(userLogin.getString("partyId"), delegator); if (roleTypeIdTo == null) { return false; } List<GenericValue> activeRelationships = EntityUtil.filterByDate( delegator.findByAnd( "PartyRelationship", UtilMisc.toMap( "partyIdFrom", partyId, "roleTypeIdFrom", roleTypeId, "partyIdTo", userLogin.get("partyId"), "roleTypeIdTo", roleTypeIdTo, "partyRelationshipTypeId", "ASSIGNED_TO"))); return activeRelationships.size() > 0; }
public static boolean isBinComplete(Delegator delegator, String picklistBinId) throws GeneralException { // lookup the items in the bin List<GenericValue> items; try { items = delegator.findByAnd("PicklistItem", UtilMisc.toMap("picklistBinId", picklistBinId)); } catch (GenericEntityException e) { Debug.logError(e, module); throw e; } if (!UtilValidate.isEmpty(items)) { for (GenericValue v : items) { String itemStatus = v.getString("itemStatusId"); if (itemStatus != null) { if (!"PICKITEM_COMPLETED".equals(itemStatus)) { return false; } } } return true; } return false; }
@Override public boolean eval(Map<String, Object> context) { // if no user is logged in, treat as if the user does not have permission GenericValue userLogin = (GenericValue) context.get("userLogin"); if (userLogin != null) { String permission = permissionExdr.expandString(context); String action = actionExdr.expandString(context); Authorization authz = (Authorization) context.get("authz"); Security security = (Security) context.get("security"); if (UtilValidate.isNotEmpty(action)) { // Debug.logWarning("Deprecated method hasEntityPermission() was called; the action field // should no longer be used", module); // run hasEntityPermission if (security.hasEntityPermission(permission, action, userLogin)) { return true; } } else { // run hasPermission if (authz.hasPermission(userLogin.getString("userLoginId"), permission, context)) { return true; } } } return false; }
private static String parseStateProvinceGeoId( String payPalShipToState, String countryGeoId, Delegator delegator) { String lookupField = "geoName"; List<EntityCondition> conditionList = FastList.newInstance(); conditionList.add(EntityCondition.makeCondition("geoAssocTypeId", "REGIONS")); if ("USA".equals(countryGeoId) || "CAN".equals(countryGeoId)) { // PayPal returns two letter code for US and Canadian States/Provinces String geoTypeId = "USA".equals(countryGeoId) ? "STATE" : "PROVINCE"; conditionList.add(EntityCondition.makeCondition("geoTypeId", geoTypeId)); lookupField = "geoCode"; } conditionList.add(EntityCondition.makeCondition("geoIdFrom", countryGeoId)); conditionList.add(EntityCondition.makeCondition(lookupField, payPalShipToState)); EntityCondition cond = EntityCondition.makeCondition(conditionList); GenericValue geoAssocAndGeoTo = null; try { geoAssocAndGeoTo = EntityQuery.use(delegator).from("GeoAssocAndGeoTo").where(cond).cache().queryFirst(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (geoAssocAndGeoTo != null) { return geoAssocAndGeoTo.getString("geoId"); } return null; }
public static Map<String, Object> doAuthorization( DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); String orderId = (String) context.get("orderId"); BigDecimal processAmount = (BigDecimal) context.get("processAmount"); GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); Locale locale = (Locale) context.get("locale"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoAuthorization"); encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId")); encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("TRANSACTIONENTITY", "Order"); String currency = (String) context.get("currency"); if (currency == null) { currency = orh.getCurrency(); } encoder.add("CURRENCYCODE", currency); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("authResult", false); result.put("authRefNum", "N/A"); result.put("processAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("authCode", error.getKey()); result.put("authMessage", error.getValue()); } else { result.put( "authMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("authResult", true); result.put("processAmount", new BigDecimal(decoder.get("AMT"))); result.put("authRefNum", decoder.get("TRANSACTIONID")); } // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what // should be checked for this type of transaction return result; }
/** * Method to return the total amount of a payment which is applied to a payment * * @param payment GenericValue object of the Payment * @param actual false for currency of the payment, true for the actual currency * @return the applied total as BigDecimal in the currency of the payment */ public static BigDecimal getPaymentApplied(GenericValue payment, Boolean actual) { BigDecimal paymentApplied = BigDecimal.ZERO; List<GenericValue> paymentApplications = null; try { List<EntityExpr> cond = UtilMisc.toList( EntityCondition.makeCondition( "paymentId", EntityOperator.EQUALS, payment.getString("paymentId")), EntityCondition.makeCondition( "toPaymentId", EntityOperator.EQUALS, payment.getString("paymentId"))); EntityCondition partyCond = EntityCondition.makeCondition(cond, EntityOperator.OR); paymentApplications = payment .getDelegator() .findList( "PaymentApplication", partyCond, null, UtilMisc.toList("invoiceId", "billingAccountId"), null, false); if (UtilValidate.isNotEmpty(paymentApplications)) { for (GenericValue paymentApplication : paymentApplications) { BigDecimal amountApplied = paymentApplication.getBigDecimal("amountApplied"); // check currency invoice and if different convert amount applied for display if (actual.equals(Boolean.FALSE) && paymentApplication.get("invoiceId") != null && payment.get("actualCurrencyAmount") != null && payment.get("actualCurrencyUomId") != null) { GenericValue invoice = paymentApplication.getRelatedOne("Invoice"); if (payment .getString("actualCurrencyUomId") .equals(invoice.getString("currencyUomId"))) { amountApplied = amountApplied .multiply(payment.getBigDecimal("amount")) .divide(payment.getBigDecimal("actualCurrencyAmount"), new MathContext(100)); } } paymentApplied = paymentApplied.add(amountApplied).setScale(decimals, rounding); } } } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting entities", module); } return paymentApplied; }
/** * Check if the party has been deactivated. * * @param partyId * @param delegator * @return is active * @throws GenericEntityNotFoundException */ public static boolean isActive(String partyId, Delegator delegator) throws GenericEntityException { GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId)); if (party == null) { throw new GenericEntityNotFoundException("No Party found with ID: " + partyId); } return (!"PARTY_DISABLED".equals(party.getString("statusId"))); }
private boolean evalAuthzPermission( Authorization authz, GenericValue userLogin, Map<String, ? extends Object> context) { if (nameOrRole == null) { Debug.logWarning("Null permission name passed for evaluation", module); return false; } return authz.hasPermission(userLogin.getString("userLoginId"), nameOrRole, context); }
/** Creates records for survey responses on survey items */ public static int makeListItemSurveyResp( Delegator delegator, GenericValue item, List<String> surveyResps) throws GenericEntityException { if (UtilValidate.isNotEmpty(surveyResps)) { int count = 0; for (String responseId : surveyResps) { GenericValue listResp = delegator.makeValue("ShoppingListItemSurvey"); listResp.set("shoppingListId", item.getString("shoppingListId")); listResp.set("shoppingListItemSeqId", item.getString("shoppingListItemSeqId")); listResp.set("surveyResponseId", responseId); delegator.create(listResp); count++; } return count; } return -1; }