/** * Copies a user preference group. Call with fromUserLoginId, userPrefGroupTypeId and optional * userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in user's * userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> copyUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); String fromUserLoginId = (String) context.get("fromUserLoginId"); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || UtilValidate.isEmpty(fromUserLoginId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale)); } try { Map<String, String> fieldMap = UtilMisc.toMap( "userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId); List<GenericValue> resultList = delegator.findByAnd("UserPreference", fieldMap); if (resultList != null) { for (GenericValue preference : resultList) { preference.set("userLoginId", userLoginId); } delegator.storeAll(resultList); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "copyPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
/** * Retrieves a group of user preferences from persistent storage. Call with userPrefGroupTypeId * and optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in * user's userLoginId will be used. The retrieved preferences group is contained in the * <b>userPrefMap</b> element. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> getUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); if (!PreferenceWorker.isValidGetId(ctx, context)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.permissionError", locale)); } Delegator delegator = ctx.getDelegator(); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userPrefGroupTypeId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale)); } String userLoginId = PreferenceWorker.getUserLoginId(context, true); Map<String, Object> userPrefMap = null; try { Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", "_NA_", "userPrefGroupTypeId", userPrefGroupTypeId); userPrefMap = PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap)); fieldMap.put("userLoginId", userLoginId); userPrefMap.putAll( PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap))); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } // for the 'DEFAULT' values find the related values in general properties and if found use // those. Iterator it = userPrefMap.entrySet().iterator(); Map generalProperties = UtilProperties.getProperties("general"); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if ("DEFAULT".equals(pairs.getValue())) { if (UtilValidate.isNotEmpty(generalProperties.get(pairs.getKey()))) { userPrefMap.put((String) pairs.getKey(), generalProperties.get(pairs.getKey())); } } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("userPrefMap", userPrefMap); return result; }
/** * Retrieves a single user preference from persistent storage. Call with userPrefTypeId and * optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in * user's userLoginId will be used. The retrieved preference is contained in the * <b>userPrefMap</b> element. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); if (!PreferenceWorker.isValidGetId(ctx, context)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.permissionError", locale)); } Delegator delegator = ctx.getDelegator(); String userPrefTypeId = (String) context.get("userPrefTypeId"); if (UtilValidate.isEmpty(userPrefTypeId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale)); } String userLoginId = PreferenceWorker.getUserLoginId(context, true); Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) { fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId); } Map<String, Object> userPrefMap = null; try { GenericValue preference = EntityUtil.getFirst(delegator.findByAnd("UserPreference", fieldMap)); if (preference != null) { userPrefMap = PreferenceWorker.createUserPrefMap(preference); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("userPrefMap", userPrefMap); if (userPrefMap != null) { // Put the value in the result Map too, makes access easier for calling methods. Object userPrefValue = userPrefMap.get(userPrefTypeId); if (userPrefValue != null) { result.put("userPrefValue", userPrefValue); } } return result; }
/** * Removes this rule from the persistant store. * * @throws RecurrenceRuleException */ public void remove() throws RecurrenceRuleException { try { rule.remove(); } catch (GenericEntityException e) { throw new RecurrenceRuleException(e.getMessage(), e); } }
public static RecurrenceRule makeRule( Delegator delegator, int frequency, int interval, int count, long endTime) throws RecurrenceRuleException { String freq[] = {"", "SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"}; if (frequency < 1 || frequency > 7) throw new RecurrenceRuleException("Invalid frequency"); if (interval < 0) throw new RecurrenceRuleException("Invalid interval"); String freqStr = freq[frequency]; try { GenericValue value = delegator.makeValue("RecurrenceRule"); value.set("frequency", freqStr); value.set("intervalNumber", Long.valueOf(interval)); value.set("countNumber", Long.valueOf(count)); if (endTime > 0) { value.set("untilDateTime", new java.sql.Timestamp(endTime)); } delegator.createSetNextSeqId(value); RecurrenceRule newRule = new RecurrenceRule(value); return newRule; } catch (GenericEntityException ee) { throw new RecurrenceRuleException(ee.getMessage(), ee); } catch (RecurrenceRuleException re) { throw re; } }
public static Map<String, Object> ping(DispatchContext dctx, Map<String, ?> context) { Delegator delegator = dctx.getDelegator(); String message = (String) context.get("message"); Locale locale = (Locale) context.get("locale"); if (message == null) { message = "PONG"; } long count = -1; try { count = delegator.findCountByCondition("SequenceValueItem", null, null, null); } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonPingDatasourceCannotConnect", locale)); } if (count > 0) { Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("message", message); return result; } else { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonPingDatasourceInvalidCount", locale)); } }
/** * Creates a PartyRelationshipType * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createPartyRelationshipType( DispatchContext ctx, Map<String, ? extends Object> context) { Map<String, Object> result = FastMap.newInstance(); Delegator delegator = ctx.getDelegator(); Security security = ctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); ServiceUtil.getPartyIdCheckSecurity( userLogin, security, context, result, "PARTYMGR", "_CREATE"); if (result.size() > 0) return result; GenericValue partyRelationshipType = delegator.makeValue( "PartyRelationshipType", UtilMisc.toMap("partyRelationshipTypeId", context.get("partyRelationshipTypeId"))); partyRelationshipType.set("parentTypeId", context.get("parentTypeId"), true); partyRelationshipType.set("hasTable", context.get("hasTable"), true); partyRelationshipType.set("roleTypeIdValidFrom", context.get("roleTypeIdValidFrom"), true); partyRelationshipType.set("roleTypeIdValidTo", context.get("roleTypeIdValidTo"), false); partyRelationshipType.set("description", context.get("description"), true); partyRelationshipType.set("partyRelationshipName", context.get("partyRelationshipName"), true); try { if (delegator.findOne( partyRelationshipType.getEntityName(), partyRelationshipType.getPrimaryKey(), false) != null) { return ServiceUtil.returnError("Could not create party relationship type: already exists"); } } catch (GenericEntityException e) { Debug.logWarning(e, module); return ServiceUtil.returnError( "Could not create party relationship type (read failure): " + e.getMessage()); } try { partyRelationshipType.create(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship type (write failure): " + e.getMessage()); } result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); return result; }
/** * Authorizes and captures an EFT transaction. If the authorization or capture fails due to * problems with the transaction, this service will result in a failure. * * <p>If this service results in an error, it means that the service is not propery configured and * will not work until the issues are resolved. */ public static Map authorizeAndCaptureEft(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); String resource = getResource(context); Double amount = (Double) context.get("processAmount"); GenericValue eftAccount = (GenericValue) context.get("eftAccount"); String currencyUomId = (String) context.get("currency"); try { Map request = buildRequestHeader(resource); request.putAll(buildRequest(eftAccount, amount, currencyUomId, "AUTH_CAPTURE")); request.putAll(buildCustomerRequest(delegator, context)); request.putAll(buildOrderRequest(context)); AuthorizeResponse response = processRequest(request, resource); // process the response Map results = ServiceUtil.returnSuccess(); if (response == null) { results.put("authResult", Boolean.FALSE); results.put("authRefNum", AuthorizeResponse.ERROR); results.put("processAmount", new Double(0.0)); } else if (AuthorizeResponse.APPROVED.equals(response.getResponseCode())) { results.put("authResult", Boolean.TRUE); results.put("authFlag", response.getReasonCode()); results.put("authMessage", response.getReasonText()); results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE)); results.put("authRefNum", response.getResponseField(AuthorizeResponse.TRANSACTION_ID)); results.put( "processAmount", new Double(response.getResponseField(AuthorizeResponse.AMOUNT))); } else { results.put("authResult", Boolean.FALSE); results.put("authFlag", response.getReasonCode()); results.put("authMessage", response.getReasonText()); results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE)); results.put("authRefNum", AuthorizeResponse.ERROR); results.put("processAmount", new Double(0.0)); } if (isTestMode(resource)) { Debug.logInfo("eCheck.NET AUTH_CAPTURE results: " + results, module); } return results; } catch (GenericEntityException e) { String message = "Entity engine error when attempting to authorize and capture EFT via eCheck.net: " + e.getMessage(); Debug.logError(e, message, module); return ServiceUtil.returnError(message); } catch (GenericServiceException e) { String message = "Service error when attempting to authorize and capture EFT via eCheck.net. This is a configuration problem that must be fixed before this service can work properly: " + e.getMessage(); Debug.logError(e, message, module); return ServiceUtil.returnError(message); } }
/** * Stores a user preference group in persistent storage. Call with userPrefMap, * userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId isn't specified, then the * currently logged-in user's userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> setUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); Map<String, Object> userPrefMap = checkMap(context.get("userPrefMap"), String.class, Object.class); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || userPrefMap == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale)); } try { for (Iterator i = userPrefMap.entrySet().iterator(); i.hasNext(); ) { Map.Entry mapEntry = (Map.Entry) i.next(); GenericValue rec = delegator.makeValidValue( "UserPreference", PreferenceWorker.toFieldMap( userLoginId, (String) mapEntry.getKey(), userPrefGroupTypeId, (String) mapEntry.getValue())); delegator.createOrStore(rec); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
/** * Stores a single user preference in persistent storage. Call with userPrefTypeId, * userPrefGroupTypeId, userPrefValue and optional userPrefLoginId. If userPrefLoginId isn't * specified, then the currently logged-in user's userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> setUserPreference(DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); String userPrefTypeId = (String) context.get("userPrefTypeId"); Object userPrefValue = (String) context.get("userPrefValue"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefTypeId) || userPrefValue == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale)); } String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); String userPrefDataType = (String) context.get("userPrefDataType"); try { if (UtilValidate.isNotEmpty(userPrefDataType)) { userPrefValue = ObjectType.simpleTypeConvert(userPrefValue, userPrefDataType, null, null, false); } GenericValue rec = delegator.makeValidValue( "UserPreference", PreferenceWorker.toFieldMap( userLoginId, userPrefTypeId, userPrefGroupTypeId, userPrefValue)); delegator.createOrStore(rec); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
public static Map<String, Object> convertOrderIdListToHeaders( DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList")); List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList")); // we don't want to process if there is already a header list if (orderHeaderList == null) { // convert the ID list to headers if (orderIdList != null) { List<EntityCondition> conditionList1 = FastList.newInstance(); List<EntityCondition> conditionList2 = FastList.newInstance(); // we are only concerned about approved sales orders conditionList2.add( EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED")); conditionList2.add( EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER")); // build the expression list from the IDs for (String orderId : orderIdList) { conditionList1.add( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId)); } // create the conditions EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR); conditionList2.add(idCond); EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND); // run the query try { orderHeaderList = delegator.findList( "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } Debug.logInfo("Recieved orderIdList - " + orderIdList, module); Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("orderHeaderList", orderHeaderList); return result; }
/** * Create Note Record * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Timestamp noteDate = (Timestamp) context.get("noteDate"); String partyId = (String) context.get("partyId"); String noteName = (String) context.get("noteName"); String note = (String) context.get("note"); String noteId = delegator.getNextSeqId("NoteData"); Locale locale = (Locale) context.get("locale"); if (noteDate == null) { noteDate = UtilDateTime.nowTimestamp(); } // check for a party id if (partyId == null) { if (userLogin != null && userLogin.get("partyId") != null) partyId = userLogin.getString("partyId"); } Map<String, Object> fields = UtilMisc.toMap( "noteId", noteId, "noteName", noteName, "noteInfo", note, "noteParty", partyId, "noteDateTime", noteDate); try { GenericValue newValue = delegator.makeValue("NoteData", fields); delegator.create(newValue); } catch (GenericEntityException e) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonNoteCannotBeUpdated", UtilMisc.toMap("errorString", e.getMessage()), locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("noteId", noteId); result.put("partyId", partyId); return result; }
@Override public boolean exec(MethodContext methodContext) throws MiniLangException { String entityName = entityNameFse.expandString(methodContext.getEnvMap()); boolean useCache = "true".equals(useCacheFse.expandString(methodContext.getEnvMap())); boolean useIterator = "true".equals(useIteratorFse.expandString(methodContext.getEnvMap())); List<String> orderByNames = orderByListFma.get(methodContext.getEnvMap()); Collection<String> fieldsToSelectList = fieldsToSelectListFma.get(methodContext.getEnvMap()); Delegator delegator = getDelegator(methodContext); try { EntityCondition whereCond = null; Map<String, ? extends Object> fieldMap = mapFma.get(methodContext.getEnvMap()); if (fieldMap != null) { whereCond = EntityCondition.makeCondition(fieldMap); } if (useIterator) { listFma.put( methodContext.getEnvMap(), delegator.find( entityName, whereCond, null, UtilMisc.toSet(fieldsToSelectList), orderByNames, null)); } else { listFma.put( methodContext.getEnvMap(), delegator.findList( entityName, whereCond, UtilMisc.toSet(fieldsToSelectList), orderByNames, null, useCache)); } } catch (GenericEntityException e) { String errMsg = "Exception thrown while performing entity find: " + e.getMessage(); Debug.logWarning(e, errMsg, module); simpleMethod.addErrorMessage(methodContext, errMsg); return false; } return true; }
@SuppressWarnings("unchecked") public Writer getWriter(final Writer out, Map args) { final StringBuilder buf = new StringBuilder(); final Environment env = Environment.getCurrentEnvironment(); final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env); // FreeMarkerWorker.convertContext(templateCtx); final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames); FreeMarkerWorker.overrideWithArgs(templateCtx, args); final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); /* final String editTemplate = FreeMarkerWorker.getArg(args, "editTemplate", ctx); final String wrapTemplateId = FreeMarkerWorker.getArg(args, "wrapTemplateId", ctx); //final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx); final String templateContentId = FreeMarkerWorker.getArg(args, "templateContentId", ctx); final String subDataResourceTypeId = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx); final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx); final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx); final String rootDir = FreeMarkerWorker.getArg(args, "rootDir", ctx); final String webSiteId = FreeMarkerWorker.getArg(args, "webSiteId", ctx); final String https = FreeMarkerWorker.getArg(args, "https", ctx); final String viewSize = FreeMarkerWorker.getArg(args, "viewSize", ctx); final String viewIndex = FreeMarkerWorker.getArg(args, "viewIndex", ctx); final String listSize = FreeMarkerWorker.getArg(args, "listSize", ctx); final String highIndex = FreeMarkerWorker.getArg(args, "highIndex", ctx); final String lowIndex = FreeMarkerWorker.getArg(args, "lowIndex", ctx); final String queryString = FreeMarkerWorker.getArg(args, "queryString", ctx); final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env); final String mimeTypeId = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx); */ final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); // final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env); GenericValue view = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env); final Integer indent = (templateCtx.get("indent") == null) ? Integer.valueOf(0) : (Integer) templateCtx.get("indent"); String contentId = (String) templateCtx.get("contentId"); String subContentId = (String) templateCtx.get("subContentId"); if (view == null) { String thisContentId = subContentId; if (UtilValidate.isEmpty(thisContentId)) { thisContentId = contentId; } if (UtilValidate.isNotEmpty(thisContentId)) { try { view = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", thisContentId)); } catch (GenericEntityException e) { Debug.logError(e, "Error getting sub-content", module); throw new RuntimeException(e.getMessage()); } } } final GenericValue subContentDataResourceView = view; final Map<String, Object> traverseContext = FastMap.newInstance(); traverseContext.put("delegator", delegator); Map<String, Object> whenMap = FastMap.newInstance(); whenMap.put("followWhen", templateCtx.get("followWhen")); whenMap.put("pickWhen", templateCtx.get("pickWhen")); whenMap.put("returnBeforePickWhen", templateCtx.get("returnBeforePickWhen")); whenMap.put("returnAfterPickWhen", templateCtx.get("returnAfterPickWhen")); traverseContext.put("whenMap", whenMap); String fromDateStr = (String) templateCtx.get("fromDateStr"); String thruDateStr = (String) templateCtx.get("thruDateStr"); Timestamp fromDate = null; if (UtilValidate.isNotEmpty(fromDateStr)) { fromDate = UtilDateTime.toTimestamp(fromDateStr); } traverseContext.put("fromDate", fromDate); Timestamp thruDate = null; if (UtilValidate.isNotEmpty(thruDateStr)) { thruDate = UtilDateTime.toTimestamp(thruDateStr); } traverseContext.put("thruDate", thruDate); String startContentAssocTypeId = (String) templateCtx.get("contentAssocTypeId"); if (startContentAssocTypeId != null) startContentAssocTypeId = "SUB_CONTENT"; traverseContext.put("contentAssocTypeId", startContentAssocTypeId); String direction = (String) templateCtx.get("direction"); if (UtilValidate.isEmpty(direction)) direction = "From"; traverseContext.put("direction", direction); return new LoopWriter(out) { @Override public void write(char cbuf[], int off, int len) { // StringBuilder ctxBuf = (StringBuilder) templateContext.get("buf"); // ctxBuf.append(cbuf, off, len); buf.append(cbuf, off, len); } @Override public void flush() throws IOException { out.flush(); } @Override public int onStart() throws TemplateModelException, IOException { // templateContext.put("buf", new StringBuilder()); List<Map<String, Object>> nodeTrail = FastList.newInstance(); traverseContext.put("nodeTrail", nodeTrail); // GenericValue content = null; /* if (UtilValidate.isNotEmpty(contentId)) { try { content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId)); } catch (GenericEntityException e) { // TODO: Not sure what to put here. throw new RuntimeException(e.getMessage()); } } */ Map<String, Object> rootNode = ContentWorker.makeNode(subContentDataResourceView); ContentWorker.traceNodeTrail("1", nodeTrail); ContentWorker.selectKids(rootNode, traverseContext); ContentWorker.traceNodeTrail("2", nodeTrail); nodeTrail.add(rootNode); boolean isPick = checkWhen( subContentDataResourceView, (String) traverseContext.get("contentAssocTypeId")); rootNode.put("isPick", Boolean.valueOf(isPick)); if (!isPick) { ContentWorker.traceNodeTrail("3", nodeTrail); isPick = ContentWorker.traverseSubContent(traverseContext); ContentWorker.traceNodeTrail("4", nodeTrail); } if (isPick) { populateContext(traverseContext, templateCtx); ContentWorker.traceNodeTrail("5", nodeTrail); return TransformControl.EVALUATE_BODY; } else { return TransformControl.SKIP_BODY; } } @Override public int afterBody() throws TemplateModelException, IOException { // out.write(buf.toString()); // buf.setLength(0); // templateContext.put("buf", new StringBuilder()); List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail")); ContentWorker.traceNodeTrail("6", nodeTrail); boolean inProgress = ContentWorker.traverseSubContent(traverseContext); ContentWorker.traceNodeTrail("7", nodeTrail); if (inProgress) { populateContext(traverseContext, templateCtx); ContentWorker.traceNodeTrail("8", nodeTrail); return TransformControl.REPEAT_EVALUATION; } else return TransformControl.END_EVALUATION; } @Override public void close() throws IOException { String wrappedFTL = buf.toString(); String encloseWrappedText = (String) templateCtx.get("encloseWrappedText"); if (UtilValidate.isEmpty(encloseWrappedText) || encloseWrappedText.equalsIgnoreCase("false")) { out.write(wrappedFTL); wrappedFTL = null; // So it won't get written again below. } String wrapTemplateId = (String) templateCtx.get("wrapTemplateId"); if (UtilValidate.isNotEmpty(wrapTemplateId)) { templateCtx.put("wrappedFTL", wrappedFTL); Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env); /* templateRoot.put("viewSize", viewSize); templateRoot.put("viewIndex", viewIndex); templateRoot.put("listSize", listSize); templateRoot.put("highIndex", highIndex); templateRoot.put("lowIndex", lowIndex); templateRoot.put("queryString", queryString); templateRoot.put("wrapDataResourceTypeId", subDataResourceTypeId); templateRoot.put("wrapContentIdTo", contentId); templateRoot.put("wrapMimeTypeId", mimeTypeId); //templateRoot.put("wrapMapKey", mapKey); */ templateRoot.put("context", templateCtx); String mimeTypeId = (String) templateCtx.get("mimeTypeId"); Locale locale = (Locale) templateCtx.get("locale"); if (locale == null) locale = Locale.getDefault(); try { ContentWorker.renderContentAsText( dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true); } catch (GeneralException e) { Debug.logError(e, "Error rendering content", module); throw new IOException("Error rendering content" + e.toString()); } /* Map resultsCtx = FreeMarkerWorker.getWrappedObject("context", env); templateContext.put("contentId", contentId); templateContext.put("locale", locale); templateContext.put("mapKey", null); templateContext.put("subContentId", null); templateContext.put("templateContentId", null); templateContext.put("subDataResourceTypeId", null); templateContext.put("mimeTypeId", null); */ } else { if (UtilValidate.isNotEmpty(wrappedFTL)) out.write(wrappedFTL); } FreeMarkerWorker.removeValues(templateCtx, removeKeyNames); FreeMarkerWorker.reloadValues(templateCtx, savedValues, env); } private boolean checkWhen(GenericValue thisContent, String contentAssocTypeId) { boolean isPick = false; Map<String, Object> assocContext = FastMap.newInstance(); if (UtilValidate.isEmpty(contentAssocTypeId)) { contentAssocTypeId = ""; } assocContext.put("contentAssocTypeId", contentAssocTypeId); // assocContext.put("contentTypeId", assocValue.get("contentTypeId")); // String assocRelation = null; String thisDirection = (String) templateCtx.get("direction"); String thisContentId = (String) templateCtx.get("thisContentId"); // String relatedDirection = null; if (thisDirection != null && thisDirection.equalsIgnoreCase("From")) { assocContext.put("contentIdFrom", thisContentId); // assocRelation = "FromContent"; // relatedDirection = "From"; } else { assocContext.put("contentIdTo", thisContentId); // assocRelation = "ToContent"; // relatedDirection = "To"; } assocContext.put("content", thisContent); List<Object> purposes = ContentWorker.getPurposes(thisContent); assocContext.put("purposes", purposes); List<String> contentTypeAncestry = FastList.newInstance(); String contentTypeId = (String) thisContent.get("contentTypeId"); try { ContentWorker.getContentTypeAncestry(delegator, contentTypeId, contentTypeAncestry); } catch (GenericEntityException e) { return false; } assocContext.put("typeAncestry", contentTypeAncestry); Map<String, Object> whenMap = UtilGenerics.checkMap(traverseContext.get("whenMap")); // String pickWhen = (String)whenMap.get("pickWhen"); List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail")); int indentSz = indent.intValue() + nodeTrail.size(); assocContext.put("indentObj", Integer.valueOf(indentSz)); isPick = ContentWorker.checkWhen(assocContext, (String) whenMap.get("pickWhen")); return isPick; } public void populateContext( Map<String, Object> traverseContext, Map<String, Object> templateContext) { List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail")); int sz = nodeTrail.size(); Map<String, Object> node = nodeTrail.get(sz - 1); // GenericValue content = (GenericValue)node.get("value"); String contentId = (String) node.get("contentId"); // String subContentId = (String)node.get("subContentId"); templateContext.put("subContentId", contentId); templateContext.put("subContentDataResourceView", null); int indentSz = indent.intValue() + nodeTrail.size(); templateContext.put("indent", Integer.valueOf(indentSz)); if (sz >= 2) { Map<String, Object> parentNode = nodeTrail.get(sz - 2); GenericValue parentContent = (GenericValue) parentNode.get("value"); String parentContentId = (String) parentNode.get("contentId"); templateContext.put("parentContentId", parentContentId); templateContext.put("parentContent", parentContent); templateContext.put("nodeTrail", nodeTrail); } } }; }
public static List<GenericValue> getRelatedCategoriesRet( Delegator delegator, String attributeName, String parentId, boolean limitView, boolean excludeEmpty, boolean recursive) { List<GenericValue> categories = FastList.newInstance(); if (Debug.verboseOn()) Debug.logVerbose("[CategoryWorker.getRelatedCategories] ParentID: " + parentId, module); List<GenericValue> rollups = null; try { rollups = delegator.findByAndCache( "ProductCategoryRollup", UtilMisc.toMap("parentProductCategoryId", parentId), UtilMisc.toList("sequenceNum")); if (limitView) { rollups = EntityUtil.filterByDate(rollups, true); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (rollups != null) { // Debug.logInfo("Rollup size: " + rollups.size(), module); for (GenericValue parent : rollups) { // Debug.logInfo("Adding child of: " + parent.getString("parentProductCategoryId"), module); GenericValue cv = null; try { cv = parent.getRelatedOneCache("CurrentProductCategory"); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); } if (cv != null) { if (excludeEmpty) { if (!isCategoryEmpty(cv)) { // Debug.logInfo("Child : " + cv.getString("productCategoryId") + " is not empty.", // module); categories.add(cv); if (recursive) { categories.addAll( getRelatedCategoriesRet( delegator, attributeName, cv.getString("productCategoryId"), limitView, excludeEmpty, recursive)); } } } else { categories.add(cv); if (recursive) { categories.addAll( getRelatedCategoriesRet( delegator, attributeName, cv.getString("productCategoryId"), limitView, excludeEmpty, recursive)); } } } } } return categories; }
/** * Creates and updates a PartyRelationship creating related PartyRoles if needed. A side of the * relationship is checked to maintain history * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createUpdatePartyRelationshipAndRoles( DispatchContext ctx, Map<String, ? extends Object> context) { Map<String, Object> result = FastMap.newInstance(); Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); try { List<GenericValue> partyRelationShipList = PartyRelationshipHelper.getActivePartyRelationships(delegator, context); if (UtilValidate.isEmpty( partyRelationShipList)) { // If already exists and active nothing to do: keep the current // one String partyId = (String) context.get("partyId"); String partyIdFrom = (String) context.get("partyIdFrom"); String partyIdTo = (String) context.get("partyIdTo"); String roleTypeIdFrom = (String) context.get("roleTypeIdFrom"); String roleTypeIdTo = (String) context.get("roleTypeIdTo"); String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId"); // Before creating the partyRelationShip, create the partyRoles if they don't exist GenericValue partyToRole = null; partyToRole = delegator.findOne( "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo), false); if (partyToRole == null) { partyToRole = delegator.makeValue( "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo)); partyToRole.create(); } GenericValue partyFromRole = null; partyFromRole = delegator.findOne( "PartyRole", UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom), false); if (partyFromRole == null) { partyFromRole = delegator.makeValue( "PartyRole", UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom)); partyFromRole.create(); } // Check if there is already a partyRelationship of that type with another party from the // side indicated String sideChecked = partyIdFrom.equals(partyId) ? "partyIdFrom" : "partyIdTo"; partyRelationShipList = delegator.findByAnd( "PartyRelationship", UtilMisc.toMap( sideChecked, partyId, "roleTypeIdFrom", roleTypeIdFrom, "roleTypeIdTo", roleTypeIdTo, "partyRelationshipTypeId", partyRelationshipTypeId)); // We consider the last one (in time) as sole active (we try to maintain a unique // relationship and keep changes history) partyRelationShipList = EntityUtil.filterByDate(partyRelationShipList); GenericValue oldPartyRelationShip = EntityUtil.getFirst(partyRelationShipList); if (UtilValidate.isNotEmpty(oldPartyRelationShip)) { oldPartyRelationShip.setFields( UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp())); // Current becomes inactive oldPartyRelationShip.store(); } try { dispatcher.runSync("createPartyRelationship", context); // Create new one } catch (GenericServiceException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship (write failure): " + e.getMessage()); } } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship (write failure): " + e.getMessage()); } result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); return result; }
// Note we're not doing a lot of error checking here as this method is really only used // to confirm the order with PayPal, the subsequent authorizations will handle any errors // that may occur. public static Map<String, Object> doExpressCheckout( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId")); Locale locale = (Locale) context.get("locale"); GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null); GenericValue payPalPaymentMethod = null; try { payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false); payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoExpressCheckoutPayment"); encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken")); encoder.add("PAYMENTACTION", "Order"); encoder.add("PAYERID", payPalPaymentMethod.getString("payerId")); // set the amount encoder.add("AMT", processAmount.setScale(2).toPlainString()); encoder.add("CURRENCYCODE", orh.getCurrency()); BigDecimal grandTotal = orh.getOrderGrandTotal(); BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2, BigDecimal.ROUND_HALF_UP); encoder.add("ITEMAMT", subTotal.toPlainString()); encoder.add("SHIPPINGAMT", shippingTotal.toPlainString()); encoder.add("TAXAMT", taxTotal.toPlainString()); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalPaymentSetting, 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, String> errorMessages = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errorMessages)) { if (errorMessages.containsKey("10417")) { // "The transaction cannot complete successfully, Instruct the customer to use an // alternative payment method" // I've only encountered this once and there's no indication of the cause so the temporary // solution is to try again boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_"); if (retry) { context.put("_RETRY_", false); return PayPalServices.doExpressCheckout(dctx, context); } } return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values())); } Map<String, Object> inMap = FastMap.newInstance(); inMap.put("userLogin", userLogin); inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId")); inMap.put("transactionId", decoder.get("TRANSACTIONID")); Map<String, Object> outMap = null; try { outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(outMap)) { Debug.logError(ServiceUtil.getErrorMessage(outMap), module); return outMap; } return ServiceUtil.returnSuccess(); }
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(); }
// 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(); }
// 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 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> 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; }
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"; }