use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.
the class FinAccountServices method createAccountAndCredit.
public static Map<String, Object> createAccountAndCredit(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
String finAccountTypeId = (String) context.get("finAccountTypeId");
String accountName = (String) context.get("accountName");
String finAccountId = (String) context.get("finAccountId");
Locale locale = (Locale) context.get("locale");
// check the type
if (finAccountTypeId == null) {
finAccountTypeId = "SVCCRED_ACCOUNT";
}
if (accountName == null) {
if ("SVCCRED_ACCOUNT".equals(finAccountTypeId)) {
accountName = "Customer Service Credit Account";
} else {
accountName = "Financial Account";
}
}
GenericValue userLogin = (GenericValue) context.get("userLogin");
try {
// find the most recent (active) service credit account for the specified party
String partyId = (String) context.get("partyId");
Map<String, String> lookupMap = UtilMisc.toMap("finAccountTypeId", finAccountTypeId, "ownerPartyId", partyId);
// if a productStoreId is present, restrict the accounts returned using the
// store's payToPartyId
String productStoreId = (String) context.get("productStoreId");
if (UtilValidate.isNotEmpty(productStoreId)) {
String payToPartyId = ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
if (UtilValidate.isNotEmpty(payToPartyId)) {
lookupMap.put("organizationPartyId", payToPartyId);
}
}
// if a currencyUomId is present, use it to restrict the accounts returned
String currencyUomId = (String) context.get("currencyUomId");
if (UtilValidate.isNotEmpty(currencyUomId)) {
lookupMap.put("currencyUomId", currencyUomId);
}
// check for an existing account
GenericValue creditAccount;
if (finAccountId != null) {
creditAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
} else {
creditAccount = EntityQuery.use(delegator).from("FinAccount").where(lookupMap).orderBy("-fromDate").filterByDate().queryFirst();
}
if (creditAccount == null) {
// create a new service credit account
String createAccountServiceName = "createFinAccount";
if (UtilValidate.isNotEmpty(productStoreId)) {
createAccountServiceName = "createFinAccountForStore";
}
// automatically set the parameters
ModelService createAccountService = dctx.getModelService(createAccountServiceName);
Map<String, Object> createAccountContext = createAccountService.makeValid(context, ModelService.IN_PARAM);
createAccountContext.put("finAccountTypeId", finAccountTypeId);
createAccountContext.put("finAccountName", accountName);
createAccountContext.put("ownerPartyId", partyId);
createAccountContext.put("userLogin", userLogin);
Map<String, Object> createAccountResult = dispatcher.runSync(createAccountServiceName, createAccountContext);
if (ServiceUtil.isError(createAccountResult) || ServiceUtil.isFailure(createAccountResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createAccountResult));
}
if (createAccountResult != null) {
String creditAccountId = (String) createAccountResult.get("finAccountId");
if (UtilValidate.isNotEmpty(creditAccountId)) {
creditAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", creditAccountId).queryOne();
// create the owner role
Map<String, Object> roleCtx = new HashMap<>();
roleCtx.put("partyId", partyId);
roleCtx.put("roleTypeId", "OWNER");
roleCtx.put("finAccountId", creditAccountId);
roleCtx.put("userLogin", userLogin);
roleCtx.put("fromDate", UtilDateTime.nowTimestamp());
Map<String, Object> roleResp;
try {
roleResp = dispatcher.runSync("createFinAccountRole", roleCtx);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(roleResp)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(roleResp));
}
// update the finAccountId for return parameter
finAccountId = creditAccountId;
}
}
if (creditAccount == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotCreditAccount", locale));
}
}
// create the credit transaction
Map<String, Object> transactionMap = new HashMap<>();
transactionMap.put("finAccountTransTypeId", "ADJUSTMENT");
transactionMap.put("finAccountId", creditAccount.getString("finAccountId"));
transactionMap.put("partyId", partyId);
transactionMap.put("amount", context.get("amount"));
transactionMap.put("reasonEnumId", context.get("reasonEnumId"));
transactionMap.put("comments", context.get("comments"));
transactionMap.put("userLogin", userLogin);
Map<String, Object> creditTransResult = dispatcher.runSync("createFinAccountTrans", transactionMap);
if (ServiceUtil.isError(creditTransResult) || ServiceUtil.isFailure(creditTransResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(creditTransResult));
}
} catch (GenericEntityException | GenericServiceException ge) {
return ServiceUtil.returnError(ge.getMessage());
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("finAccountId", finAccountId);
return result;
}
use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.
the class PaymentGatewayServices method processCaptureResult.
private static void processCaptureResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference, String authServiceType, Locale locale) throws GeneralException {
if (result == null) {
throw new GeneralException("Null capture result sent to processCaptureResult; fatal error");
}
LocalDispatcher dispatcher = dctx.getDispatcher();
Boolean captureResult = (Boolean) result.get("captureResult");
BigDecimal amount = null;
if (result.get("captureAmount") != null) {
amount = (BigDecimal) result.get("captureAmount");
} else if (result.get("processAmount") != null) {
amount = (BigDecimal) result.get("processAmount");
result.put("captureAmount", amount);
}
if (amount == null) {
throw new GeneralException("Unable to process null capture amount");
}
// setup the amount big decimal
amount = amount.setScale(decimals, rounding);
result.put("orderPaymentPreference", paymentPreference);
result.put("userLogin", userLogin);
result.put("serviceTypeEnum", authServiceType);
ModelService model = dctx.getModelService("processCaptureResult");
Map<String, Object> context = model.makeValid(result, ModelService.IN_PARAM);
Map<String, Object> capRes;
try {
capRes = dispatcher.runSync("processCaptureResult", context);
} catch (GenericServiceException e) {
Debug.logError(e, module);
throw e;
}
if (capRes != null && ServiceUtil.isError(capRes)) {
throw new GeneralException(ServiceUtil.getErrorMessage(capRes));
}
if (!captureResult.booleanValue()) {
// capture returned false (error)
try {
processReAuthFromCaptureFailure(dctx, result, amount, userLogin, paymentPreference, locale);
} catch (GeneralException e) {
// just log this for now (same as previous implementation)
Debug.logError(e, module);
}
}
}
use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.
the class PaymentGatewayServices method processManualCcTx.
// manual processing service
public static Map<String, Object> processManualCcTx(DispatchContext dctx, Map<String, ? extends Object> context) {
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Security security = dctx.getSecurity();
// security check
if (!security.hasEntityPermission("MANUAL", "_PAYMENT", userLogin) && !security.hasEntityPermission("ACCOUNTING", "_CREATE", userLogin)) {
Debug.logWarning("**** Security [" + (new Date()).toString() + "]: " + userLogin.get("userLoginId") + " attempt to run manual payment transaction!", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotAuthorized", locale));
}
String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
String paymentMethodTypeId = (String) context.get("paymentMethodTypeId");
String productStoreId = (String) context.get("productStoreId");
String transactionType = (String) context.get("transactionType");
String referenceCode = (String) context.get("referenceCode");
if (referenceCode == null) {
referenceCode = Long.valueOf(System.currentTimeMillis()).toString();
}
// Get the OrderPaymentPreference
GenericValue paymentPref = null;
try {
paymentPref = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
}
// Error if no OrderPaymentPreference was found
if (paymentPref == null) {
Debug.logWarning("Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
}
// Get the OrderHeader
GenericValue orderHeader = null;
String orderId = paymentPref.getString("orderId");
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problem getting OrderHeader for orderId " + orderId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
// Error if no OrderHeader was found
if (orderHeader == null) {
Debug.logWarning("Could not find OrderHeader with orderId: " + orderId + "; not processing payments.", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// check valid implemented types
if (!transactionType.equals(CREDIT_SERVICE_TYPE)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotYetSupported", locale));
}
// transaction request context
Map<String, Object> requestContext = new HashMap<>();
String paymentService = null;
String paymentConfig = null;
String paymentGatewayConfigId = null;
// get the transaction settings
GenericValue paymentSettings = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, paymentMethodTypeId, transactionType, false);
if (paymentSettings == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotFound", UtilMisc.toMap("productStoreId", productStoreId, "transactionType", transactionType), locale));
} else {
paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
String customMethodId = paymentSettings.getString("paymentCustomMethodId");
if (UtilValidate.isNotEmpty(customMethodId)) {
paymentService = getPaymentCustomMethod(delegator, customMethodId);
}
if (UtilValidate.isEmpty(paymentService)) {
paymentService = paymentSettings.getString("paymentService");
}
paymentConfig = paymentSettings.getString("paymentPropertiesPath");
if (paymentConfig == null) {
paymentConfig = "payment.properties";
}
requestContext.put("paymentConfig", paymentConfig);
requestContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
}
// check the service name
if (paymentService == null || paymentGatewayConfigId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotValid", locale));
}
if ("CREDIT_CARD".equals(paymentMethodTypeId)) {
GenericValue creditCard = delegator.makeValue("CreditCard");
creditCard.setAllFields(context, true, null, null);
if (creditCard.get("firstNameOnCard") == null || creditCard.get("lastNameOnCard") == null || creditCard.get("cardType") == null || creditCard.get("cardNumber") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardMissingMandatoryFields", locale));
}
String expMonth = (String) context.get("expMonth");
String expYear = (String) context.get("expYear");
String expDate = expMonth + "/" + expYear;
creditCard.set("expireDate", expDate);
requestContext.put("creditCard", creditCard);
requestContext.put("cardSecurityCode", context.get("cardSecurityCode"));
GenericValue billingAddress = delegator.makeValue("PostalAddress");
billingAddress.setAllFields(context, true, null, null);
if (billingAddress.get("address1") == null || billingAddress.get("city") == null || billingAddress.get("postalCode") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardBillingAddressMssingMandatoryFields", locale));
}
requestContext.put("billingAddress", billingAddress);
GenericValue billToEmail = delegator.makeValue("ContactMech");
billToEmail.set("infoString", context.get("infoString"));
if (billToEmail.get("infoString") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardEmailAddressCannotBeEmpty", locale));
}
requestContext.put("billToParty", orh.getBillToParty());
requestContext.put("billToEmail", billToEmail);
requestContext.put("referenceCode", referenceCode);
String currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
requestContext.put("currency", currency);
requestContext.put("creditAmount", context.get("amount"));
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotYetSupported", locale) + " " + paymentMethodTypeId);
}
// process the transaction
Map<String, Object> response = null;
try {
response = dispatcher.runSync(paymentService, requestContext, TX_TIME, true);
if (ServiceUtil.isError(response)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(response));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentServiceError", UtilMisc.toMap("paymentService", paymentService, "authContext", requestContext), locale));
}
// get the response result code
if (response != null && ServiceUtil.isSuccess(response)) {
Map<String, Object> responseRes;
try {
ModelService model = dctx.getModelService("processCreditResult");
response.put("orderPaymentPreference", paymentPref);
response.put("userLogin", userLogin);
Map<String, Object> resCtx = model.makeValid(response, ModelService.IN_PARAM);
responseRes = dispatcher.runSync(model.name, resCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditError", UtilMisc.toMap("errorString", e.getMessage()), locale));
}
if (responseRes != null && ServiceUtil.isError(responseRes)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(responseRes));
}
} else if (ServiceUtil.isError(response)) {
saveError(dispatcher, userLogin, paymentPref, response, CREDIT_SERVICE_TYPE, "PGT_CREDIT");
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(response));
}
// check for errors
if (ServiceUtil.isError(response)) {
return ServiceUtil.returnError(ServiceUtil.makeErrorMessage(response, null, null, null, null));
}
// get the reference number
String refNum = (String) response.get("creditRefNum");
String code = (String) response.get("creditCode");
String msg = (String) response.get("creditMessage");
Map<String, Object> returnResults = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingPaymentTransactionManualResult", UtilMisc.toMap("msg", msg, "code", code, "refNum", refNum), locale));
returnResults.put("referenceNum", refNum);
return returnResults;
}
use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.
the class PaymentGatewayServices method capturePayment.
private static Map<String, Object> capturePayment(DispatchContext dctx, GenericValue userLogin, OrderReadHelper orh, GenericValue paymentPref, BigDecimal amount, GenericValue authTrans, Locale locale) {
LocalDispatcher dispatcher = dctx.getDispatcher();
// look up the payment configuration settings
String serviceName = null;
String paymentConfig = null;
String paymentGatewayConfigId = null;
// get the payment settings i.e. serviceName and config properties file name
GenericValue paymentSettings = getPaymentSettings(orh.getOrderHeader(), paymentPref, CAPTURE_SERVICE_TYPE, false);
if (paymentSettings != null) {
String customMethodId = paymentSettings.getString("paymentCustomMethodId");
if (UtilValidate.isNotEmpty(customMethodId)) {
serviceName = getPaymentCustomMethod(orh.getOrderHeader().getDelegator(), customMethodId);
}
if (UtilValidate.isEmpty(serviceName)) {
serviceName = paymentSettings.getString("paymentService");
}
paymentConfig = paymentSettings.getString("paymentPropertiesPath");
paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
if (serviceName == null) {
Debug.logError("Service name is null for payment setting; cannot process", module);
return null;
}
} else {
Debug.logError("Invalid payment settings entity, no payment settings found", module);
return null;
}
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
// check the validity of the authorization; re-auth if necessary
if (!PaymentGatewayServices.checkAuthValidity(paymentPref, paymentConfig)) {
try {
// re-auth required before capture
Map<String, Object> processorResult = PaymentGatewayServices.authPayment(dispatcher, userLogin, orh, paymentPref, amount, true, null);
boolean authResult = false;
if (processorResult != null) {
// process the auth results
try {
authResult = processResult(dctx, processorResult, userLogin, paymentPref, locale);
if (!authResult) {
Debug.logError("Re-Authorization failed : " + paymentPref + " : " + processorResult, module);
}
} catch (GeneralException e) {
Debug.logError(e, "Trouble processing the re-auth result : " + paymentPref + " : " + processorResult, module);
}
} else {
Debug.logError("Payment not re-authorized : " + paymentPref + " (no process result)", module);
}
if (!authResult) {
// returning null to cancel the capture process.
return null;
}
// get the new auth transaction
authTrans = getAuthTransaction(paymentPref);
} catch (GeneralException e) {
Debug.logError(e, "Error re-authorizing payment", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentReauthorizingError", locale));
}
}
// prepare the context for the capture service (must follow the ccCaptureInterface
Map<String, Object> captureContext = new HashMap<>();
captureContext.put("userLogin", userLogin);
captureContext.put("orderPaymentPreference", paymentPref);
captureContext.put("paymentConfig", paymentConfig);
captureContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
captureContext.put("currency", orh.getCurrency());
// this is necessary because the ccCaptureInterface uses "captureAmount" but the paymentProcessInterface uses "processAmount"
try {
ModelService captureService = dctx.getModelService(serviceName);
Set<String> inParams = captureService.getInParamNames();
if (inParams.contains("captureAmount")) {
captureContext.put("captureAmount", amount);
} else if (inParams.contains("processAmount")) {
captureContext.put("processAmount", amount);
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentServiceMissingAmount", UtilMisc.toMap("serviceName", serviceName, "inParams", inParams), locale));
}
} catch (GenericServiceException ex) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentServiceCannotGetModel", UtilMisc.toMap("serviceName", serviceName), locale));
}
if (authTrans != null) {
captureContext.put("authTrans", authTrans);
}
if (Debug.infoOn()) {
Debug.logInfo("Capture [" + serviceName + "] : " + captureContext, module);
}
try {
String paymentMethodTypeId = paymentPref.getString("paymentMethodTypeId");
if (paymentMethodTypeId != null && "GIFT_CARD".equals(paymentMethodTypeId)) {
getBillingInformation(orh, paymentPref, captureContext);
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
// now invoke the capture service
Map<String, Object> captureResult = null;
try {
// NOTE DEJ20070819 calling this with a new transaction synchronously caused a deadlock because in this
// transaction OrderHeader was updated and with this transaction paused and waiting for the new transaction
// and the new transaction was waiting trying to read the same OrderHeader record; note that this only happens
// for FinAccounts because they are processed internally whereas others are not
// NOTE HOW TO FIX: don't call in separate transaction from here; individual services can have require-new-transaction
// set to true if they want to behave that way (had: [, TX_TIME, true])
captureResult = dispatcher.runSync(serviceName, captureContext);
if (ServiceUtil.isError(captureResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(captureResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, "Could not capture payment ... serviceName: " + serviceName + " ... context: " + captureContext, module);
return null;
}
// pass the payTo partyId to the result processor; we just add it to the result context.
String payToPartyId = getPayToPartyId(orh.getOrderHeader());
captureResult.put("payToPartyId", payToPartyId);
// add paymentSettings to result; for use by later processors
captureResult.put("paymentSettings", paymentSettings);
// pass the currencyUomId as well
captureResult.put("currencyUomId", orh.getCurrency());
// log the error message as a gateway response when it fails
if (ServiceUtil.isError(captureResult)) {
saveError(dispatcher, userLogin, paymentPref, captureResult, CAPTURE_SERVICE_TYPE, "PGT_CAPTURE");
}
return captureResult;
}
use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.
the class GroupServiceModel method invoke.
/**
* Invoker method to invoke this service
* @param dispatcher ServiceDispatcher used for this invocation
* @param localName Name of the LocalDispatcher used
* @param context Context for this service (will use only valid parameters)
* @return Map result Map
* @throws GenericServiceException
*/
public Map<String, Object> invoke(ServiceDispatcher dispatcher, String localName, Map<String, Object> context) throws GenericServiceException {
DispatchContext dctx = dispatcher.getLocalContext(localName);
ModelService model = dctx.getModelService(getName());
Map<String, Object> thisContext = model.makeValid(context, ModelService.IN_PARAM);
Debug.logInfo("Running grouped service [" + serviceName + "]", module);
if ("async".equals(getMode())) {
List<String> requiredOut = model.getParameterNames(ModelService.OUT_PARAM, false);
if (requiredOut.size() > 0) {
Debug.logWarning("Grouped service (" + getName() + ") requested 'async' invocation; running sync because of required OUT parameters.", module);
return dispatcher.runSync(localName, model, thisContext);
}
dispatcher.runAsync(localName, model, thisContext, false);
return new HashMap<>();
}
return dispatcher.runSync(localName, model, thisContext);
}
Aggregations