use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class FinAccountPaymentServices method finAccountCapture.
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));
if (ServiceUtil.isError(releaseResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// build the withdraw context
Map<String, Object> withdrawCtx = new HashMap<>();
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");
// for captures; if auth passed, allow
withdrawCtx.put("requireBalance", Boolean.FALSE);
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 ServiceUtil.returnError(ServiceUtil.getErrorMessage(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;
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class FinAccountPaymentServices method createFinAcctPaymentTransaction.
private static String createFinAcctPaymentTransaction(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, BigDecimal amount, String productStoreId, String partyId, String orderId, String orderItemSeqId, String currencyUom, String txType, String finAccountId, String reasonEnumId) throws GeneralException {
final String coParty = ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
final String paymentMethodType = "FIN_ACCOUNT";
if (UtilValidate.isEmpty(partyId)) {
partyId = "_NA_";
}
String paymentType;
String partyIdFrom;
String partyIdTo;
BigDecimal paymentAmount;
// determine the payment type and which direction the parties should go
if ("DEPOSIT".equals(txType)) {
paymentType = "RECEIPT";
partyIdFrom = partyId;
partyIdTo = coParty;
paymentAmount = amount;
} else if ("WITHDRAWAL".equals(txType)) {
paymentType = "DISBURSEMENT";
partyIdFrom = coParty;
partyIdTo = partyId;
paymentAmount = amount;
} else if ("ADJUSTMENT".equals(txType)) {
if (amount.compareTo(BigDecimal.ZERO) < 0) {
paymentType = "DISBURSEMENT";
partyIdFrom = coParty;
partyIdTo = partyId;
// must be positive
paymentAmount = amount.negate();
} else {
paymentType = "RECEIPT";
partyIdFrom = partyId;
partyIdTo = coParty;
paymentAmount = amount;
}
} else {
throw new GeneralException("Unable to create financial account transaction!");
}
// payment amount should always be positive; adjustments may
// create the payment for the transaction
Map<String, Object> paymentCtx = UtilMisc.<String, Object>toMap("paymentTypeId", paymentType);
paymentCtx.put("paymentMethodTypeId", paymentMethodType);
paymentCtx.put("partyIdTo", partyIdTo);
paymentCtx.put("partyIdFrom", partyIdFrom);
paymentCtx.put("statusId", "PMNT_RECEIVED");
paymentCtx.put("currencyUomId", currencyUom);
paymentCtx.put("amount", paymentAmount);
paymentCtx.put("userLogin", userLogin);
paymentCtx.put("paymentRefNum", Long.toString(UtilDateTime.nowTimestamp().getTime()));
String paymentId;
Map<String, Object> payResult;
try {
payResult = dispatcher.runSync("createPayment", paymentCtx);
if (ServiceUtil.isError(payResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(payResult));
}
} catch (GenericServiceException e) {
throw new GeneralException(e);
}
if (payResult == null) {
throw new GeneralException("Unknow error in creating financial account transaction!");
}
if (ServiceUtil.isError(payResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(payResult));
}
paymentId = (String) payResult.get("paymentId");
// create the initial transaction
Map<String, Object> transCtx = UtilMisc.<String, Object>toMap("finAccountTransTypeId", txType);
transCtx.put("finAccountId", finAccountId);
transCtx.put("partyId", partyId);
transCtx.put("orderId", orderId);
transCtx.put("orderItemSeqId", orderItemSeqId);
transCtx.put("reasonEnumId", reasonEnumId);
transCtx.put("amount", amount);
transCtx.put("userLogin", userLogin);
transCtx.put("paymentId", paymentId);
Map<String, Object> transResult;
try {
transResult = dispatcher.runSync("createFinAccountTrans", transCtx);
if (ServiceUtil.isError(transResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(transResult));
}
} catch (GenericServiceException e) {
throw new GeneralException(e);
}
if (transResult == null) {
throw new GeneralException("Unknown error in creating financial account transaction!");
}
if (ServiceUtil.isError(transResult)) {
throw new GeneralException(ServiceUtil.getErrorMessage(transResult));
}
return (String) transResult.get("finAccountTransId");
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class FinAccountServices method createFinAccountForStore.
public static Map<String, Object> createFinAccountForStore(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String productStoreId = (String) context.get("productStoreId");
String finAccountTypeId = (String) context.get("finAccountTypeId");
Locale locale = (Locale) context.get("locale");
GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
try {
// get the product store id and use it to generate a unique fin account code
GenericValue productStoreFinAccountSetting = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where("productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId).cache().queryOne();
if (productStoreFinAccountSetting == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountSetting", UtilMisc.toMap("productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId), locale));
}
Long accountCodeLength = productStoreFinAccountSetting.getLong("accountCodeLength");
Long accountValidDays = productStoreFinAccountSetting.getLong("accountValidDays");
Long pinCodeLength = productStoreFinAccountSetting.getLong("pinCodeLength");
String requirePinCode = productStoreFinAccountSetting.getString("requirePinCode");
// automatically set the parameters for the create fin account service
ModelService createService = dctx.getModelService("createFinAccount");
Map<String, Object> inContext = createService.makeValid(context, ModelService.IN_PARAM);
Timestamp now = UtilDateTime.nowTimestamp();
// now use our values
String finAccountCode = null;
if (UtilValidate.isNotEmpty(accountCodeLength)) {
finAccountCode = FinAccountHelper.getNewFinAccountCode(accountCodeLength.intValue(), delegator);
inContext.put("finAccountCode", finAccountCode);
}
// with pin codes, the account code becomes the ID and the pin becomes the code
if ("Y".equalsIgnoreCase(requirePinCode)) {
String pinCode = FinAccountHelper.getNewFinAccountCode(pinCodeLength.intValue(), delegator);
inContext.put("finAccountPin", pinCode);
}
// set the dates/userlogin
if (UtilValidate.isNotEmpty(accountValidDays)) {
inContext.put("thruDate", UtilDateTime.getDayEnd(now, accountValidDays));
}
inContext.put("fromDate", now);
inContext.put("userLogin", userLogin);
// product store payToPartyId
String payToPartyId = ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
inContext.put("organizationPartyId", payToPartyId);
inContext.put("currencyUomId", productStore.get("defaultCurrencyUomId"));
Map<String, Object> createResult = dispatcher.runSync("createFinAccount", inContext);
if (ServiceUtil.isError(createResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResult));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("finAccountId", createResult.get("finAccountId"));
result.put("finAccountCode", finAccountCode);
return result;
} catch (GenericEntityException | GenericServiceException ex) {
return ServiceUtil.returnError(ex.getMessage());
}
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class FinAccountProductServices method createPartyFinAccountFromPurchase.
public static Map<String, Object> createPartyFinAccountFromPurchase(DispatchContext dctx, Map<String, Object> context) {
// this service should always be called via FULFILLMENT_EXTASYNC
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
GenericValue orderItem = (GenericValue) context.get("orderItem");
GenericValue userLogin = (GenericValue) context.get("userLogin");
// order ID for tracking
String orderId = orderItem.getString("orderId");
String orderItemSeqId = orderItem.getString("orderItemSeqId");
// the order header for store info
GenericValue orderHeader;
try {
orderHeader = orderItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderHeader from OrderItem", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderCannotGetOrderHeader", UtilMisc.toMap("orderId", orderId), locale));
}
String productId = orderItem.getString("productId");
GenericValue featureAndAppl;
try {
List<GenericValue> featureAndAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureTypeId", "TYPE", "productFeatureApplTypeId", "STANDARD_FEATURE").queryList();
featureAndAppls = EntityUtil.filterByDate(featureAndAppls);
featureAndAppl = EntityUtil.getFirst(featureAndAppls);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// financial account data; pulled from the TYPE feature of the product
// default
String finAccountTypeId = "BALANCE_ACCOUNT";
String finAccountName = "Customer Financial Account";
if (featureAndAppl != null) {
if (UtilValidate.isNotEmpty(featureAndAppl.getString("idCode"))) {
finAccountTypeId = featureAndAppl.getString("idCode");
}
if (UtilValidate.isNotEmpty(featureAndAppl.getString("description"))) {
finAccountName = featureAndAppl.getString("description");
}
}
// locate the financial account type
GenericValue finAccountType;
try {
finAccountType = EntityQuery.use(delegator).from("FinAccountType").where("finAccountTypeId", finAccountTypeId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
String replenishEnumId = finAccountType.getString("replenishEnumId");
// get the order read helper
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// get the currency
String currency = orh.getCurrency();
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
// get the product store
String productStoreId = null;
if (orderHeader != null) {
productStoreId = orh.getProductStoreId();
}
if (productStoreId == null) {
Debug.logFatal("Unable to create financial accout; no productStoreId on OrderHeader : " + orderId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotCreate", UtilMisc.toMap("orderId", orderId), locale));
}
// party ID (owner)
GenericValue billToParty = orh.getBillToParty();
String partyId = null;
if (billToParty != null) {
partyId = billToParty.getString("partyId");
}
// payment method info
List<GenericValue> payPrefs = orh.getPaymentPreferences();
String paymentMethodId = null;
if (payPrefs != null) {
for (GenericValue pref : payPrefs) {
// needs to be a CC or EFT account
String type = pref.getString("paymentMethodTypeId");
if ("CREDIT_CARD".equals(type) || "EFT_ACCOUNT".equals(type)) {
paymentMethodId = pref.getString("paymentMethodId");
}
}
}
// some person data for expanding
GenericValue partyGroup = null;
GenericValue person = null;
GenericValue party = null;
if (billToParty != null) {
try {
party = billToParty.getRelatedOne("Party", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (party != null) {
String partyTypeId = party.getString("partyTypeId");
if ("PARTY_GROUP".equals(partyTypeId)) {
partyGroup = billToParty;
} else if ("PERSON".equals(partyTypeId)) {
person = billToParty;
}
}
}
// create the context for FSE
Map<String, Object> expContext = new HashMap<>();
expContext.put("orderHeader", orderHeader);
expContext.put("orderItem", orderItem);
expContext.put("party", party);
expContext.put("person", person);
expContext.put("partyGroup", partyGroup);
// expand the name field to dynamically add information
FlexibleStringExpander exp = FlexibleStringExpander.getInstance(finAccountName);
finAccountName = exp.expandString(expContext);
// price/amount/quantity to create initial deposit amount
BigDecimal quantity = orderItem.getBigDecimal("quantity");
BigDecimal price = orderItem.getBigDecimal("unitPrice");
BigDecimal deposit = price.multiply(quantity).setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);
// create the financial account
Map<String, Object> createCtx = new HashMap<>();
String finAccountId;
createCtx.put("finAccountTypeId", finAccountTypeId);
createCtx.put("finAccountName", finAccountName);
createCtx.put("productStoreId", productStoreId);
createCtx.put("ownerPartyId", partyId);
createCtx.put("currencyUomId", currency);
createCtx.put("statusId", "FNACT_ACTIVE");
createCtx.put("userLogin", userLogin);
// if we auto-replenish this type; set the level to the initial deposit
if (replenishEnumId != null && "FARP_AUTOMATIC".equals(replenishEnumId)) {
createCtx.put("replenishLevel", deposit);
createCtx.put("replenishPaymentId", paymentMethodId);
}
Map<String, Object> createResp;
try {
createResp = dispatcher.runSync("createFinAccountForStore", createCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(createResp)) {
Debug.logFatal(ServiceUtil.getErrorMessage(createResp), module);
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp));
}
finAccountId = (String) createResp.get("finAccountId");
// create the owner role
Map<String, Object> roleCtx = new HashMap<>();
roleCtx.put("partyId", partyId);
roleCtx.put("roleTypeId", "OWNER");
roleCtx.put("finAccountId", finAccountId);
roleCtx.put("userLogin", userLogin);
roleCtx.put("fromDate", UtilDateTime.nowTimestamp());
Map<String, Object> roleResp;
try {
roleResp = dispatcher.runSync("createFinAccountRole", roleCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(roleResp)) {
Debug.logFatal(ServiceUtil.getErrorMessage(roleResp), module);
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(roleResp));
}
// create the initial deposit
Map<String, Object> depositCtx = new HashMap<>();
depositCtx.put("finAccountId", finAccountId);
depositCtx.put("productStoreId", productStoreId);
depositCtx.put("currency", currency);
depositCtx.put("partyId", partyId);
depositCtx.put("orderId", orderId);
depositCtx.put("orderItemSeqId", orderItemSeqId);
depositCtx.put("amount", deposit);
depositCtx.put("reasonEnumId", "FATR_IDEPOSIT");
depositCtx.put("userLogin", userLogin);
Map<String, Object> depositResp;
try {
depositResp = dispatcher.runSync("finAccountDeposit", depositCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (ServiceUtil.isError(depositResp)) {
Debug.logFatal(ServiceUtil.getErrorMessage(depositResp), module);
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(depositResp));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("finAccountId", finAccountId);
return result;
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class InvoiceServices method checkPaymentInvoices.
public static Map<String, Object> checkPaymentInvoices(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String paymentId = (String) context.get("paymentId");
try {
GenericValue payment = EntityQuery.use(delegator).from("Payment").where("paymentId", paymentId).queryOne();
if (payment == null) {
throw new GenericServiceException("Payment with ID [" + paymentId + "] not found!");
}
List<GenericValue> paymentApplications = payment.getRelated("PaymentApplication", null, null, false);
if (UtilValidate.isEmpty(paymentApplications)) {
return ServiceUtil.returnSuccess();
}
// TODO: this is inefficient -- instead use HashSet to construct a distinct Set of invoiceIds, then iterate over it and call checkInvoicePaymentAppls
for (GenericValue paymentApplication : paymentApplications) {
String invoiceId = paymentApplication.getString("invoiceId");
if (invoiceId != null) {
Map<String, Object> serviceResult = dispatcher.runSync("checkInvoicePaymentApplications", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "userLogin", userLogin));
if (ServiceUtil.isError(serviceResult)) {
return serviceResult;
}
}
}
return ServiceUtil.returnSuccess();
} catch (GenericServiceException | GenericEntityException se) {
Debug.logError(se, se.getMessage(), module);
return ServiceUtil.returnError(se.getMessage());
}
}
Aggregations