use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ShippingEvents method getShipGroupEstimate.
public static Map<String, Object> getShipGroupEstimate(LocalDispatcher dispatcher, Delegator delegator, String orderTypeId, String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId, String shippingContactMechId, String productStoreId, String supplierPartyId, List<Map<String, Object>> itemInfo, BigDecimal shippableWeight, BigDecimal shippableQuantity, BigDecimal shippableTotal, String partyId, String productStoreShipMethId, BigDecimal totalAllowance) {
String standardMessage = "A problem occurred calculating shipping. Fees will be calculated offline.";
List<String> errorMessageList = new LinkedList<String>();
if ("NO_SHIPPING".equals(shipmentMethodTypeId)) {
return ServiceUtil.returnSuccess();
}
if (shipmentMethodTypeId == null || carrierPartyId == null) {
if ("SALES_ORDER".equals(orderTypeId)) {
errorMessageList.add("Please Select Your Shipping Method.");
return ServiceUtil.returnError(errorMessageList);
} else {
return ServiceUtil.returnSuccess();
}
}
if (carrierRoleTypeId == null) {
carrierRoleTypeId = "CARRIER";
}
// if as supplier is associated, then we have a drop shipment and should use the origin shipment address of it
String shippingOriginContactMechId = null;
if (supplierPartyId != null) {
try {
GenericValue originAddress = getShippingOriginContactMech(delegator, supplierPartyId);
if (originAddress == null) {
return ServiceUtil.returnError("Cannot find the origin shipping address (SHIP_ORIG_LOCATION) for the supplier with ID [" + supplierPartyId + "]. Will not be able to calculate drop shipment estimate.");
}
shippingOriginContactMechId = originAddress.getString("contactMechId");
} catch (GeneralException e) {
return ServiceUtil.returnError(standardMessage);
}
}
// no shippable items; we won't change any shipping at all
if (shippableQuantity.compareTo(BigDecimal.ZERO) == 0) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shippingTotal", BigDecimal.ZERO);
return result;
}
// check for an external service call
GenericValue storeShipMethod = ProductStoreWorker.getProductStoreShipmentMethod(delegator, productStoreId, shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId);
if (storeShipMethod == null) {
errorMessageList.add("No applicable shipment method found.");
return ServiceUtil.returnError(errorMessageList);
}
// the initial amount before manual estimates
BigDecimal shippingTotal = BigDecimal.ZERO;
// prepare the service invocation fields
Map<String, Object> serviceFields = new HashMap<String, Object>();
serviceFields.put("initialEstimateAmt", shippingTotal);
serviceFields.put("shippableTotal", shippableTotal);
serviceFields.put("shippableQuantity", shippableQuantity);
serviceFields.put("shippableWeight", shippableWeight);
serviceFields.put("shippableItemInfo", itemInfo);
serviceFields.put("productStoreId", productStoreId);
serviceFields.put("carrierRoleTypeId", "CARRIER");
serviceFields.put("carrierPartyId", carrierPartyId);
serviceFields.put("shipmentMethodTypeId", shipmentMethodTypeId);
serviceFields.put("shippingContactMechId", shippingContactMechId);
serviceFields.put("shippingOriginContactMechId", shippingOriginContactMechId);
serviceFields.put("partyId", partyId);
serviceFields.put("productStoreShipMethId", productStoreShipMethId);
// call the external shipping service
try {
BigDecimal externalAmt = null;
if (UtilValidate.isNotEmpty(shippingContactMechId)) {
externalAmt = getExternalShipEstimate(dispatcher, storeShipMethod, serviceFields);
}
if (externalAmt != null) {
shippingTotal = shippingTotal.add(externalAmt);
}
} catch (GeneralException e) {
return ServiceUtil.returnError(standardMessage);
}
// update the initial amount
serviceFields.put("initialEstimateAmt", shippingTotal);
// call the generic estimate service
try {
BigDecimal genericAmt = getGenericShipEstimate(dispatcher, storeShipMethod, serviceFields);
if (genericAmt != null) {
shippingTotal = shippingTotal.add(genericAmt);
}
} catch (GeneralException e) {
return ServiceUtil.returnError(standardMessage);
}
// using shippingAllowance percent and deduct it from Actual Shipping Cost.
if (BigDecimal.ZERO.compareTo(shippingTotal) < 0 && UtilValidate.isNotEmpty(totalAllowance) && BigDecimal.ZERO.compareTo(totalAllowance) < 0) {
BigDecimal shippingAllowancePercent = storeShipMethod.getBigDecimal("allowancePercent") != null ? storeShipMethod.getBigDecimal("allowancePercent") : BigDecimal.ZERO;
totalAllowance = totalAllowance.multiply(shippingAllowancePercent.divide(BigDecimal.valueOf(100)));
shippingTotal = shippingTotal.subtract(totalAllowance);
}
// Check if minimum price is set for any Shipping Option, if yes,
// compare it with total shipping and use greater of the two.
BigDecimal minimumPrice = storeShipMethod.getBigDecimal("minimumPrice");
if (UtilValidate.isNotEmpty(minimumPrice) && shippingTotal.compareTo(minimumPrice) < 0) {
shippingTotal = minimumPrice;
}
// return the totals
Map<String, Object> responseResult = ServiceUtil.returnSuccess();
responseResult.put("shippingTotal", shippingTotal);
return responseResult;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ShoppingListEvents method saveCartToAutoSaveList.
/**
* Saves the shopping cart to the specialized (auto-save) shopping list
*/
public static String saveCartToAutoSaveList(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
try {
fillAutoSaveList(cart, dispatcher);
} catch (GeneralException e) {
Debug.logError(e, "Error saving the cart to the auto-save list: " + e.toString(), module);
}
return "success";
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ShoppingListEvents method restoreAutoSaveList.
/**
* Restores the specialized (auto-save) shopping list back into the shopping cart
*/
public static String restoreAutoSaveList(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericValue productStore = ProductStoreWorker.getProductStore(request);
if (!ProductStoreWorker.autoSaveCart(productStore)) {
// if auto-save is disabled just return here
return "success";
}
HttpSession session = request.getSession();
ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
// safety check for missing required parameter.
if (cart.getWebSiteId() == null) {
cart.setWebSiteId(WebSiteWorker.getWebSiteId(request));
}
// locate the user's identity
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (userLogin == null) {
userLogin = (GenericValue) session.getAttribute("autoUserLogin");
}
// find the list ID
String autoSaveListId = cart.getAutoSaveListId();
if (autoSaveListId == null) {
try {
autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
} catch (GeneralException e) {
Debug.logError(e, module);
}
cart.setAutoSaveListId(autoSaveListId);
} else if (userLogin != null) {
String existingAutoSaveListId = null;
try {
existingAutoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
} catch (GeneralException e) {
Debug.logError(e, module);
}
if (existingAutoSaveListId != null) {
if (!existingAutoSaveListId.equals(autoSaveListId)) {
// Replace with existing shopping list
cart.setAutoSaveListId(existingAutoSaveListId);
autoSaveListId = existingAutoSaveListId;
cart.setLastListRestore(null);
} else {
// because at this point items in the cart and the items in the shopping list are same so just return.
return "success";
}
}
}
// check to see if we are okay to load this list
java.sql.Timestamp lastLoad = cart.getLastListRestore();
boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false);
if (!okayToLoad && lastLoad != null) {
GenericValue shoppingList = null;
try {
shoppingList = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListId", autoSaveListId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (shoppingList != null) {
java.sql.Timestamp lastModified = shoppingList.getTimestamp("lastAdminModified");
if (lastModified != null) {
if (lastModified.after(lastLoad)) {
okayToLoad = true;
}
if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) {
okayToLoad = true;
}
}
}
}
// load (restore) the list of we have determined it is okay to load
if (okayToLoad) {
String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
try {
addListToCart(delegator, dispatcher, cart, prodCatalogId, autoSaveListId, false, false, userLogin != null ? true : false);
cart.setLastListRestore(UtilDateTime.nowTimestamp());
} catch (IllegalArgumentException e) {
Debug.logError(e, module);
}
}
return "success";
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ZipSalesServices method getItemTaxList.
private static List<GenericValue> getItemTaxList(Delegator delegator, GenericValue item, String zipCode, String city, BigDecimal itemAmount, BigDecimal shippingAmount, boolean isUseTax) throws GeneralException {
List<GenericValue> adjustments = new LinkedList<GenericValue>();
// check the item for tax status
if (item != null && item.get("taxable") != null && "N".equals(item.getString("taxable"))) {
// item not taxable
return adjustments;
}
// lookup the records
List<GenericValue> zipLookup = EntityQuery.use(delegator).from("ZipSalesTaxLookup").where("zipCode", zipCode).orderBy("-fromDate").queryList();
if (UtilValidate.isEmpty(zipLookup)) {
throw new GeneralException("The zip code entered is not valid.");
}
// the filtered list
// TODO: taxLookup is always null, so filter by County will never be executed
List<GenericValue> taxLookup = null;
// only do filtering if there are more then one zip code found
if (zipLookup != null && zipLookup.size() > 1) {
// first filter by city
List<GenericValue> cityLookup = EntityUtil.filterByAnd(zipLookup, UtilMisc.toMap("city", city.toUpperCase()));
if (UtilValidate.isNotEmpty(cityLookup)) {
if (cityLookup.size() > 1) {
// filter by county
List<GenericValue> countyLookup = EntityUtil.filterByAnd(taxLookup, UtilMisc.toMap("countyDefault", "Y"));
if (UtilValidate.isNotEmpty(countyLookup)) {
// use the county default
taxLookup = countyLookup;
} else {
// no county default; just use the first city
taxLookup = cityLookup;
}
} else {
// just one city found; use that one
taxLookup = cityLookup;
}
} else {
// no city found; lookup default city
List<GenericValue> defaultLookup = EntityUtil.filterByAnd(zipLookup, UtilMisc.toMap("generalDefault", "Y"));
if (UtilValidate.isNotEmpty(defaultLookup)) {
// use the default city lookup
taxLookup = defaultLookup;
} else {
// no default found; just use the first from the zip lookup
taxLookup = zipLookup;
}
}
} else {
// zero or 1 zip code found; use it
taxLookup = zipLookup;
}
// get the first one
GenericValue taxEntry = null;
if (UtilValidate.isNotEmpty(taxLookup)) {
taxEntry = taxLookup.iterator().next();
}
if (taxEntry == null) {
Debug.logWarning("No tax entry found for : " + zipCode + " / " + city + " - " + itemAmount, module);
return adjustments;
}
String fieldName = "comboSalesTax";
if (isUseTax) {
fieldName = "comboUseTax";
}
BigDecimal comboTaxRate = taxEntry.getBigDecimal(fieldName);
if (comboTaxRate == null) {
Debug.logWarning("No Combo Tax Rate In Field " + fieldName + " @ " + zipCode + " / " + city + " - " + itemAmount, module);
return adjustments;
}
// get state code
String stateCode = taxEntry.getString("stateCode");
// check if shipping is exempt
boolean taxShipping = true;
// look up the rules
List<GenericValue> ruleLookup = null;
try {
ruleLookup = EntityQuery.use(delegator).from("ZipSalesRuleLookup").where("stateCode", stateCode).orderBy("-fromDate").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
// filter out city
if (ruleLookup != null && ruleLookup.size() > 1) {
ruleLookup = EntityUtil.filterByAnd(ruleLookup, UtilMisc.toMap("city", city.toUpperCase()));
}
// no county captured; so filter by date
if (ruleLookup != null && ruleLookup.size() > 1) {
ruleLookup = EntityUtil.filterByDate(ruleLookup);
}
if (ruleLookup != null) {
for (GenericValue rule : ruleLookup) {
if (!taxShipping) {
// if we found an rule which passes no need to contine (all rules are ||)
break;
}
String idCode = rule.getString("idCode");
String taxable = rule.getString("taxable");
String condition = rule.getString("shipCond");
if ("T".equals(taxable)) {
// this record is taxable
continue;
} else {
// except if conditions are met
boolean qualify = false;
if (UtilValidate.isNotEmpty(condition)) {
char[] conditions = condition.toCharArray();
for (int i = 0; i < conditions.length; i++) {
switch(conditions[i]) {
case 'A':
// SHIPPING CHARGE SEPARATELY STATED ON INVOICE
// OFBiz does this by default
qualify = true;
break;
case 'B':
// SHIPPING CHARGE SEPARATED ON INVOICE FROM HANDLING OR SIMILAR CHARGES
// we do not support this currently
qualify = false;
break;
case 'C':
// ITEM NOT SOLD FOR GUARANTEED SHIPPED PRICE
// we don't support this currently
qualify = false;
break;
case 'D':
// SHIPPING CHARGE IS COST ONLY
// we assume a handling charge is included
qualify = false;
break;
case 'E':
// SHIPPED DIRECTLY TO PURCHASER
// this is true, unless gifts do not count?
qualify = true;
break;
case 'F':
// SHIPPED VIA COMMON CARRIER
// best guess default
qualify = true;
break;
case 'G':
// SHIPPED VIA CONTRACT CARRIER
// best guess default
qualify = false;
break;
case 'H':
// SHIPPED VIA VENDOR EQUIPMENT
// best guess default
qualify = false;
break;
case 'I':
// SHIPPED F.O.B. ORIGIN
// no clue
qualify = false;
break;
case 'J':
// SHIPPED F.O.B. DESTINATION
// no clue
qualify = false;
break;
case 'K':
// F.O.B. IS PURCHASERS OPTION
// no clue
qualify = false;
break;
case 'L':
// SHIPPING ORIGINATES OR TERMINATES IN DIFFERENT STATES
// not determined at order time, no way to know
qualify = true;
break;
case 'M':
// PROOF OF VENDOR ACTING AS SHIPPING AGENT FOR PURCHASER
// no clue
qualify = false;
break;
case 'N':
// SHIPPED FROM VENDOR LOCATION
// sure why not
qualify = true;
break;
case 'O':
// SHIPPING IS BY PURCHASER OPTION
// most online stores require shipping
qualify = false;
break;
case 'P':
// CREDIT ALLOWED FOR SHIPPING CHARGE PAID BY PURCHASER TO CARRIER
// best guess default
qualify = false;
break;
default:
break;
}
}
}
if (qualify) {
if (isUseTax) {
if (idCode.indexOf('U') > 0) {
taxShipping = false;
}
} else {
if (idCode.indexOf('S') > 0) {
taxShipping = false;
}
}
}
}
}
}
BigDecimal taxableAmount = itemAmount;
if (taxShipping) {
// Debug.logInfo("Taxing shipping", module);
taxableAmount = taxableAmount.add(shippingAmount);
} else {
Debug.logInfo("Shipping is not taxable", module);
}
// calc tax amount
BigDecimal taxRate = comboTaxRate;
BigDecimal taxCalc = taxableAmount.multiply(taxRate);
adjustments.add(delegator.makeValue("OrderAdjustment", UtilMisc.toMap("amount", taxCalc, "orderAdjustmentTypeId", "SALES_TAX", "comments", taxRate, "description", "Sales Tax (" + stateCode + ")")));
return adjustments;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class ZipSalesServices method flatTaxCalc.
// tax calc service
public static Map<String, Object> flatTaxCalc(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
List<GenericValue> itemProductList = UtilGenerics.checkList(context.get("itemProductList"));
List<BigDecimal> itemAmountList = UtilGenerics.checkList(context.get("itemAmountList"));
List<BigDecimal> itemShippingList = UtilGenerics.checkList(context.get("itemShippingList"));
BigDecimal orderShippingAmount = (BigDecimal) context.get("orderShippingAmount");
GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
// flatTaxCalc only uses the Zip + City from the address
String stateProvince = shippingAddress.getString("stateProvinceGeoId");
String postalCode = shippingAddress.getString("postalCode");
String city = shippingAddress.getString("city");
// setup the return lists.
List<GenericValue> orderAdjustments = new LinkedList<GenericValue>();
List<List<GenericValue>> itemAdjustments = new LinkedList<List<GenericValue>>();
// check for a valid state/province geo
String validStates = EntityUtilProperties.getPropertyValue("zipsales", "zipsales.valid.states", delegator);
if (UtilValidate.isNotEmpty(validStates)) {
List<String> stateSplit = StringUtil.split(validStates, "|");
if (!stateSplit.contains(stateProvince)) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("orderAdjustments", orderAdjustments);
result.put("itemAdjustments", itemAdjustments);
return result;
}
}
try {
// loop through and get per item tax rates
for (int i = 0; i < itemProductList.size(); i++) {
GenericValue product = itemProductList.get(i);
BigDecimal itemAmount = itemAmountList.get(i);
BigDecimal shippingAmount = itemShippingList.get(i);
itemAdjustments.add(getItemTaxList(delegator, product, postalCode, city, itemAmount, shippingAmount, false));
}
if (orderShippingAmount.compareTo(BigDecimal.ZERO) > 0) {
List<GenericValue> taxList = getItemTaxList(delegator, null, postalCode, city, BigDecimal.ZERO, orderShippingAmount, false);
orderAdjustments.addAll(taxList);
}
} catch (GeneralException e) {
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("orderAdjustments", orderAdjustments);
result.put("itemAdjustments", itemAdjustments);
return result;
}
Aggregations