use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class PayPalServices method doExpressCheckout.
// 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, RoundingMode.HALF_UP);
BigDecimal taxTotal = orh.getTaxTotal().setScale(2, RoundingMode.HALF_UP);
BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2, RoundingMode.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 = new HashMap<String, Object>();
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();
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class PayPalServices method getPaymentMethodGatewayPayPal.
private static GenericValue getPaymentMethodGatewayPayPal(DispatchContext dctx, Map<String, ? extends Object> context, String paymentServiceTypeEnumId) {
Delegator delegator = dctx.getDelegator();
String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
GenericValue payPalGatewayConfig = null;
if (paymentGatewayConfigId == null) {
String productStoreId = null;
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
if (orderPaymentPreference != null) {
OrderReadHelper orh = new OrderReadHelper(delegator, orderPaymentPreference.getString("orderId"));
productStoreId = orh.getProductStoreId();
} else {
ShoppingCart cart = (ShoppingCart) context.get("cart");
if (cart != null) {
productStoreId = cart.getProductStoreId();
}
}
if (productStoreId != null) {
GenericValue payPalPaymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "EXT_PAYPAL", paymentServiceTypeEnumId, true);
if (payPalPaymentSetting != null) {
paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId");
}
}
}
if (paymentGatewayConfigId != null) {
try {
payPalGatewayConfig = EntityQuery.use(delegator).from("PaymentGatewayPayPal").where("paymentGatewayConfigId", paymentGatewayConfigId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return payPalGatewayConfig;
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class FinAccountPaymentServices method finAccountPreAuth.
// 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");
if (paymentPref != null) {
// 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 {
Map<String, Object> result = dispatcher.runSync("expireFinAccountAuth", input);
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
if (finAccountId == 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 {
// default 30 days for an auth
thruDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), Long.valueOf(30));
}
Map<String, Object> tmpResult = dispatcher.runSync("createFinAccountAuth", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "amount", amount, "thruDate", thruDate, "userLogin", userLogin));
if (ServiceUtil.isError(tmpResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(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);
// a refNum is always required from authorization
refNum = "0";
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 | GenericServiceException ex) {
Debug.logError(ex, "Cannot authorize financial account", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeAuthorized", UtilMisc.toMap("errorString", ex.getMessage()), locale));
}
}
use of org.apache.ofbiz.order.order.OrderReadHelper 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.order.order.OrderReadHelper 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;
}
Aggregations