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 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); } } }
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 String makeProductUrl( HttpServletRequest request, String previousCategoryId, String productCategoryId, String productId) { Delegator delegator = (Delegator) request.getAttribute("delegator"); String url = null; try { GenericValue product = EntityQuery.use(delegator) .from("Product") .where("productId", productId) .cache() .queryOne(); ProductContentWrapper wrapper = new ProductContentWrapper(product, request); List<String> trail = CategoryWorker.getTrail(request); url = makeProductUrl( delegator, wrapper, trail, request.getContextPath(), previousCategoryId, productCategoryId, productId); } catch (GenericEntityException e) { Debug.logWarning(e, "Cannot create product's URL for: " + productId, module); return redirectUrl; } return url; }
/** * 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 String getPartyName(Delegator delegator, String partyId, boolean lastNameFirst) { GenericValue partyObject = null; try { partyObject = EntityQuery.use(delegator).from("PartyNameView").where("partyId", partyId).queryOne(); } catch (GenericEntityException e) { Debug.logError(e, "Error finding PartyNameView in getPartyName", module); } if (partyObject == null) { return partyId; } else { return formatPartyNameObject(partyObject, lastNameFirst); } }
public static void setRequestAttributes( ServletRequest request, Delegator delegator, ServletContext servletContext) { HttpServletRequest httpRequest = (HttpServletRequest) request; // check if multi tenant is enabled boolean useMultitenant = EntityUtil.isMultiTenantEnabled(); if (useMultitenant) { // get tenant delegator by domain name String serverName = request.getServerName(); try { // if tenant was specified, replace delegator with the new per-tenant delegator and set // tenantId to session attribute delegator = getDelegator(servletContext); // Use base delegator for fetching data from entity of entityGroup org.ofbiz.tenant Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName()); GenericValue tenantDomainName = EntityQuery.use(baseDelegator) .from("TenantDomainName") .where("domainName", serverName) .queryOne(); if (UtilValidate.isNotEmpty(tenantDomainName)) { String tenantId = tenantDomainName.getString("tenantId"); // make that tenant active, setup a new delegator and a new dispatcher String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId; httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName); // after this line the delegator is replaced with the new per-tenant delegator delegator = DelegatorFactory.getDelegator(tenantDelegatorName); servletContext.setAttribute("delegator", delegator); } } catch (GenericEntityException e) { Debug.logWarning(e, "Unable to get Tenant", module); } } // set the web context in the request for future use request.setAttribute("servletContext", httpRequest.getSession().getServletContext()); request.setAttribute("delegator", delegator); // set the webSiteId in the session if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))) { httpRequest .getSession() .setAttribute( "webSiteId", httpRequest.getSession().getServletContext().getAttribute("webSiteId")); } }
private static String getCountryGeoIdFromGeoCode(String geoCode, Delegator delegator) { String geoId = null; try { GenericValue countryGeo = EntityQuery.use(delegator) .from("Geo") .where("geoTypeId", "COUNTRY", "geoCode", geoCode) .cache() .queryFirst(); if (countryGeo != null) { geoId = countryGeo.getString("geoId"); } } catch (GenericEntityException e) { Debug.logError(e, module); } return geoId; }
/** * Fills the specialized shopping list with the current shopping cart if one exists (if not leaves * it alone) */ public static void fillAutoSaveList(ShoppingCart cart, LocalDispatcher dispatcher) throws GeneralException { if (cart != null && dispatcher != null) { GenericValue userLogin = ShoppingListEvents.getCartUserLogin(cart); Delegator delegator = cart.getDelegator(); String autoSaveListId = cart.getAutoSaveListId(); if (autoSaveListId == null) { autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId()); cart.setAutoSaveListId(autoSaveListId); } GenericValue shoppingList = EntityQuery.use(delegator) .from("ShoppingList") .where("shoppingListId", autoSaveListId) .queryOne(); Integer currentListSize = 0; if (UtilValidate.isNotEmpty(shoppingList)) { List<GenericValue> shoppingListItems = shoppingList.getRelated("ShoppingListItem", null, null, false); if (UtilValidate.isNotEmpty(shoppingListItems)) { currentListSize = shoppingListItems.size(); } } try { String[] itemsArray = makeCartItemsArray(cart); if (itemsArray != null && itemsArray.length != 0) { addBulkFromCart( delegator, dispatcher, cart, userLogin, autoSaveListId, null, itemsArray, false, false); } else if (itemsArray.length == 0 && currentListSize != 0) { clearListInfo(delegator, autoSaveListId); } } catch (IllegalArgumentException e) { throw new GeneralException(e.getMessage(), e); } } }
/** * Gets the cached value object for this merchant's keys * * @return Cached GenericValue object */ public GenericValue getGenericValue() { GenericValue value = null; try { value = EntityQuery.use(delegator) .from("ValueLinkKey") .where("merchantId", merchantId) .cache() .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (value == null) { throw new RuntimeException("No ValueLinkKey record found for Merchant ID : " + merchantId); } return value; }
private static GenericValue getPaymentMethodGatewayPayPal( DispatchContext dctx, Map<String, ? extends Object> context, String paymentServiceTypeEnumId) { Delegator delegator = dctx.getDelegator(); String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId"); GenericValue payPalGatewayConfig = null; if (paymentGatewayConfigId == null) { String productStoreId = null; GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); if (orderPaymentPreference != null) { OrderReadHelper orh = new OrderReadHelper(delegator, orderPaymentPreference.getString("orderId")); productStoreId = orh.getProductStoreId(); } else { ShoppingCart cart = (ShoppingCart) context.get("cart"); if (cart != null) { productStoreId = cart.getProductStoreId(); } } if (productStoreId != null) { GenericValue payPalPaymentSetting = ProductStoreWorker.getProductStorePaymentSetting( delegator, productStoreId, "EXT_PAYPAL", paymentServiceTypeEnumId, true); if (payPalPaymentSetting != null) { paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId"); } } } if (paymentGatewayConfigId != null) { try { payPalGatewayConfig = EntityQuery.use(delegator) .from("PaymentGatewayPayPal") .where("paymentGatewayConfigId", paymentGatewayConfigId) .cache() .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } } return payPalGatewayConfig; }
public static String makeCategoryUrl( HttpServletRequest request, String previousCategoryId, String productCategoryId, String productId, String viewSize, String viewIndex, String viewSort, String searchString) { Delegator delegator = (Delegator) request.getAttribute("delegator"); try { GenericValue productCategory = EntityQuery.use(delegator) .from("ProductCategory") .where("productCategoryId", productCategoryId) .cache() .queryOne(); CategoryContentWrapper wrapper = new CategoryContentWrapper(productCategory, request); List<String> trail = CategoryWorker.getTrail(request); return makeCategoryUrl( delegator, wrapper, trail, request.getContextPath(), previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString); } catch (GenericEntityException e) { Debug.logWarning(e, "Cannot create category's URL for: " + productCategoryId, module); return redirectUrl; } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Delegator delegator = (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator"); // Get ServletContext ServletContext servletContext = config.getServletContext(); ContextFilter.setCharacterEncoding(request); // Set request attribute and session UrlServletHelper.setRequestAttributes(request, delegator, servletContext); // set initial parameters String initDefaultLocalesString = config.getInitParameter("defaultLocaleString"); String initRedirectUrl = config.getInitParameter("redirectUrl"); defaultLocaleString = UtilValidate.isNotEmpty(initDefaultLocalesString) ? initDefaultLocalesString : ""; redirectUrl = UtilValidate.isNotEmpty(initRedirectUrl) ? initRedirectUrl : ""; String pathInfo = httpRequest.getServletPath(); if (UtilValidate.isNotEmpty(pathInfo)) { List<String> pathElements = StringUtil.split(pathInfo, "/"); String alternativeUrl = pathElements.get(0); String productId = null; String productCategoryId = null; String urlContentId = null; try { // look for productId if (alternativeUrl.endsWith("-p")) { List<EntityCondition> productContentConds = FastList.newInstance(); productContentConds.add( EntityCondition.makeCondition("productContentTypeId", "ALTERNATIVE_URL")); productContentConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productContentInfos = EntityQuery.use(delegator) .from("ProductContentAndInfo") .where(productContentConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productContentInfos)) { for (GenericValue productContentInfo : productContentInfos) { String contentId = (String) productContentInfo.get("contentId"); List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator) .from("ContentAssocDataResourceViewTo") .where( "contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productIdStr = null; productIdStr = alternativeUrl.replace(textData + "-", ""); productIdStr = productIdStr.replace("-p", ""); String checkProductId = (String) productContentInfo.get("productId"); if (productIdStr.equalsIgnoreCase(checkProductId)) { productId = checkProductId; break; } } } } } if (UtilValidate.isEmpty(productId)) { List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator) .from("ContentDataResourceView") .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productIdStr = null; productIdStr = alternativeUrl.replace(textData + "-", ""); productIdStr = productIdStr.replace("-p", ""); String checkProductId = (String) productContentInfo.get("productId"); if (productIdStr.equalsIgnoreCase(checkProductId)) { productId = checkProductId; break; } } } } } } } } } // look for productCategoryId if (alternativeUrl.endsWith("-c")) { List<EntityCondition> productCategoryContentConds = FastList.newInstance(); productCategoryContentConds.add( EntityCondition.makeCondition("prodCatContentTypeId", "ALTERNATIVE_URL")); productCategoryContentConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryContentInfos = EntityQuery.use(delegator) .from("ProductCategoryContentAndInfo") .where(productCategoryContentConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryContentInfos)) { for (GenericValue productCategoryContentInfo : productCategoryContentInfos) { String contentId = (String) productCategoryContentInfo.get("contentId"); List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator) .from("ContentAssocDataResourceViewTo") .where( "contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productCategoryStr = null; productCategoryStr = alternativeUrl.replace(textData + "-", ""); productCategoryStr = productCategoryStr.replace("-c", ""); String checkProductCategoryId = (String) productCategoryContentInfo.get("productCategoryId"); if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) { productCategoryId = checkProductCategoryId; break; } } } } } } if (UtilValidate.isEmpty(productCategoryId)) { List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator) .from("ContentDataResourceView") .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productCategoryStr = null; productCategoryStr = alternativeUrl.replace(textData + "-", ""); productCategoryStr = productCategoryStr.replace("-c", ""); String checkProductCategoryId = (String) productCategoryContentInfo.get("productCategoryId"); if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) { productCategoryId = checkProductCategoryId; break; } } } } } } } } } } catch (GenericEntityException e) { Debug.logWarning("Cannot look for product and product category", module); } // generate forward URL StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("/" + CONTROL_MOUNT_POINT); if (UtilValidate.isNotEmpty(productId)) { try { List<EntityCondition> conds = FastList.newInstance(); conds.add(EntityCondition.makeCondition("productId", productId)); conds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryMembers = EntityQuery.use(delegator) .select("productCategoryId") .from("ProductCategoryMember") .where(conds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryMembers)) { GenericValue productCategoryMember = EntityUtil.getFirst(productCategoryMembers); productCategoryId = productCategoryMember.getString("productCategoryId"); } } catch (GenericEntityException e) { Debug.logError(e, "Cannot find product category for product: " + productId, module); } urlBuilder.append("/" + PRODUCT_REQUEST); } else { urlBuilder.append("/" + CATEGORY_REQUEST); } // generate trail belong to a top category String topCategoryId = CategoryWorker.getCatalogTopCategory(httpRequest, null); List<GenericValue> trailCategories = CategoryWorker.getRelatedCategoriesRet( httpRequest, "trailCategories", topCategoryId, false, false, true); List<String> trailCategoryIds = EntityUtil.getFieldListFromEntityList(trailCategories, "productCategoryId", true); // look for productCategoryId from productId if (UtilValidate.isNotEmpty(productId)) { try { List<EntityCondition> rolllupConds = FastList.newInstance(); rolllupConds.add(EntityCondition.makeCondition("productId", productId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryMembers = EntityQuery.use(delegator) .from("ProductCategoryMember") .where(rolllupConds) .orderBy("-fromDate") .cache(true) .queryList(); for (GenericValue productCategoryMember : productCategoryMembers) { String trailCategoryId = productCategoryMember.getString("productCategoryId"); if (trailCategoryIds.contains(trailCategoryId)) { productCategoryId = trailCategoryId; break; } } } catch (GenericEntityException e) { Debug.logError(e, "Cannot generate trail from product category", module); } } // generate trail elements from productCategoryId if (UtilValidate.isNotEmpty(productCategoryId)) { List<String> trailElements = FastList.newInstance(); trailElements.add(productCategoryId); String parentProductCategoryId = productCategoryId; while (UtilValidate.isNotEmpty(parentProductCategoryId)) { // find product category rollup try { List<EntityCondition> rolllupConds = FastList.newInstance(); rolllupConds.add( EntityCondition.makeCondition("productCategoryId", parentProductCategoryId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryRollups = EntityQuery.use(delegator) .from("ProductCategoryRollup") .where(rolllupConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryRollups)) { // add only categories that belong to the top category to trail for (GenericValue productCategoryRollup : productCategoryRollups) { String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId"); parentProductCategoryId = trailCategoryId; if (trailCategoryIds.contains(trailCategoryId)) { trailElements.add(trailCategoryId); break; } } } else { parentProductCategoryId = null; } } catch (GenericEntityException e) { Debug.logError(e, "Cannot generate trail from product category", module); } } Collections.reverse(trailElements); List<String> trail = CategoryWorker.getTrail(httpRequest); if (trail == null) { trail = FastList.newInstance(); } // adjust trail String previousCategoryId = null; if (trail.size() > 0) { previousCategoryId = trail.get(trail.size() - 1); } trail = CategoryWorker.adjustTrail(trail, productCategoryId, previousCategoryId); if (trailElements.size() == 1) { CategoryWorker.setTrail(request, trailElements.get(0), null); } else if (trailElements.size() == 2) { CategoryWorker.setTrail(request, trailElements.get(1), trailElements.get(0)); } else if (trailElements.size() > 2) { if (trail.contains(trailElements.get(0))) { // first category is in the trail, so remove it everything after that and fill it in // with the list from the pathInfo int firstElementIndex = trail.indexOf(trailElements.get(0)); while (trail.size() > firstElementIndex) { trail.remove(firstElementIndex); } trail.addAll(trailElements); } else { // first category is NOT in the trail, so clear out the trail and use the trailElements // list trail.clear(); trail.addAll(trailElements); } CategoryWorker.setTrail(request, trail); } request.setAttribute("productCategoryId", productCategoryId); if (productId != null) { request.setAttribute("product_id", productId); request.setAttribute("productId", productId); } } // Set view query parameters UrlServletHelper.setViewQueryParameters(request, urlBuilder); if (UtilValidate.isNotEmpty(productId) || UtilValidate.isNotEmpty(productCategoryId) || UtilValidate.isNotEmpty(urlContentId)) { Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); ContextFilter.setAttributesFromRequestBody(request); RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString()); dispatch.forward(request, response); return; } // Check path alias UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo); } // we're done checking; continue on chain.doFilter(request, response); }
public static String timeSheetChecker(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Delegator delegator = (Delegator) session.getAttribute("delegator"); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); List<Map<String, Object>> noTimeEntryList = new LinkedList<Map<String, Object>>(); String partyId = userLogin.getString("partyId"); Timestamp now = UtilDateTime.nowTimestamp(); Timestamp weekStart = UtilDateTime.getWeekStart(now); if (UtilValidate.isEmpty(delegator)) { delegator = (Delegator) request.getAttribute("delegator"); } try { // should be scrum team or scrum master. EntityConditionList<EntityExpr> exprOrs = EntityCondition.makeCondition( UtilMisc.toList( EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_TEAM"), EntityCondition.makeCondition( "roleTypeId", EntityOperator.EQUALS, "SCRUM_MASTER")), EntityOperator.OR); EntityConditionList<EntityCondition> exprAnds = EntityCondition.makeCondition( UtilMisc.toList( exprOrs, EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)), EntityOperator.AND); List<GenericValue> partyRoleList = EntityQuery.use(delegator).from("PartyRole").where(exprAnds).queryList(); if (UtilValidate.isNotEmpty(partyRoleList)) { List<GenericValue> timesheetList = EntityQuery.use(delegator) .from("Timesheet") .where("partyId", partyId, "statusId", "TIMESHEET_IN_PROCESS") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(timesheetList)) { for (GenericValue timesheetMap : timesheetList) { String timesheetId = timesheetMap.getString("timesheetId"); Timestamp timesheetDate = timesheetMap.getTimestamp("fromDate"); // check monday - friday for (int i = 0; i < 5; i++) { Timestamp realTimeDate = UtilDateTime.addDaysToTimestamp(timesheetDate, i); Timestamp nowStartDate = UtilDateTime.getDayStart(now); // compare week and compare date if ((timesheetDate.compareTo(weekStart) <= 0) && (realTimeDate.compareTo(nowStartDate) < 0)) { // check time entry List<GenericValue> timeEntryList = timesheetMap.getRelated( "TimeEntry", UtilMisc.toMap( "partyId", partyId, "timesheetId", timesheetId, "fromDate", realTimeDate), null, false); // check EmplLeave List<GenericValue> emplLeaveList = EntityQuery.use(delegator) .from("EmplLeave") .where("partyId", partyId, "fromDate", realTimeDate) .cache(true) .queryList(); if (UtilValidate.isEmpty(timeEntryList) && UtilValidate.isEmpty(emplLeaveList)) { Map<String, Object> noEntryMap = new HashMap<String, Object>(); noEntryMap.put("timesheetId", timesheetId); noTimeEntryList.add(noEntryMap); break; } } } } } } } catch (GenericEntityException EntEx) { EntEx.printStackTrace(); Debug.logError(EntEx.getMessage(), module); } if (UtilValidate.isNotEmpty(noTimeEntryList)) { StringBuilder warningDataBuffer = new StringBuilder(); int size = noTimeEntryList.size(); for (Map<String, Object> dataMap : noTimeEntryList) { if (--size == 0) { warningDataBuffer.append(dataMap.get("timesheetId")); } else { warningDataBuffer.append(dataMap.get("timesheetId")).append(", "); } warningDataBuffer.append(dataMap.get("timesheetId")); } String warningData = warningDataBuffer.toString(); Debug.logInfo("The following time sheet no time entry: [" + warningData + "]", module); request.setAttribute( "_ERROR_MESSAGE_", UtilProperties.getMessage( "scrumUiLabels", "ScrumTimesheetWarningMessage", UtilMisc.toMap("warningMessage", warningData), UtilHttp.getLocale(request))); } return "success"; }
public static Map<String, Object> finAccountCapture( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue userLogin = (GenericValue) context.get("userLogin"); GenericValue authTrans = (GenericValue) context.get("authTrans"); BigDecimal amount = (BigDecimal) context.get("captureAmount"); String currency = (String) context.get("currency"); // get the authorization transaction if (authTrans == null) { authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); } if (authTrans == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotCapture", locale)); } // get the auth record String finAccountAuthId = authTrans.getString("referenceNum"); GenericValue finAccountAuth; try { finAccountAuth = EntityQuery.use(delegator) .from("FinAccountAuth") .where("finAccountAuthId", finAccountAuthId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } Debug.logInfo( "Financial account capture [" + finAccountAuth.get("finAccountId") + "] for the amount of $" + amount + " Tx #" + finAccountAuth.get("finAccountAuthId"), module); // get the financial account GenericValue finAccount; try { finAccount = finAccountAuth.getRelatedOne("FinAccount", false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // make sure authorization has not expired Timestamp authExpiration = finAccountAuth.getTimestamp("thruDate"); if ((authExpiration != null) && (authExpiration.before(UtilDateTime.nowTimestamp()))) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountAuthorizationExpired", UtilMisc.toMap( "paymentGatewayResponseId", authTrans.getString("paymentGatewayResponseId"), "authExpiration", authExpiration), locale)); } // make sure the fin account itself has not expired if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale)); } String finAccountId = finAccount.getString("finAccountId"); // need the product store ID & party ID String orderId = orderPaymentPreference.getString("orderId"); String productStoreId = null; String partyId = null; if (orderId != null) { OrderReadHelper orh = new OrderReadHelper(delegator, orderId); productStoreId = orh.getProductStoreId(); GenericValue billToParty = orh.getBillToParty(); if (billToParty != null) { partyId = billToParty.getString("partyId"); } } // BIG NOTE: make sure the expireFinAccountAuth and finAccountWithdraw services are done in the // SAME TRANSACTION // (i.e. no require-new-transaction in either of them AND no running async) // cancel the authorization before doing the withdraw to avoid problems with way negative // available amount on account; should happen in same transaction to avoid conflict problems Map<String, Object> releaseResult; try { releaseResult = dispatcher.runSync( "expireFinAccountAuth", UtilMisc.<String, Object>toMap( "userLogin", userLogin, "finAccountAuthId", finAccountAuthId)); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(releaseResult)) { return releaseResult; } // build the withdraw context Map<String, Object> withdrawCtx = new HashMap<String, Object>(); withdrawCtx.put("finAccountId", finAccountId); withdrawCtx.put("productStoreId", productStoreId); withdrawCtx.put("currency", currency); withdrawCtx.put("partyId", partyId); withdrawCtx.put("orderId", orderId); withdrawCtx.put("amount", amount); withdrawCtx.put("reasonEnumId", "FATR_PURCHASE"); withdrawCtx.put("requireBalance", Boolean.FALSE); // for captures; if auth passed, allow withdrawCtx.put("userLogin", userLogin); // call the withdraw service Map<String, Object> withdrawResp; try { withdrawResp = dispatcher.runSync("finAccountWithdraw", withdrawCtx); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(withdrawResp)) { return withdrawResp; } // create the capture response Map<String, Object> result = ServiceUtil.returnSuccess(); Boolean processResult = (Boolean) withdrawResp.get("processResult"); BigDecimal withdrawAmount = (BigDecimal) withdrawResp.get("amount"); String referenceNum = (String) withdrawResp.get("referenceNum"); result.put("captureResult", processResult); result.put("captureRefNum", referenceNum); result.put("captureCode", "C"); result.put("captureFlag", "1"); result.put("captureAmount", withdrawAmount); return result; }
/** Restores the specialized (auto-save) shopping list back into the shopping cart */ public static String restoreAutoSaveList( HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue productStore = ProductStoreWorker.getProductStore(request); if (!ProductStoreWorker.autoSaveCart(productStore)) { // if auto-save is disabled just return here return "success"; } HttpSession session = request.getSession(); ShoppingCart cart = ShoppingCartEvents.getCartObject(request); // safety check for missing required parameter. if (cart.getWebSiteId() == null) { cart.setWebSiteId(WebSiteWorker.getWebSiteId(request)); } // locate the user's identity GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); if (userLogin == null) { userLogin = (GenericValue) session.getAttribute("autoUserLogin"); } // find the list ID String autoSaveListId = cart.getAutoSaveListId(); if (autoSaveListId == null) { try { autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId()); } catch (GeneralException e) { Debug.logError(e, module); } cart.setAutoSaveListId(autoSaveListId); } else if (userLogin != null) { String existingAutoSaveListId = null; try { existingAutoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId()); } catch (GeneralException e) { Debug.logError(e, module); } if (existingAutoSaveListId != null) { if (!existingAutoSaveListId.equals(autoSaveListId)) { // Replace with existing shopping list cart.setAutoSaveListId(existingAutoSaveListId); autoSaveListId = existingAutoSaveListId; cart.setLastListRestore(null); } else { // CASE: User first login and logout and then re-login again. This condition does not // require a restore at all // because at this point items in the cart and the items in the shopping list are same so // just return. return "success"; } } } // check to see if we are okay to load this list java.sql.Timestamp lastLoad = cart.getLastListRestore(); boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false); if (!okayToLoad && lastLoad != null) { GenericValue shoppingList = null; try { shoppingList = EntityQuery.use(delegator) .from("ShoppingList") .where("shoppingListId", autoSaveListId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (shoppingList != null) { java.sql.Timestamp lastModified = shoppingList.getTimestamp("lastAdminModified"); if (lastModified != null) { if (lastModified.after(lastLoad)) { okayToLoad = true; } if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) { okayToLoad = true; } } } } // load (restore) the list of we have determined it is okay to load if (okayToLoad) { String prodCatalogId = CatalogWorker.getCurrentCatalogId(request); try { addListToCart( delegator, dispatcher, cart, prodCatalogId, autoSaveListId, false, false, userLogin != null ? true : false); cart.setLastListRestore(UtilDateTime.nowTimestamp()); } catch (IllegalArgumentException e) { Debug.logError(e, module); } } return "success"; }
public static String addListToCart( Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart, String prodCatalogId, String shoppingListId, boolean includeChild, boolean setAsListItem, boolean append) throws java.lang.IllegalArgumentException { String errMsg = null; // no list; no add if (shoppingListId == null) { errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.choose_shopping_list", cart.getLocale()); throw new IllegalArgumentException(errMsg); } // get the shopping list GenericValue shoppingList = null; List<GenericValue> shoppingListItems = null; try { shoppingList = EntityQuery.use(delegator) .from("ShoppingList") .where("shoppingListId", shoppingListId) .queryOne(); if (shoppingList == null) { errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale()); throw new IllegalArgumentException(errMsg); } shoppingListItems = shoppingList.getRelated("ShoppingListItem", null, null, false); if (shoppingListItems == null) { shoppingListItems = FastList.newInstance(); } // include all items of child lists if flagged to do so if (includeChild) { List<GenericValue> childShoppingLists = shoppingList.getRelated("ChildShoppingList", null, null, false); for (GenericValue v : childShoppingLists) { List<GenericValue> items = v.getRelated("ShoppingListItem", null, null, false); shoppingListItems.addAll(items); } } } catch (GenericEntityException e) { Debug.logError(e, "Problems getting ShoppingList and ShoppingListItem records", module); errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.error_getting_shopping_list_and_items", cart.getLocale()); throw new IllegalArgumentException(errMsg); } // no items; not an error; just mention that nothing was added if (UtilValidate.isEmpty(shoppingListItems)) { errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.no_items_added", cart.getLocale()); return errMsg; } // check if we are to clear the cart first if (!append) { cart.clear(); // Prevent the system from creating a new shopping list every time the cart is restored for // anonymous user. cart.setAutoSaveListId(shoppingListId); } // get the survey info for all the items Map<String, List<String>> shoppingListSurveyInfo = getItemSurveyInfos(shoppingListItems); // add the items StringBuilder eventMessage = new StringBuilder(); for (GenericValue shoppingListItem : shoppingListItems) { String productId = shoppingListItem.getString("productId"); BigDecimal quantity = shoppingListItem.getBigDecimal("quantity"); Timestamp reservStart = shoppingListItem.getTimestamp("reservStart"); BigDecimal reservLength = shoppingListItem.getBigDecimal("reservLength"); BigDecimal reservPersons = shoppingListItem.getBigDecimal("reservPersons"); // String accommodationMapId = shoppingListItem.getString("accommodationMapId"); // String accommodationSpotId = shoppingListItem.getString("accommodationSpotId"); String configId = shoppingListItem.getString("configId"); try { String listId = shoppingListItem.getString("shoppingListId"); String itemId = shoppingListItem.getString("shoppingListItemSeqId"); Map<String, Object> attributes = FastMap.newInstance(); // list items are noted in the shopping cart if (setAsListItem) { attributes.put("shoppingListId", listId); attributes.put("shoppingListItemSeqId", itemId); } // check if we have existing survey responses to append if (shoppingListSurveyInfo.containsKey(listId + "." + itemId) && UtilValidate.isNotEmpty(shoppingListSurveyInfo.get(listId + "." + itemId))) { attributes.put("surveyResponses", shoppingListSurveyInfo.get(listId + "." + itemId)); } ProductConfigWrapper configWrapper = null; if (UtilValidate.isNotEmpty(configId)) { configWrapper = ProductConfigWorker.loadProductConfigWrapper( delegator, dispatcher, configId, productId, cart.getProductStoreId(), prodCatalogId, cart.getWebSiteId(), cart.getCurrency(), cart.getLocale(), cart.getAutoUserLogin()); } // TODO: add code to check for survey response requirement // i cannot get the addOrDecrease function to accept a null reservStart field: i get a null // pointer exception a null constant works.... if (reservStart == null) { cart.addOrIncreaseItem( productId, null, quantity, null, null, null, null, null, null, attributes, prodCatalogId, configWrapper, null, null, null, dispatcher); } else { cart.addOrIncreaseItem( productId, null, quantity, reservStart, reservLength, reservPersons, null, null, null, null, null, attributes, prodCatalogId, configWrapper, null, null, null, dispatcher); } Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId); errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.added_product_to_cart", messageMap, cart.getLocale()); eventMessage.append(errMsg).append("\n"); } catch (CartItemModifyException e) { Debug.logWarning( e, UtilProperties.getMessage( resource_error, "OrderProblemsAddingItemFromListToCart", cart.getLocale())); Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId); errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale()); eventMessage.append(errMsg).append("\n"); } catch (ItemNotFoundException e) { Debug.logWarning( e, UtilProperties.getMessage(resource_error, "OrderProductNotFound", cart.getLocale())); Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId); errMsg = UtilProperties.getMessage( resource_error, "shoppinglistevents.problem_adding_product_to_cart", messageMap, cart.getLocale()); eventMessage.append(errMsg).append("\n"); } } if (eventMessage.length() > 0) { return eventMessage.toString(); } // all done return ""; // no message to return; will simply reply as success }
// base payment integration services public static Map<String, Object> finAccountPreAuth( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); String finAccountCode = (String) context.get("finAccountCode"); String finAccountPin = (String) context.get("finAccountPin"); String finAccountId = (String) context.get("finAccountId"); String orderId = (String) context.get("orderId"); BigDecimal amount = (BigDecimal) context.get("processAmount"); // check for an existing auth trans and cancel it GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref); if (authTrans != null) { Map<String, Object> input = UtilMisc.toMap("userLogin", userLogin, "finAccountAuthId", authTrans.get("referenceNum")); try { dispatcher.runSync("expireFinAccountAuth", input); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } if (finAccountId == null && paymentPref != null) { finAccountId = paymentPref.getString("finAccountId"); } // obtain the order information OrderReadHelper orh = new OrderReadHelper(delegator, orderId); // NOTE DEJ20070808: this means that we want store related settings for where the item is being // purchased, // NOT where the account was setup; should this be changed to use settings from the store where // the account was setup? String productStoreId = orh.getProductStoreId(); // TODO, NOTE DEJ20070808: why is this setup this way anyway? for the allowAuthToNegative // wouldn't that be better setup // on the FinAccount and not on the ProductStoreFinActSetting? maybe an override on the // FinAccount would be good... // get the financial account GenericValue finAccount; if (finAccountId != null) { try { finAccount = EntityQuery.use(delegator) .from("FinAccount") .where("finAccountId", finAccountId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } else { if (finAccountCode != null) { try { finAccount = FinAccountHelper.getFinAccountFromCode(finAccountCode, delegator); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountCannotLocateItFromAccountCode", locale)); } } else { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountIdAndFinAccountCodeAreNull", locale)); } } if (finAccount == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "AccountingFinAccountIdInvalid", locale)); } String finAccountTypeId = finAccount.getString("finAccountTypeId"); finAccountId = finAccount.getString("finAccountId"); String statusId = finAccount.getString("statusId"); try { // fin the store requires a pin number; validate the PIN with the code Map<String, Object> findProductStoreFinActSettingMap = UtilMisc.<String, Object>toMap( "productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId); GenericValue finAccountSettings = EntityQuery.use(delegator) .from("ProductStoreFinActSetting") .where(findProductStoreFinActSettingMap) .cache() .queryOne(); if (finAccountSettings == null) { Debug.logWarning( "In finAccountPreAuth could not find ProductStoreFinActSetting record, values searched by: " + findProductStoreFinActSettingMap, module); } if (Debug.verboseOn()) Debug.logVerbose("In finAccountPreAuth finAccountSettings=" + finAccountSettings, module); BigDecimal minBalance = FinAccountHelper.ZERO; String allowAuthToNegative = "N"; if (finAccountSettings != null) { allowAuthToNegative = finAccountSettings.getString("allowAuthToNegative"); minBalance = finAccountSettings.getBigDecimal("minBalance"); if (minBalance == null) { minBalance = FinAccountHelper.ZERO; } // validate the PIN if the store requires it if ("Y".equals(finAccountSettings.getString("requirePinCode"))) { if (!FinAccountHelper.validatePin(delegator, finAccountCode, finAccountPin)) { Map<String, Object> result = ServiceUtil.returnSuccess(); result.put( "authMessage", UtilProperties.getMessage( resourceError, "AccountingFinAccountPinCodeCombinatorNotFound", locale)); result.put("authResult", Boolean.FALSE); result.put("processAmount", amount); result.put("authFlag", "0"); result.put("authCode", "A"); result.put("authRefNum", "0"); Debug.logWarning("Unable to auth FinAccount: " + result, module); return result; } } } // check for expiration date if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) { Map<String, Object> result = ServiceUtil.returnSuccess(); result.put( "authMessage", UtilProperties.getMessage( resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale)); result.put("authResult", Boolean.FALSE); result.put("processAmount", amount); result.put("authFlag", "0"); result.put("authCode", "A"); result.put("authRefNum", "0"); Debug.logWarning("Unable to auth FinAccount: " + result, module); return result; } // check for account being in bad standing somehow if ("FNACT_NEGPENDREPL".equals(statusId) || "FNACT_MANFROZEN".equals(statusId) || "FNACT_CANCELLED".equals(statusId)) { // refresh the finaccount finAccount.refresh(); statusId = finAccount.getString("statusId"); if ("FNACT_NEGPENDREPL".equals(statusId) || "FNACT_MANFROZEN".equals(statusId) || "FNACT_CANCELLED".equals(statusId)) { Map<String, Object> result = ServiceUtil.returnSuccess(); if ("FNACT_NEGPENDREPL".equals(statusId)) { result.put( "authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountNegative", locale)); } else if ("FNACT_MANFROZEN".equals(statusId)) { result.put( "authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountFrozen", locale)); } else if ("FNACT_CANCELLED".equals(statusId)) { result.put( "authMessage", UtilProperties.getMessage(resourceError, "AccountingFinAccountCancelled", locale)); } result.put("authResult", Boolean.FALSE); result.put("processAmount", amount); result.put("authFlag", "0"); result.put("authCode", "A"); result.put("authRefNum", "0"); Debug.logWarning("Unable to auth FinAccount: " + result, module); return result; } } // check the amount to authorize against the available balance of fin account, which includes // active authorizations as well as transactions BigDecimal availableBalance = finAccount.getBigDecimal("availableBalance"); if (availableBalance == null) { availableBalance = FinAccountHelper.ZERO; } else { BigDecimal availableBalanceOriginal = availableBalance; availableBalance = availableBalance.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding); if (availableBalance.compareTo(availableBalanceOriginal) != 0) { Debug.logWarning( "In finAccountPreAuth for finAccountId [" + finAccountId + "] availableBalance [" + availableBalanceOriginal + "] was different after rounding [" + availableBalance + "]; it should never have made it into the database this way, so check whatever put it there.", module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); String authMessage = null; Boolean processResult; String refNum; // make sure to round and scale it to the same as availableBalance amount = amount.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding); Debug.logInfo( "Allow auth to negative: " + allowAuthToNegative + " :: available: " + availableBalance + " comp: " + minBalance + " = " + availableBalance.compareTo(minBalance) + " :: req: " + amount, module); // check the available balance to see if we can auth this tx if (("Y".equals(allowAuthToNegative) && availableBalance.compareTo(minBalance) > -1) || (availableBalance.compareTo(amount) > -1)) { Timestamp thruDate; if (finAccountSettings != null && finAccountSettings.getLong("authValidDays") != null) { thruDate = UtilDateTime.getDayEnd( UtilDateTime.nowTimestamp(), finAccountSettings.getLong("authValidDays")); } else { thruDate = UtilDateTime.getDayEnd( UtilDateTime.nowTimestamp(), Long.valueOf(30)); // default 30 days for an auth } Map<String, Object> tmpResult = dispatcher.runSync( "createFinAccountAuth", UtilMisc.<String, Object>toMap( "finAccountId", finAccountId, "amount", amount, "thruDate", thruDate, "userLogin", userLogin)); if (ServiceUtil.isError(tmpResult)) { return tmpResult; } refNum = (String) tmpResult.get("finAccountAuthId"); processResult = Boolean.TRUE; // refresh the account finAccount.refresh(); } else { Debug.logWarning( "Attempted to authorize [" + amount + "] against a balance of only [" + availableBalance + "] for finAccountId [" + finAccountId + "]", module); refNum = "0"; // a refNum is always required from authorization authMessage = "Insufficient funds"; processResult = Boolean.FALSE; } result.put("processAmount", amount); result.put("authMessage", authMessage); result.put("authResult", processResult); result.put("processAmount", amount); result.put("authFlag", "1"); result.put("authCode", "A"); result.put("authRefNum", refNum); Debug.logInfo("FinAccont Auth: " + result, module); return result; } catch (GenericEntityException ex) { Debug.logError(ex, "Cannot authorize financial account", module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountCannotBeAuthorized", UtilMisc.toMap("errorString", ex.getMessage()), locale)); } catch (GenericServiceException ex) { Debug.logError(ex, "Cannot authorize financial account", module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountCannotBeAuthorized", UtilMisc.toMap("errorString", ex.getMessage()), locale)); } }
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 = FastMap.newInstance(); 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"); inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us 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 = FastMap.newInstance(); 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, BigDecimal.ROUND_HALF_UP); cart.addPaymentAmount(paymentMethodId, maxAmount, true); return ServiceUtil.returnSuccess(); }
public static Map<String, Object> payPalCheckoutUpdate( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); HttpServletRequest request = (HttpServletRequest) context.get("request"); HttpServletResponse response = (HttpServletResponse) context.get("response"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); String token = (String) paramMap.get("TOKEN"); WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token)); ShoppingCart cart = null; if (weakCart != null) { cart = weakCart.get(); } if (cart == null) { Debug.logError("Could locate the ShoppingCart for token " + token, module); return ServiceUtil.returnSuccess(); } // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll // create one and // then delete once we're done, now is not the time to worry about updating everything String contactMechId = null; Map<String, Object> inMap = FastMap.newInstance(); inMap.put("address1", paramMap.get("SHIPTOSTREET")); inMap.put("address2", paramMap.get("SHIPTOSTREET2")); inMap.put("city", paramMap.get("SHIPTOCITY")); String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY"); String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator); if (countryGeoId == null) { return ServiceUtil.returnSuccess(); } inMap.put("countryGeoId", countryGeoId); inMap.put( "stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator)); inMap.put("postalCode", paramMap.get("SHIPTOZIP")); try { GenericValue userLogin = EntityQuery.use(delegator) .from("UserLogin") .where("userLoginId", "system") .cache() .queryOne(); inMap.put("userLogin", userLogin); } catch (GenericEntityException e) { Debug.logError(e, module); } boolean beganTransaction = false; Transaction parentTransaction = null; try { parentTransaction = TransactionUtil.suspend(); beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e1) { Debug.logError(e1, module); } try { Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap); contactMechId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnSuccess(); } try { TransactionUtil.commit(beganTransaction); if (parentTransaction != null) TransactionUtil.resume(parentTransaction); } catch (GenericTransactionException e) { Debug.logError(e, module); } // clone the cart so we can modify it temporarily CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart); String oldShipAddress = cart.getShippingContactMechId(); coh.setCheckOutShippingAddress(contactMechId); ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0); int line = 0; NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "CallbackResponse"); for (GenericValue shipMethod : estWrapper.getShippingMethods()) { BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod); // Check that we have a valid estimate (allowing zero value estimates for now) if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) { continue; } cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId")); cart.setAllCarrierPartyId(shipMethod.getString("partyId")); try { coh.calcAndAddTax(); } catch (GeneralException e) { Debug.logError(e, module); continue; } String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description"); encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel); encoder.add( "L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); // Just make this first one default for now encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false"); encoder.add( "L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); line++; } String responseMsg = null; try { responseMsg = encoder.encode(); } catch (PayPalException e) { Debug.logError(e, module); } if (responseMsg != null) { try { response.setContentLength(responseMsg.getBytes("UTF-8").length); } catch (UnsupportedEncodingException e) { Debug.logError(e, module); } try { Writer writer = response.getWriter(); writer.write(responseMsg); writer.close(); } catch (IOException e) { Debug.logError(e, module); } } // Remove the temporary ship address try { GenericValue postalAddress = EntityQuery.use(delegator) .from("PostalAddress") .where("contactMechId", contactMechId) .queryOne(); postalAddress.remove(); GenericValue contactMech = EntityQuery.use(delegator) .from("ContactMech") .where("contactMechId", contactMechId) .queryOne(); contactMech.remove(); } catch (GenericEntityException e) { Debug.logError(e, module); } coh.setCheckOutShippingAddress(oldShipAddress); return ServiceUtil.returnSuccess(); }
// base account transaction services public static Map<String, Object> finAccountWithdraw( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String productStoreId = (String) context.get("productStoreId"); String finAccountId = (String) context.get("finAccountId"); String orderItemSeqId = (String) context.get("orderItemSeqId"); String reasonEnumId = (String) context.get("reasonEnumId"); String orderId = (String) context.get("orderId"); Boolean requireBalance = (Boolean) context.get("requireBalance"); BigDecimal amount = (BigDecimal) context.get("amount"); if (requireBalance == null) requireBalance = Boolean.TRUE; final String WITHDRAWAL = "WITHDRAWAL"; 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.properties", "currency.uom.id.default", "USD", delegator); } // validate the amount if (amount.compareTo(BigDecimal.ZERO) < 0) { return ServiceUtil.returnError( UtilProperties.getMessage(resourceError, "AccountingFinAccountMustBePositive", locale)); } GenericValue finAccount; try { finAccount = EntityQuery.use(delegator) .from("FinAccount") .where("finAccountId", finAccountId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // verify we have a financial account if (finAccount == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", ""), locale)); } // make sure the fin account itself has not expired if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale)); } // check the actual balance (excluding authorized amounts) and create the transaction if it is // sufficient BigDecimal previousBalance = finAccount.getBigDecimal("actualBalance"); if (previousBalance == null) { previousBalance = FinAccountHelper.ZERO; } BigDecimal balance; String refNum; Boolean procResult; if (requireBalance && previousBalance.compareTo(amount) < 0) { procResult = Boolean.FALSE; balance = previousBalance; refNum = "N/A"; } else { try { refNum = FinAccountPaymentServices.createFinAcctPaymentTransaction( delegator, dispatcher, userLogin, amount, productStoreId, partyId, orderId, orderItemSeqId, currencyUom, WITHDRAWAL, finAccountId, reasonEnumId); finAccount.refresh(); balance = finAccount.getBigDecimal("actualBalance"); procResult = Boolean.TRUE; } catch (GeneralException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } // make sure balance is not null if (balance == null) { balance = FinAccountHelper.ZERO; } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("previousBalance", previousBalance); result.put("balance", balance); result.put("amount", amount); result.put("processResult", procResult); result.put("referenceNum", refNum); return result; }
// base deposit service public static Map<String, Object> finAccountDeposit( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String productStoreId = (String) context.get("productStoreId"); String finAccountId = (String) context.get("finAccountId"); String orderItemSeqId = (String) context.get("orderItemSeqId"); String reasonEnumId = (String) context.get("reasonEnumId"); String orderId = (String) context.get("orderId"); Boolean isRefund = (Boolean) context.get("isRefund"); BigDecimal amount = (BigDecimal) context.get("amount"); final String DEPOSIT = isRefund == null || !isRefund ? "DEPOSIT" : "ADJUSTMENT"; 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.properties", "currency.uom.id.default", "USD", delegator); } GenericValue finAccount; try { finAccount = EntityQuery.use(delegator) .from("FinAccount") .where("finAccountId", finAccountId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", finAccountId), locale)); } // verify we have a financial account if (finAccount == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", ""), locale)); } // make sure the fin account itself has not expired if ((finAccount.getTimestamp("thruDate") != null) && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountExpired", UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")), locale)); } Debug.logInfo("Deposit into financial account #" + finAccountId + " [" + amount + "]", module); // get the previous balance BigDecimal previousBalance = finAccount.getBigDecimal("actualBalance"); if (previousBalance == null) { previousBalance = FinAccountHelper.ZERO; } // create the transaction BigDecimal actualBalance; String refNum; try { refNum = FinAccountPaymentServices.createFinAcctPaymentTransaction( delegator, dispatcher, userLogin, amount, productStoreId, partyId, orderId, orderItemSeqId, currencyUom, DEPOSIT, finAccountId, reasonEnumId); finAccount.refresh(); actualBalance = finAccount.getBigDecimal("actualBalance"); } catch (GeneralException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // make sure balance is not null if (actualBalance == null) { actualBalance = FinAccountHelper.ZERO; } else { if (actualBalance.compareTo(BigDecimal.ZERO) < 0) { // balance went below zero, set negative pending replenishment status so that no more auths // or captures will go through until it is replenished try { Map<String, Object> rollbackCtx = UtilMisc.toMap( "userLogin", userLogin, "finAccountId", finAccountId, "statusId", "FNACT_NEGPENDREPL"); dispatcher.addRollbackService("updateFinAccount", rollbackCtx, true); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("previousBalance", previousBalance); result.put("balance", actualBalance); result.put("amount", amount); result.put("processResult", Boolean.TRUE); result.put("referenceNum", refNum); return result; }
// auto-replenish service (deposit) public static Map<String, Object> finAccountReplenish( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String productStoreId = (String) context.get("productStoreId"); String finAccountId = (String) context.get("finAccountId"); // lookup the FinAccount GenericValue finAccount; try { finAccount = EntityQuery.use(delegator) .from("FinAccount") .where("finAccountId", finAccountId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (finAccount == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNotFound", UtilMisc.toMap("finAccountId", finAccountId), locale)); } String currency = finAccount.getString("currencyUomId"); String statusId = finAccount.getString("statusId"); // look up the type -- determine auto-replenish is active GenericValue finAccountType; try { finAccountType = finAccount.getRelatedOne("FinAccountType", false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } String replenishEnumId = finAccountType.getString("replenishEnumId"); if (!"FARP_AUTOMATIC".equals(replenishEnumId)) { // type does not support auto-replenish return ServiceUtil.returnSuccess(); } // attempt to lookup the product store from a previous deposit if (productStoreId == null) { productStoreId = getLastProductStoreId(delegator, finAccountId); if (productStoreId == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountCannotBeReplenish", locale)); } } // get the product store settings GenericValue finAccountSettings; Map<String, Object> psfasFindMap = UtilMisc.<String, Object>toMap( "productStoreId", productStoreId, "finAccountTypeId", finAccount.getString("finAccountTypeId")); try { finAccountSettings = EntityQuery.use(delegator) .from("ProductStoreFinActSetting") .where(psfasFindMap) .cache() .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (finAccountSettings == null) { Debug.logWarning( "finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because no ProductStoreFinActSetting record found for: " + psfasFindMap, module); // no settings; don't replenish return ServiceUtil.returnSuccess(); } BigDecimal replenishThreshold = finAccountSettings.getBigDecimal("replenishThreshold"); if (replenishThreshold == null) { Debug.logWarning( "finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because ProductStoreFinActSetting.replenishThreshold field was null for: " + psfasFindMap, module); return ServiceUtil.returnSuccess(); } BigDecimal replenishLevel = finAccount.getBigDecimal("replenishLevel"); if (replenishLevel == null || replenishLevel.compareTo(BigDecimal.ZERO) == 0) { Debug.logWarning( "finAccountReplenish Warning: not replenishing FinAccount [" + finAccountId + "] because FinAccount.replenishLevel field was null or 0", module); // no replenish level set; this account goes not support auto-replenish return ServiceUtil.returnSuccess(); } // get the current balance BigDecimal balance = finAccount.getBigDecimal("actualBalance"); // see if we are within the threshold for replenishment if (balance.compareTo(replenishThreshold) > -1) { Debug.logInfo( "finAccountReplenish Info: Not replenishing FinAccount [" + finAccountId + "] because balance [" + balance + "] is greater than the replenishThreshold [" + replenishThreshold + "]", module); // not ready return ServiceUtil.returnSuccess(); } // configure rollback service to set status to Negative Pending Replenishment if ("FNACT_NEGPENDREPL".equals(statusId)) { try { Map<String, Object> rollbackCtx = UtilMisc.toMap( "userLogin", userLogin, "finAccountId", finAccountId, "statusId", "FNACT_NEGPENDREPL"); dispatcher.addRollbackService("updateFinAccount", rollbackCtx, true); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } String replenishMethod = finAccountSettings.getString("replenishMethodEnumId"); BigDecimal depositAmount; if (replenishMethod == null || "FARP_TOP_OFF".equals(replenishMethod)) { // the deposit is level - balance (500 - (-10) = 510 || 500 - (10) = 490) depositAmount = replenishLevel.subtract(balance); } else if ("FARP_REPLENISH_LEVEL".equals(replenishMethod)) { // the deposit is replenish-level itself depositAmount = replenishLevel; } else { return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountUnknownReplenishMethod", locale)); } // get the owner party String ownerPartyId = finAccount.getString("ownerPartyId"); if (ownerPartyId == null) { // no owner cannot replenish; (not fatal, just not supported by this account) Debug.logWarning( "finAccountReplenish Warning: No owner attached to financial account [" + finAccountId + "] cannot auto-replenish", module); return ServiceUtil.returnSuccess(); } // get the payment method to use to replenish String paymentMethodId = finAccount.getString("replenishPaymentId"); if (paymentMethodId == null) { Debug.logWarning( "finAccountReplenish Warning: No payment method (replenishPaymentId) attached to financial account [" + finAccountId + "] cannot auto-replenish", module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNoPaymentMethodAssociatedWithReplenishAccount", locale)); } GenericValue paymentMethod; try { paymentMethod = EntityQuery.use(delegator) .from("PaymentMethod") .where("paymentMethodId", paymentMethodId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (paymentMethod == null) { // no payment methods on file; cannot replenish Debug.logWarning( "finAccountReplenish Warning: No payment method found for ID [" + paymentMethodId + "] for party [" + ownerPartyId + "] cannot auto-replenish", module); return ServiceUtil.returnError( UtilProperties.getMessage( resourceError, "AccountingFinAccountNoPaymentMethodAssociatedWithReplenishAccount", locale)); } // hit the payment method for the amount to replenish Map<String, BigDecimal> orderItemMap = UtilMisc.toMap("Auto-Replenishment FA #" + finAccountId, depositAmount); Map<String, Object> replOrderCtx = new HashMap<String, Object>(); replOrderCtx.put("productStoreId", productStoreId); replOrderCtx.put("paymentMethodId", paymentMethod.getString("paymentMethodId")); replOrderCtx.put("currency", currency); replOrderCtx.put("partyId", ownerPartyId); replOrderCtx.put("itemMap", orderItemMap); replOrderCtx.put("userLogin", userLogin); Map<String, Object> replResp; try { replResp = dispatcher.runSync("createSimpleNonProductSalesOrder", replOrderCtx); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(replResp)) { return replResp; } String orderId = (String) replResp.get("orderId"); // create the deposit Map<String, Object> depositCtx = new HashMap<String, Object>(); depositCtx.put("productStoreId", productStoreId); depositCtx.put("finAccountId", finAccountId); depositCtx.put("currency", currency); depositCtx.put("partyId", ownerPartyId); depositCtx.put("orderId", orderId); depositCtx.put("orderItemSeqId", "00001"); // always one item on a replish order depositCtx.put("amount", depositAmount); depositCtx.put("reasonEnumId", "FATR_REPLENISH"); depositCtx.put("userLogin", userLogin); try { Map<String, Object> depositResp = dispatcher.runSync("finAccountDeposit", depositCtx); if (ServiceUtil.isError(depositResp)) { return depositResp; } } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // say we are in good standing again if ("FNACT_NEGPENDREPL".equals(statusId)) { try { Map<String, Object> ufaResp = dispatcher.runSync( "updateFinAccount", UtilMisc.<String, Object>toMap( "finAccountId", finAccountId, "statusId", "FNACT_ACTIVE", "userLogin", userLogin)); if (ServiceUtil.isError(ufaResp)) { return ufaResp; } } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } return ServiceUtil.returnSuccess(); }