use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.
the class LoginWorker method doBasicLogout.
public static void doBasicLogout(GenericValue userLogin, HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
Delegator delegator = (Delegator) request.getAttribute("delegator");
Security security = (Security) request.getAttribute("security");
if (security != null && userLogin != null) {
security.clearUserData(userLogin);
}
// set the logged out flag
if (userLogin != null) {
LoginWorker.setLoggedOut(userLogin.getString("userLoginId"), delegator);
}
// this is a setting we don't want to lose, although it would be good to have a more general solution here...
String currCatalog = (String) session.getAttribute("CURRENT_CATALOG_ID");
// also make sure the delegatorName is preserved, especially so that a new Visit can be created
String delegatorName = (String) session.getAttribute("delegatorName");
// also save the shopping cart if we have one
// DON'T save the cart, causes too many problems: security issues with things done in cart to easy to miss, especially bad on public systems; was put in here because of the "not me" link for auto-login stuff, but that is a small problem compared to what it causes
// ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
// clean up some request attributes to which may no longer be valid now that user has logged out
request.removeAttribute("delegator");
request.removeAttribute("dispatcher");
request.removeAttribute("security");
// now empty out the session
session.invalidate();
session = request.getSession(true);
if (EntityUtilProperties.propertyValueEquals("security", "security.login.tomcat.sso", "true")) {
try {
// log out from Tomcat SSO
request.logout();
} catch (ServletException e) {
Debug.logError(e, module);
}
}
// setup some things that should always be there
UtilHttp.setInitialRequestInfo(request);
if (currCatalog != null)
session.setAttribute("CURRENT_CATALOG_ID", currCatalog);
if (delegatorName != null) {
// Commented it as multi tenancy support is now available for front-store application as well.
// if there is a tenantId in the delegatorName remove it now so that tenant selection doesn't last beyond logout
/*if (delegatorName.indexOf('#') > 0) {
delegatorName = delegatorName.substring(0, delegatorName.indexOf('#'));
}*/
session.setAttribute("delegatorName", delegatorName);
delegator = DelegatorFactory.getDelegator(delegatorName);
LocalDispatcher dispatcher = WebAppUtil.makeWebappDispatcher(session.getServletContext(), delegator);
setWebContextObjects(request, response, delegator, dispatcher);
}
// DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", new WebShoppingCart(shoppingCart, session));
}
use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.
the class OrderServices method recalcOrderShipping.
/**
* Service for checking and re-calc the shipping amount
*/
public static Map<String, Object> recalcOrderShipping(DispatchContext ctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = ctx.getDispatcher();
Delegator delegator = ctx.getDelegator();
String orderId = (String) context.get("orderId");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
// check and make sure we have permission to change the order
Security security = ctx.getSecurity();
boolean hasPermission = OrderServices.hasPermission(orderId, userLogin, "UPDATE", security, delegator);
if (!hasPermission) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToChangeThisOrdersStatus", locale));
}
// get the order header
GenericValue orderHeader = null;
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotGetOrderHeaderEntity", locale) + e.getMessage());
}
if (orderHeader == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorNoValidOrderHeaderFoundForOrderId", UtilMisc.toMap("orderId", orderId), locale));
}
OrderReadHelper orh = new OrderReadHelper(orderHeader);
List<GenericValue> shipGroups = orh.getOrderItemShipGroups();
if (shipGroups != null) {
for (GenericValue shipGroup : shipGroups) {
String shipGroupSeqId = shipGroup.getString("shipGroupSeqId");
if (shipGroup.get("contactMechId") == null || shipGroup.get("shipmentMethodTypeId") == null) {
// not shipped (face-to-face order)
continue;
}
Map<String, Object> shippingEstMap = ShippingEvents.getShipEstimate(dispatcher, delegator, orh, shipGroupSeqId);
BigDecimal shippingTotal = null;
if (UtilValidate.isEmpty(orh.getValidOrderItems(shipGroupSeqId))) {
shippingTotal = ZERO;
Debug.logInfo("No valid order items found - " + shippingTotal, module);
} else {
shippingTotal = UtilValidate.isEmpty(shippingEstMap.get("shippingTotal")) ? ZERO : (BigDecimal) shippingEstMap.get("shippingTotal");
shippingTotal = shippingTotal.setScale(orderDecimals, orderRounding);
Debug.logInfo("Got new shipping estimate - " + shippingTotal, module);
}
if (Debug.infoOn()) {
Debug.logInfo("New Shipping Total [" + orderId + " / " + shipGroupSeqId + "] : " + shippingTotal, module);
}
BigDecimal currentShipping = OrderReadHelper.getAllOrderItemsAdjustmentsTotal(orh.getOrderItemAndShipGroupAssoc(shipGroupSeqId), orh.getAdjustments(), false, false, true);
currentShipping = currentShipping.add(OrderReadHelper.calcOrderAdjustments(orh.getOrderHeaderAdjustments(shipGroupSeqId), orh.getOrderItemsSubTotal(), false, false, true));
if (Debug.infoOn()) {
Debug.logInfo("Old Shipping Total [" + orderId + " / " + shipGroupSeqId + "] : " + currentShipping, module);
}
List<String> errorMessageList = UtilGenerics.checkList(shippingEstMap.get(ModelService.ERROR_MESSAGE_LIST));
if (errorMessageList != null) {
Debug.logWarning("Problem finding shipping estimates for [" + orderId + "/ " + shipGroupSeqId + "] = " + errorMessageList, module);
continue;
}
if ((shippingTotal != null) && (shippingTotal.compareTo(currentShipping) != 0)) {
// place the difference as a new shipping adjustment
BigDecimal adjustmentAmount = shippingTotal.subtract(currentShipping);
String adjSeqId = delegator.getNextSeqId("OrderAdjustment");
GenericValue orderAdjustment = delegator.makeValue("OrderAdjustment", UtilMisc.toMap("orderAdjustmentId", adjSeqId));
orderAdjustment.set("orderAdjustmentTypeId", "SHIPPING_CHARGES");
orderAdjustment.set("amount", adjustmentAmount);
orderAdjustment.set("orderId", orh.getOrderId());
orderAdjustment.set("shipGroupSeqId", shipGroupSeqId);
orderAdjustment.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
orderAdjustment.set("createdDate", UtilDateTime.nowTimestamp());
orderAdjustment.set("createdByUserLogin", userLogin.getString("userLoginId"));
try {
orderAdjustment.create();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem creating shipping re-calc adjustment : " + orderAdjustment, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotCreateAdjustment", locale));
}
}
// TODO: re-balance free shipping adjustment
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.
the class OrderServices method setItemStatus.
/**
* Service for changing the status on order item(s)
*/
public static Map<String, Object> setItemStatus(DispatchContext ctx, Map<String, ? extends Object> context) {
Delegator delegator = ctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String orderId = (String) context.get("orderId");
String orderItemSeqId = (String) context.get("orderItemSeqId");
String fromStatusId = (String) context.get("fromStatusId");
String statusId = (String) context.get("statusId");
Timestamp statusDateTime = (Timestamp) context.get("statusDateTime");
Locale locale = (Locale) context.get("locale");
// check and make sure we have permission to change the order
Security security = ctx.getSecurity();
boolean hasPermission = OrderServices.hasPermission(orderId, userLogin, "UPDATE", security, delegator);
if (!hasPermission) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToChangeThisOrdersStatus", locale));
}
List<EntityExpr> exprs = new ArrayList<>();
exprs.add(EntityCondition.makeCondition("orderId", orderId));
if (orderItemSeqId != null) {
exprs.add(EntityCondition.makeCondition("orderItemSeqId", orderItemSeqId));
}
if (fromStatusId != null) {
exprs.add(EntityCondition.makeCondition("statusId", fromStatusId));
} else {
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("ITEM_COMPLETED", "ITEM_CANCELLED")));
}
List<GenericValue> orderItems = null;
try {
orderItems = EntityQuery.use(delegator).from("OrderItem").where(exprs).queryList();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotGetOrderItemEntity", locale) + e.getMessage());
}
if (UtilValidate.isNotEmpty(orderItems)) {
List<GenericValue> toBeStored = new ArrayList<>();
for (GenericValue orderItem : orderItems) {
if (orderItem == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotChangeItemStatusItemNotFound", locale));
}
if (Debug.verboseOn()) {
Debug.logVerbose("[OrderServices.setItemStatus] : Status Change: [" + orderId + "] (" + orderItem.getString("orderItemSeqId"), module);
}
if (Debug.verboseOn()) {
Debug.logVerbose("[OrderServices.setItemStatus] : From Status : " + orderItem.getString("statusId"), module);
}
if (Debug.verboseOn()) {
Debug.logVerbose("[OrderServices.setOrderStatus] : To Status : " + statusId, module);
}
if (orderItem.getString("statusId").equals(statusId)) {
continue;
}
try {
GenericValue statusChange = EntityQuery.use(delegator).from("StatusValidChange").where("statusId", orderItem.getString("statusId"), "statusIdTo", statusId).queryOne();
if (statusChange == null) {
Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderItemStatusNotChangedIsNotAValidChange", UtilMisc.toMap("orderStatusId", orderItem.getString("statusId"), "statusId", statusId), locale), module);
continue;
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeItemStatus", locale) + e.getMessage());
}
orderItem.set("statusId", statusId);
toBeStored.add(orderItem);
if (statusDateTime == null) {
statusDateTime = UtilDateTime.nowTimestamp();
}
// now create a status change
Map<String, Object> changeFields = new HashMap<>();
changeFields.put("orderStatusId", delegator.getNextSeqId("OrderStatus"));
changeFields.put("statusId", statusId);
changeFields.put("orderId", orderId);
changeFields.put("orderItemSeqId", orderItem.getString("orderItemSeqId"));
changeFields.put("statusDatetime", statusDateTime);
changeFields.put("statusUserLogin", userLogin.getString("userLoginId"));
GenericValue orderStatus = delegator.makeValue("OrderStatus", changeFields);
toBeStored.add(orderStatus);
}
// store the changes
if (toBeStored.size() > 0) {
try {
delegator.storeAll(toBeStored);
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotStoreStatusChanges", locale) + e.getMessage());
}
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.
the class OrderServices method setOrderStatus.
/**
* Service for changing the status on an order header
*/
public static Map<String, Object> setOrderStatus(DispatchContext ctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = ctx.getDispatcher();
Delegator delegator = ctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String orderId = (String) context.get("orderId");
String statusId = (String) context.get("statusId");
String changeReason = (String) context.get("changeReason");
Map<String, Object> successResult = ServiceUtil.returnSuccess();
Locale locale = (Locale) context.get("locale");
// check and make sure we have permission to change the order
Security security = ctx.getSecurity();
boolean hasPermission = OrderServices.hasPermission(orderId, userLogin, "UPDATE", security, delegator);
if (!hasPermission) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToChangeThisOrdersStatus", locale));
}
try {
GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
if (orderHeader == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeOrderStatusOrderCannotBeFound", locale));
}
// first save off the old status
successResult.put("oldStatusId", orderHeader.get("statusId"));
successResult.put("orderTypeId", orderHeader.get("orderTypeId"));
if (Debug.verboseOn()) {
Debug.logVerbose("[OrderServices.setOrderStatus] : From Status : " + orderHeader.getString("statusId"), module);
}
if (Debug.verboseOn()) {
Debug.logVerbose("[OrderServices.setOrderStatus] : To Status : " + statusId, module);
}
if (orderHeader.getString("statusId").equals(statusId)) {
Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderTriedToSetOrderStatusWithTheSameStatusIdforOrderWithId", UtilMisc.toMap("statusId", statusId, "orderId", orderId), locale), module);
return successResult;
}
try {
GenericValue statusChange = EntityQuery.use(delegator).from("StatusValidChange").where("statusId", orderHeader.getString("statusId"), "statusIdTo", statusId).cache(true).queryOne();
if (statusChange == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeOrderStatusStatusIsNotAValidChange", locale) + ": [" + orderHeader.getString("statusId") + "] -> [" + statusId + "]");
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeOrderStatus", locale) + e.getMessage() + ").");
}
// update the current status
orderHeader.set("statusId", statusId);
// now create a status change
GenericValue orderStatus = delegator.makeValue("OrderStatus");
orderStatus.put("orderStatusId", delegator.getNextSeqId("OrderStatus"));
orderStatus.put("statusId", statusId);
orderStatus.put("orderId", orderId);
orderStatus.put("statusDatetime", UtilDateTime.nowTimestamp());
orderStatus.put("statusUserLogin", userLogin.getString("userLoginId"));
orderStatus.put("changeReason", changeReason);
orderHeader.store();
orderStatus.create();
successResult.put("needsInventoryIssuance", orderHeader.get("needsInventoryIssuance"));
successResult.put("grandTotal", orderHeader.get("grandTotal"));
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeOrderStatus", locale) + e.getMessage() + ").");
}
if ("Y".equals(context.get("setItemStatus"))) {
String newItemStatusId = null;
if ("ORDER_APPROVED".equals(statusId)) {
newItemStatusId = "ITEM_APPROVED";
} else if ("ORDER_COMPLETED".equals(statusId)) {
newItemStatusId = "ITEM_COMPLETED";
} else if ("ORDER_CANCELLED".equals(statusId)) {
newItemStatusId = "ITEM_CANCELLED";
}
if (newItemStatusId != null) {
try {
Map<String, Object> resp = dispatcher.runSync("changeOrderItemStatus", UtilMisc.<String, Object>toMap("orderId", orderId, "statusId", newItemStatusId, "userLogin", userLogin));
if (ServiceUtil.isError(resp)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeItemStatus", locale) + newItemStatusId, null, null, resp);
}
} catch (GenericServiceException e) {
Debug.logError(e, "Error changing item status to " + newItemStatusId + ": " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCouldNotChangeItemStatus", locale) + newItemStatusId + ": " + e.toString());
}
}
}
successResult.put("orderStatusId", statusId);
return successResult;
}
use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.
the class OrderServices method recalcOrderTax.
/**
* Service for checking and re-calc the tax amount
*/
public static Map<String, Object> recalcOrderTax(DispatchContext ctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = ctx.getDispatcher();
Delegator delegator = ctx.getDelegator();
String orderId = (String) context.get("orderId");
String orderItemSeqId = (String) context.get("orderItemSeqId");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
// check and make sure we have permission to change the order
Security security = ctx.getSecurity();
boolean hasPermission = OrderServices.hasPermission(orderId, userLogin, "UPDATE", security, delegator);
if (!hasPermission) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderYouDoNotHavePermissionToChangeThisOrdersStatus", locale));
}
// get the order header
GenericValue orderHeader = null;
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorCannotGetOrderHeaderEntity", locale) + e.getMessage());
}
if (orderHeader == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderErrorNoValidOrderHeaderFoundForOrderId", UtilMisc.toMap("orderId", orderId), locale));
}
// Retrieve the order tax adjustments
List<GenericValue> orderTaxAdjustments = null;
try {
orderTaxAdjustments = EntityQuery.use(delegator).from("OrderAdjustment").where("orderId", orderId, "orderAdjustmentTypeId", "SALES_TAX").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to retrieve SALES_TAX adjustments for order : " + orderId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderUnableToRetrieveSalesTaxAdjustments", locale));
}
// Accumulate the total existing tax adjustment
BigDecimal totalExistingOrderTax = ZERO;
for (GenericValue orderTaxAdjustment : orderTaxAdjustments) {
if (orderTaxAdjustment.get("amount") != null) {
totalExistingOrderTax = totalExistingOrderTax.add(orderTaxAdjustment.getBigDecimal("amount").setScale(taxDecimals, taxRounding));
}
}
// Accumulate the total manually added tax adjustment
BigDecimal totalManuallyAddedOrderTax = ZERO;
for (GenericValue orderTaxAdjustment : orderTaxAdjustments) {
if (orderTaxAdjustment.get("amount") != null && "Y".equals(orderTaxAdjustment.getString("isManual"))) {
totalManuallyAddedOrderTax = totalManuallyAddedOrderTax.add(orderTaxAdjustment.getBigDecimal("amount").setScale(taxDecimals, taxRounding));
}
}
// Recalculate the taxes for the order
BigDecimal totalNewOrderTax = ZERO;
OrderReadHelper orh = new OrderReadHelper(orderHeader);
List<GenericValue> shipGroups = orh.getOrderItemShipGroups();
if (shipGroups != null) {
for (GenericValue shipGroup : shipGroups) {
String shipGroupSeqId = shipGroup.getString("shipGroupSeqId");
List<GenericValue> validOrderItems = orh.getValidOrderItems(shipGroupSeqId);
if (validOrderItems != null) {
// prepare the inital lists
List<GenericValue> products = new ArrayList<>(validOrderItems.size());
List<BigDecimal> amounts = new ArrayList<>(validOrderItems.size());
List<BigDecimal> shipAmts = new ArrayList<>(validOrderItems.size());
List<BigDecimal> itPrices = new ArrayList<>(validOrderItems.size());
List<BigDecimal> itQuantities = new ArrayList<>(validOrderItems.size());
// adjustments and total
List<GenericValue> allAdjustments = orh.getAdjustments();
List<GenericValue> orderHeaderAdjustments = OrderReadHelper.getOrderHeaderAdjustments(allAdjustments, shipGroupSeqId);
BigDecimal orderSubTotal = OrderReadHelper.getOrderItemsSubTotal(validOrderItems, allAdjustments);
// shipping amount
BigDecimal orderShipping = OrderReadHelper.calcOrderAdjustments(orderHeaderAdjustments, orderSubTotal, false, false, true);
// promotions amount
BigDecimal orderPromotions = OrderReadHelper.calcOrderPromoAdjustmentsBd(allAdjustments);
// build up the list of tax calc service parameters
for (int i = 0; i < validOrderItems.size(); i++) {
GenericValue orderItem = validOrderItems.get(i);
String productId = orderItem.getString("productId");
try {
// get the product entity
products.add(i, EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne());
// get the item amount
amounts.add(i, OrderReadHelper.getOrderItemSubTotal(orderItem, allAdjustments, true, false));
// get the shipping amount
shipAmts.add(i, OrderReadHelper.getOrderItemAdjustmentsTotal(orderItem, allAdjustments, false, false, true));
itPrices.add(i, orderItem.getBigDecimal("unitPrice"));
itQuantities.add(i, orderItem.getBigDecimal("quantity"));
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot read order item entity : " + orderItem, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderCannotReadTheOrderItemEntity", locale));
}
}
GenericValue shippingAddress = orh.getShippingAddress(shipGroupSeqId);
// no shipping address, try the billing address
if (shippingAddress == null) {
List<GenericValue> billingAddressList = orh.getBillingLocations();
if (billingAddressList.size() > 0) {
shippingAddress = billingAddressList.get(0);
}
}
// this should be made consistent with the CheckOutHelper.makeTaxContext(int shipGroup, GenericValue shipAddress) method
if (shippingAddress == null) {
// face-to-face order; use the facility address
String facilityId = orderHeader.getString("originFacilityId");
if (facilityId != null) {
GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator, facilityId, UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
if (facilityContactMech != null) {
try {
shippingAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
}
}
// if shippingAddress is still null then don't calculate tax; it may be an situation where no tax is applicable, or the data is bad and we don't have a way to find an address to check tax for
if (shippingAddress == null) {
Debug.logWarning("Not calculating tax for Order [" + orderId + "] because there is no shippingAddress, and no address on the origin facility [" + orderHeader.getString("originFacilityId") + "]", module);
continue;
}
// prepare the service context
Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productStoreId", orh.getProductStoreId(), "itemProductList", products, "itemAmountList", amounts, "itemShippingList", shipAmts, "itemPriceList", itPrices, "itemQuantityList", itQuantities, "orderShippingAmount", orderShipping);
serviceContext.put("shippingAddress", shippingAddress);
serviceContext.put("orderPromotionsAmount", orderPromotions);
if (orh.getBillToParty() != null) {
serviceContext.put("billToPartyId", orh.getBillToParty().getString("partyId"));
}
if (orh.getBillFromParty() != null) {
serviceContext.put("payToPartyId", orh.getBillFromParty().getString("partyId"));
}
// invoke the calcTax service
Map<String, Object> serviceResult = null;
try {
serviceResult = dispatcher.runSync("calcTax", serviceContext);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemOccurredInTaxService", locale));
}
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
// the adjustments (returned in order) from the tax service
List<GenericValue> orderAdj = UtilGenerics.checkList(serviceResult.get("orderAdjustments"));
List<List<GenericValue>> itemAdj = UtilGenerics.checkList(serviceResult.get("itemAdjustments"));
// Accumulate the new tax total from the recalculated header adjustments
if (UtilValidate.isNotEmpty(orderAdj)) {
for (GenericValue oa : orderAdj) {
if (oa.get("amount") != null) {
totalNewOrderTax = totalNewOrderTax.add(oa.getBigDecimal("amount").setScale(taxDecimals, taxRounding));
}
}
}
// Accumulate the new tax total from the recalculated item adjustments
if (UtilValidate.isNotEmpty(itemAdj)) {
for (int i = 0; i < itemAdj.size(); i++) {
List<GenericValue> itemAdjustments = itemAdj.get(i);
for (GenericValue ia : itemAdjustments) {
if (ia.get("amount") != null) {
totalNewOrderTax = totalNewOrderTax.add(ia.getBigDecimal("amount").setScale(taxDecimals, taxRounding));
}
}
}
}
}
}
// If there is any manually added tax then add it into new system generated tax.
if (totalManuallyAddedOrderTax.compareTo(BigDecimal.ZERO) > 0) {
totalNewOrderTax = totalNewOrderTax.add(totalManuallyAddedOrderTax).setScale(taxDecimals, taxRounding);
}
// Determine the difference between existing and new tax adjustment totals, if any
BigDecimal orderTaxDifference = totalNewOrderTax.subtract(totalExistingOrderTax).setScale(taxDecimals, taxRounding);
// If the total has changed, create an OrderAdjustment to reflect the fact
if (orderTaxDifference.signum() != 0) {
Map<String, Object> createOrderAdjContext = new HashMap<>();
createOrderAdjContext.put("orderAdjustmentTypeId", "SALES_TAX");
createOrderAdjContext.put("orderId", orderId);
if (UtilValidate.isNotEmpty(orderItemSeqId)) {
createOrderAdjContext.put("orderItemSeqId", orderItemSeqId);
} else {
createOrderAdjContext.put("orderItemSeqId", "_NA_");
}
createOrderAdjContext.put("shipGroupSeqId", "_NA_");
createOrderAdjContext.put("description", "Tax adjustment due to order change");
createOrderAdjContext.put("amount", orderTaxDifference);
createOrderAdjContext.put("userLogin", userLogin);
Map<String, Object> createOrderAdjResponse = null;
try {
createOrderAdjResponse = dispatcher.runSync("createOrderAdjustment", createOrderAdjContext);
} catch (GenericServiceException e) {
String createOrderAdjErrMsg = UtilProperties.getMessage(resource_error, "OrderErrorCallingCreateOrderAdjustmentService", locale);
Debug.logError(createOrderAdjErrMsg, module);
return ServiceUtil.returnError(createOrderAdjErrMsg);
}
if (ServiceUtil.isError(createOrderAdjResponse)) {
Debug.logError(ServiceUtil.getErrorMessage(createOrderAdjResponse), module);
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createOrderAdjResponse));
}
}
}
return ServiceUtil.returnSuccess();
}
Aggregations