use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class ShoppingOrderController method displayCheckout.
@SuppressWarnings("unused")
@RequestMapping("/checkout.html")
public String displayCheckout(@CookieValue("cart") String cookie, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
Language language = (Language) request.getAttribute("LANGUAGE");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
model.addAttribute("googleMapsKey", googleMapsKey);
/**
* Shopping cart
*
* ShoppingCart should be in the HttpSession
* Otherwise the cart id is in the cookie
* Otherwise the customer is in the session and a cart exist in the DB
* Else -> Nothing to display
*/
// check if an existing order exist
ShopOrder order = null;
order = super.getSessionAttribute(Constants.ORDER, request);
// Get the cart from the DB
String shoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
com.salesmanager.core.model.shoppingcart.ShoppingCart cart = null;
if (StringUtils.isBlank(shoppingCartCode)) {
if (cookie == null) {
// session expired and cookie null, nothing to do
return "redirect:/shop/cart/shoppingCart.html";
}
String[] merchantCookie = cookie.split("_");
String merchantStoreCode = merchantCookie[0];
if (!merchantStoreCode.equals(store.getCode())) {
return "redirect:/shop/cart/shoppingCart.html";
}
shoppingCartCode = merchantCookie[1];
}
cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
if (cart == null && customer != null) {
cart = shoppingCartFacade.getShoppingCartModel(customer, store);
}
boolean allAvailables = true;
boolean requiresShipping = false;
boolean freeShoppingCart = true;
// Filter items, delete unavailable
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> availables = new HashSet<ShoppingCartItem>();
if (cart == null) {
return "redirect:/shop/cart/shoppingCart.html";
}
// Take out items no more available
Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cart.getLineItems();
for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
Long id = item.getProduct().getId();
Product p = productService.getById(id);
if (p.isAvailable()) {
availables.add(item);
} else {
allAvailables = false;
}
FinalPrice finalPrice = pricingService.calculateProductPrice(p);
if (finalPrice.getFinalPrice().longValue() > 0) {
freeShoppingCart = false;
}
if (p.isProductShipeable()) {
requiresShipping = true;
}
}
cart.setLineItems(availables);
if (!allAvailables) {
shoppingCartFacade.saveOrUpdateShoppingCart(cart);
}
super.setSessionAttribute(Constants.SHOPPING_CART, cart.getShoppingCartCode(), request);
if (shoppingCartCode == null && cart == null) {
// error
return "redirect:/shop/cart/shoppingCart.html";
}
if (customer != null) {
if (cart.getCustomerId() != customer.getId().longValue()) {
return "redirect:/shop/shoppingCart.html";
}
} else {
customer = orderFacade.initEmptyCustomer(store);
AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
if (anonymousCustomer != null && anonymousCustomer.getBilling() != null) {
Billing billing = customer.getBilling();
billing.setCity(anonymousCustomer.getBilling().getCity());
Map<String, Country> countriesMap = countryService.getCountriesMap(language);
Country anonymousCountry = countriesMap.get(anonymousCustomer.getBilling().getCountry());
if (anonymousCountry != null) {
billing.setCountry(anonymousCountry);
}
Map<String, Zone> zonesMap = zoneService.getZones(language);
Zone anonymousZone = zonesMap.get(anonymousCustomer.getBilling().getZone());
if (anonymousZone != null) {
billing.setZone(anonymousZone);
}
if (anonymousCustomer.getBilling().getPostalCode() != null) {
billing.setPostalCode(anonymousCustomer.getBilling().getPostalCode());
}
customer.setBilling(billing);
}
}
if (CollectionUtils.isEmpty(items)) {
return "redirect:/shop/shoppingCart.html";
}
if (order == null) {
// TODO
order = orderFacade.initializeOrder(store, customer, cart, language);
}
/**
* hook for displaying or not delivery address configuration
*/
ShippingMetaData shippingMetaData = shippingService.getShippingMetaData(store);
model.addAttribute("shippingMetaData", shippingMetaData);
/**
* shipping *
*/
ShippingQuote quote = null;
if (requiresShipping) {
// System.out.println("** Berfore default shipping quote **");
// Get all applicable shipping quotes
quote = orderFacade.getShippingQuote(customer, cart, order, store, language);
model.addAttribute("shippingQuote", quote);
}
if (quote != null) {
String shippingReturnCode = quote.getShippingReturnCode();
if (StringUtils.isBlank(shippingReturnCode) || shippingReturnCode.equals(ShippingQuote.NO_POSTAL_CODE)) {
if (order.getShippingSummary() == null) {
ShippingSummary summary = orderFacade.getShippingSummary(quote, store, language);
order.setShippingSummary(summary);
// TODO DTO
request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, summary);
}
if (order.getSelectedShippingOption() == null) {
order.setSelectedShippingOption(quote.getSelectedShippingOption());
}
// save quotes in HttpSession
List<ShippingOption> options = quote.getShippingOptions();
// TODO DTO
request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
if (!CollectionUtils.isEmpty(options)) {
for (ShippingOption shipOption : options) {
StringBuilder moduleName = new StringBuilder();
moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
String carrier = messages.getMessage(moduleName.toString(), locale);
String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
shipOption.setDescription(carrier);
shipOption.setNote(note);
// option name
if (!StringUtils.isBlank(shipOption.getOptionCode())) {
// try to get the translate
StringBuilder optionCodeBuilder = new StringBuilder();
try {
optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
shipOption.setOptionName(optionName);
} catch (Exception e) {
// label not found
LOGGER.warn("displayCheckout No shipping code found for " + optionCodeBuilder.toString());
}
}
}
}
}
if (quote.getDeliveryAddress() != null) {
ReadableCustomerDeliveryAddressPopulator addressPopulator = new ReadableCustomerDeliveryAddressPopulator();
addressPopulator.setCountryService(countryService);
addressPopulator.setZoneService(zoneService);
ReadableDelivery deliveryAddress = new ReadableDelivery();
addressPopulator.populate(quote.getDeliveryAddress(), deliveryAddress, store, language);
model.addAttribute("deliveryAddress", deliveryAddress);
super.setSessionAttribute(Constants.KEY_SESSION_ADDRESS, deliveryAddress, request);
}
// get shipping countries
List<Country> shippingCountriesList = orderFacade.getShipToCountry(store, language);
model.addAttribute("countries", shippingCountriesList);
} else {
// get all countries
List<Country> countries = countryService.getCountries(language);
model.addAttribute("countries", countries);
}
if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED)) {
LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
model.addAttribute("errorMessages", messages.getMessage(quote.getShippingReturnCode(), locale, quote.getShippingReturnCode()));
}
if (quote != null && !StringUtils.isBlank(quote.getQuoteError())) {
LOGGER.error("Shipping quote error " + quote.getQuoteError());
model.addAttribute("errorMessages", quote.getQuoteError());
}
if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY)) {
LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
model.addAttribute("errorMessages", quote.getShippingReturnCode());
}
/**
* end shipping *
*/
// get payment methods
List<PaymentMethod> paymentMethods = paymentService.getAcceptedPaymentMethods(store);
// not free and no payment methods
if (CollectionUtils.isEmpty(paymentMethods) && !freeShoppingCart) {
LOGGER.error("No payment method configured");
model.addAttribute("errorMessages", messages.getMessage("payment.not.configured", locale, "No payments configured"));
}
if (!CollectionUtils.isEmpty(paymentMethods)) {
// select default payment method
PaymentMethod defaultPaymentSelected = null;
for (PaymentMethod paymentMethod : paymentMethods) {
if (paymentMethod.isDefaultSelected()) {
defaultPaymentSelected = paymentMethod;
break;
}
}
if (defaultPaymentSelected == null) {
// forced default selection
defaultPaymentSelected = paymentMethods.get(0);
defaultPaymentSelected.setDefaultSelected(true);
}
order.setDefaultPaymentMethodCode(defaultPaymentSelected.getPaymentMethodCode());
}
// readable shopping cart items for order summary box
ShoppingCartData shoppingCart = shoppingCartFacade.getShoppingCartData(cart, language);
model.addAttribute("cart", shoppingCart);
order.setCartCode(shoppingCart.getCode());
// order total
OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
order.setOrderTotalSummary(orderTotalSummary);
// if order summary has to be re-used
super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
// display hacks
if (!StringUtils.isBlank(googleMapsKey)) {
model.addAttribute("fieldDisabled", "true");
model.addAttribute("cssClass", "");
} else {
model.addAttribute("fieldDisabled", "false");
model.addAttribute("cssClass", "required");
}
model.addAttribute("order", order);
model.addAttribute("paymentMethods", paymentMethods);
/**
* template *
*/
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
return template.toString();
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class ShoppingOrderController method calculateOrderTotal.
/**
* Calculates the order total following price variation like changing a shipping option
* @param order
* @param request
* @param response
* @param locale
* @return
* @throws Exception
*/
@RequestMapping(value = { "/calculateOrderTotal.json" }, method = RequestMethod.POST)
@ResponseBody
public ReadableShopOrder calculateOrderTotal(@ModelAttribute(value = "order") ShopOrder order, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
Language language = (Language) request.getAttribute("LANGUAGE");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
ReadableShopOrder readableOrder = new ReadableShopOrder();
try {
// re-generate cart
com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
ReadableShopOrderPopulator populator = new ReadableShopOrderPopulator();
populator.populate(order, readableOrder, store, language);
ReadableDelivery readableDelivery = super.getSessionAttribute(Constants.KEY_SESSION_ADDRESS, request);
if (order.getSelectedShippingOption() != null) {
ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute(Constants.SHIPPING_SUMMARY);
@SuppressWarnings("unchecked") List<ShippingOption> options = (List<ShippingOption>) request.getSession().getAttribute(Constants.SHIPPING_OPTIONS);
// for total calculation
order.setShippingSummary(summary);
ReadableShippingSummary readableSummary = new ReadableShippingSummary();
ReadableShippingSummaryPopulator readableSummaryPopulator = new ReadableShippingSummaryPopulator();
readableSummaryPopulator.setPricingService(pricingService);
readableSummaryPopulator.populate(summary, readableSummary, store, language);
// override summary
readableSummary.setDelivery(readableDelivery);
if (!CollectionUtils.isEmpty(options)) {
// get submitted shipping option
ShippingOption quoteOption = null;
ShippingOption selectedOption = order.getSelectedShippingOption();
// check if selectedOption exist
for (ShippingOption shipOption : options) {
StringBuilder moduleName = new StringBuilder();
moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
String carrier = messages.getMessage(moduleName.toString(), locale);
String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
shipOption.setNote(note);
shipOption.setDescription(carrier);
if (!StringUtils.isBlank(shipOption.getOptionId()) && shipOption.getOptionId().equals(selectedOption.getOptionId())) {
quoteOption = shipOption;
}
// option name
if (!StringUtils.isBlank(shipOption.getOptionCode())) {
// try to get the translate
StringBuilder optionCodeBuilder = new StringBuilder();
try {
// optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode()).append(".").append(shipOption.getOptionCode());
optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
shipOption.setOptionName(optionName);
} catch (Exception e) {
// label not found
LOGGER.warn("calculateOrderTotal No shipping code found for " + optionCodeBuilder.toString());
}
}
}
if (quoteOption == null) {
quoteOption = options.get(0);
}
readableSummary.setSelectedShippingOption(quoteOption);
readableSummary.setShippingOptions(options);
summary.setShippingOption(quoteOption.getOptionId());
summary.setShippingOptionCode(quoteOption.getOptionCode());
summary.setShipping(quoteOption.getOptionPrice());
// override with new summary
order.setShippingSummary(summary);
@SuppressWarnings("unchecked") Map<String, String> informations = (Map<String, String>) request.getSession().getAttribute("SHIPPING_INFORMATIONS");
readableSummary.setQuoteInformations(informations);
}
// TODO readable address format
readableOrder.setShippingSummary(readableSummary);
readableOrder.setDelivery(readableDelivery);
}
// set list of shopping cart items for core price calculation
List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(cart.getLineItems());
order.setShoppingCartItems(items);
order.setCartCode(shoppingCartCode);
// order total calculation
OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
ReadableOrderTotalPopulator totalPopulator = new ReadableOrderTotalPopulator();
totalPopulator.setMessages(messages);
totalPopulator.setPricingService(pricingService);
List<ReadableOrderTotal> subtotals = new ArrayList<ReadableOrderTotal>();
for (OrderTotal total : orderTotalSummary.getTotals()) {
if (total.getOrderTotalCode() == null || !total.getOrderTotalCode().equals("order.total.total")) {
ReadableOrderTotal t = new ReadableOrderTotal();
totalPopulator.populate(total, t, store, language);
subtotals.add(t);
} else {
// grand total
ReadableOrderTotal ot = new ReadableOrderTotal();
totalPopulator.populate(total, ot, store, language);
readableOrder.setGrandTotal(ot.getTotal());
}
}
readableOrder.setSubTotals(subtotals);
} catch (Exception e) {
LOGGER.error("Error while getting shipping quotes", e);
readableOrder.setErrorMessage(messages.getMessage("message.error", locale));
}
return readableOrder;
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class CustomShippingQuoteRules method getShippingQuotes.
@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote quote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
Validate.notNull(delivery, "Delivery cannot be null");
Validate.notNull(delivery.getCountry(), "Delivery.country cannot be null");
Validate.notNull(packages, "packages cannot be null");
Validate.notEmpty(packages, "packages cannot be empty");
// requires the postal code
if (StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
Double distance = null;
if (quote != null) {
// look if distance has been calculated
if (quote.getQuoteInformations() != null) {
if (quote.getQuoteInformations().containsKey(Constants.DISTANCE_KEY)) {
distance = (Double) quote.getQuoteInformations().get(Constants.DISTANCE_KEY);
}
}
}
// calculate volume (L x W x H)
Double volume = null;
Double weight = 0D;
Double size = null;
// calculate weight
for (PackageDetails pack : packages) {
weight = weight + pack.getShippingWeight();
Double tmpVolume = pack.getShippingHeight() * pack.getShippingLength() * pack.getShippingWidth();
if (volume == null || tmpVolume > volume) {
// take the largest volume
volume = tmpVolume;
}
// largest size
List<Double> sizeList = new ArrayList<Double>();
sizeList.add(pack.getShippingHeight());
sizeList.add(pack.getShippingWidth());
sizeList.add(pack.getShippingLength());
Double maxSize = Collections.max(sizeList);
if (size == null || maxSize > size) {
size = maxSize;
}
}
// Build a ShippingInputParameters
ShippingInputParameters inputParameters = new ShippingInputParameters();
inputParameters.setWeight((long) weight.doubleValue());
inputParameters.setCountry(delivery.getCountry().getIsoCode());
inputParameters.setProvince("*");
inputParameters.setModuleName(module.getCode());
if (delivery.getZone() != null && delivery.getZone().getCode() != null) {
inputParameters.setProvince(delivery.getZone().getCode());
}
if (distance != null) {
double ddistance = distance;
long ldistance = (long) ddistance;
inputParameters.setDistance(ldistance);
}
if (volume != null) {
inputParameters.setVolume((long) volume.doubleValue());
}
List<ShippingOption> options = quote.getShippingOptions();
if (options == null) {
options = new ArrayList<ShippingOption>();
quote.setShippingOptions(options);
}
LOGGER.debug("Setting input parameters " + inputParameters.toString());
KieSession kieSession = droolsBeanFactory.getKieSession(ResourceFactory.newClassPathResource("com/salesmanager/drools/rules/PriceByDistance.drl"));
DecisionResponse resp = new DecisionResponse();
kieSession.insert(inputParameters);
kieSession.setGlobal("decision", resp);
kieSession.fireAllRules();
if (resp.getCustomPrice() != null) {
ShippingOption shippingOption = new ShippingOption();
shippingOption.setOptionPrice(new BigDecimal(resp.getCustomPrice()));
shippingOption.setShippingModuleCode(MODULE_CODE);
shippingOption.setOptionCode(MODULE_CODE);
shippingOption.setOptionId(MODULE_CODE);
options.add(shippingOption);
}
return options;
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class StorePickupShippingQuote method prePostProcessShippingQuotes.
@Override
public void prePostProcessShippingQuotes(ShippingQuote quote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration globalShippingConfiguration, IntegrationModule currentModule, ShippingConfiguration shippingConfiguration, List<IntegrationModule> allModules, Locale locale) throws IntegrationException {
Validate.notNull(globalShippingConfiguration, "IntegrationConfiguration must not be null for StorePickUp");
try {
if (!globalShippingConfiguration.isActive())
return;
String region = null;
String price = globalShippingConfiguration.getIntegrationKeys().get("price");
if (delivery.getZone() != null) {
region = delivery.getZone().getCode();
} else {
region = delivery.getState();
}
ShippingOption shippingOption = new ShippingOption();
shippingOption.setShippingModuleCode(MODULE_CODE);
shippingOption.setOptionCode(MODULE_CODE);
shippingOption.setOptionId(new StringBuilder().append(MODULE_CODE).append("_").append(region).toString());
shippingOption.setOptionPrice(productPriceUtils.getAmount(price));
shippingOption.setOptionPriceText(productPriceUtils.getStoreFormatedAmountWithCurrency(store, productPriceUtils.getAmount(price)));
List<ShippingOption> options = quote.getShippingOptions();
if (options == null) {
options = new ArrayList<ShippingOption>();
quote.setShippingOptions(options);
}
options.add(shippingOption);
if (quote.getSelectedShippingOption() == null) {
quote.setSelectedShippingOption(shippingOption);
}
} catch (Exception e) {
throw new IntegrationException(e);
}
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class USPSParsedElements method getShippingQuotes.
@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
if (packages == null) {
return null;
}
if (StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
// only applies to Canada and US
/* Country country = delivery.getCountry();
if(!country.getIsoCode().equals("US") || !country.getIsoCode().equals("US")){
throw new IntegrationException("USPS Not configured for shipping in country " + country.getIsoCode());
}*/
// supports en and fr
String language = locale.getLanguage();
if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
language = Locale.ENGLISH.getLanguage();
}
// if store is not CAD /** maintained in the currency **/
/* if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) {
total = CurrencyUtil.convertToCurrency(total, store.getCurrency(),
Constants.CURRENCY_CODE_CAD);
}*/
Language lang = store.getDefaultLanguage();
HttpGet httpget = null;
Reader xmlreader = null;
String pack = configuration.getIntegrationOptions().get("packages").get(0);
try {
Map<String, Country> countries = countryService.getCountriesMap(lang);
Country destination = countries.get(delivery.getCountry().getIsoCode());
Map<String, String> keys = configuration.getIntegrationKeys();
if (keys == null || StringUtils.isBlank(keys.get("account"))) {
// TODO can we return null
return null;
}
String host = null;
String protocol = null;
String port = null;
String url = null;
// against which environment are we using the service
String env = configuration.getEnvironment();
// must be US
if (!store.getCountry().getIsoCode().equals("US")) {
throw new IntegrationException("Can't use the service for store country code ");
}
Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
for (String key : moduleConfigsMap.keySet()) {
ModuleConfig moduleConfig = moduleConfigsMap.get(key);
if (moduleConfig.getEnv().equals(env)) {
host = moduleConfig.getHost();
protocol = moduleConfig.getScheme();
port = moduleConfig.getPort();
url = moduleConfig.getUri();
}
}
StringBuilder xmlheader = new StringBuilder();
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmlheader.append("<RateV3Request USERID=\"").append(keys.get("account")).append("\">");
} else {
xmlheader.append("<IntlRateRequest USERID=\"").append(keys.get("account")).append("\">");
}
StringBuilder xmldatabuffer = new StringBuilder();
double totalW = 0;
double totalH = 0;
double totalL = 0;
double totalG = 0;
double totalP = 0;
for (PackageDetails detail : packages) {
// need size in inch
double w = DataUtils.getMeasure(detail.getShippingWidth(), store, MeasureUnit.IN.name());
double h = DataUtils.getMeasure(detail.getShippingHeight(), store, MeasureUnit.IN.name());
double l = DataUtils.getMeasure(detail.getShippingLength(), store, MeasureUnit.IN.name());
totalW = totalW + w;
totalH = totalH + h;
totalL = totalL + l;
// Girth = Length + (Width x 2) + (Height x 2)
double girth = l + (w * 2) + (h * 2);
totalG = totalG + girth;
// need weight in pounds
double p = DataUtils.getWeight(detail.getShippingWeight(), store, MeasureUnit.LB.name());
totalP = totalP + p;
}
/* BigDecimal convertedOrderTotal = CurrencyUtil.convertToCurrency(
orderTotal, store.getCurrency(),
Constants.CURRENCY_CODE_USD);*/
// calculate total shipping volume
// ship date is 3 days from here
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 3);
Date newDate = c.getTime();
SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
String shipDate = format.format(newDate);
int i = 1;
// need pounds and ounces
int pounds = (int) totalP;
String ouncesString = String.valueOf(totalP - pounds);
int ouncesIndex = ouncesString.indexOf(".");
String ounces = "00";
if (ouncesIndex > -1) {
ounces = ouncesString.substring(ouncesIndex + 1);
}
String size = "REGULAR";
if (totalL + totalG <= 64) {
size = "REGULAR";
} else if (totalL + totalG <= 108) {
size = "LARGE";
} else {
size = "OVERSIZE";
}
/**
* Domestic <Package ID="1ST"> <Service>ALL</Service>
* <ZipOrigination>90210</ZipOrigination>
* <ZipDestination>96698</ZipDestination> <Pounds>8</Pounds>
* <Ounces>32</Ounces> <Container/> <Size>REGULAR</Size>
* <Machinable>true</Machinable> </Package>
*
* //MAXWEIGHT=70 lbs
*
* //domestic container default=VARIABLE whiteSpace=collapse
* enumeration=VARIABLE enumeration=FLAT RATE BOX enumeration=FLAT
* RATE ENVELOPE enumeration=LG FLAT RATE BOX
* enumeration=RECTANGULAR enumeration=NONRECTANGULAR
*
* //INTL enumeration=Package enumeration=Postcards or aerogrammes
* enumeration=Matter for the blind enumeration=Envelope
*
* Size May be left blank in situations that do not Size. Defined as
* follows: REGULAR: package plus girth is 84 inches or less; LARGE:
* package length plus girth measure more than 84 inches not more
* than 108 inches; OVERSIZE: package length plus girth is more than
* 108 but not 130 inches. For example: <Size>REGULAR</Size>
*
* International <Package ID="1ST"> <Machinable>true</Machinable>
* <MailType>Envelope</MailType> <Country>Canada</Country>
* <Length>0</Length> <Width>0</Width> <Height>0</Height>
* <ValueOfContents>250</ValueOfContents> </Package>
*
* <Package ID="2ND"> <Pounds>4</Pounds> <Ounces>3</Ounces>
* <MailType>Package</MailType> <GXG> <Length>46</Length>
* <Width>14</Width> <Height>15</Height> <POBoxFlag>N</POBoxFlag>
* <GiftFlag>N</GiftFlag> </GXG>
* <ValueOfContents>250</ValueOfContents> <Country>Japan</Country>
* </Package>
*/
xmldatabuffer.append("<Package ID=\"").append(i).append("\">");
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmldatabuffer.append("<Service>");
xmldatabuffer.append("ALL");
xmldatabuffer.append("</Service>");
xmldatabuffer.append("<ZipOrigination>");
xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
xmldatabuffer.append("</ZipOrigination>");
xmldatabuffer.append("<ZipDestination>");
xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
xmldatabuffer.append("</ZipDestination>");
xmldatabuffer.append("<Pounds>");
xmldatabuffer.append(pounds);
xmldatabuffer.append("</Pounds>");
xmldatabuffer.append("<Ounces>");
xmldatabuffer.append(ounces);
xmldatabuffer.append("</Ounces>");
xmldatabuffer.append("<Container>");
xmldatabuffer.append(pack);
xmldatabuffer.append("</Container>");
xmldatabuffer.append("<Size>");
xmldatabuffer.append(size);
xmldatabuffer.append("</Size>");
// TODO must be changed if not machinable
xmldatabuffer.append("<Machinable>true</Machinable>");
xmldatabuffer.append("<ShipDate>");
xmldatabuffer.append(shipDate);
xmldatabuffer.append("</ShipDate>");
} else {
// if international
xmldatabuffer.append("<Pounds>");
xmldatabuffer.append(pounds);
xmldatabuffer.append("</Pounds>");
xmldatabuffer.append("<Ounces>");
xmldatabuffer.append(ounces);
xmldatabuffer.append("</Ounces>");
xmldatabuffer.append("<MailType>");
xmldatabuffer.append(pack);
xmldatabuffer.append("</MailType>");
xmldatabuffer.append("<ValueOfContents>");
xmldatabuffer.append(productPriceUtils.getAdminFormatedAmount(store, orderTotal));
xmldatabuffer.append("</ValueOfContents>");
xmldatabuffer.append("<Country>");
xmldatabuffer.append(destination.getName());
xmldatabuffer.append("</Country>");
}
// if international & CXG
/*
* xmldatabuffer.append("<CXG>"); xmldatabuffer.append("<Length>");
* xmldatabuffer.append(""); xmldatabuffer.append("</Length>");
* xmldatabuffer.append("<Width>"); xmldatabuffer.append("");
* xmldatabuffer.append("</Width>");
* xmldatabuffer.append("<Height>"); xmldatabuffer.append("");
* xmldatabuffer.append("</Height>");
* xmldatabuffer.append("<POBoxFlag>"); xmldatabuffer.append("");
* xmldatabuffer.append("</POBoxFlag>");
* xmldatabuffer.append("<GiftFlag>"); xmldatabuffer.append("");
* xmldatabuffer.append("</GiftFlag>");
* xmldatabuffer.append("</CXG>");
*/
/*
* xmldatabuffer.append("<Width>"); xmldatabuffer.append(totalW);
* xmldatabuffer.append("</Width>");
* xmldatabuffer.append("<Length>"); xmldatabuffer.append(totalL);
* xmldatabuffer.append("</Length>");
* xmldatabuffer.append("<Height>"); xmldatabuffer.append(totalH);
* xmldatabuffer.append("</Height>");
* xmldatabuffer.append("<Girth>"); xmldatabuffer.append(totalG);
* xmldatabuffer.append("</Girth>");
*/
xmldatabuffer.append("</Package>");
String xmlfooter = "</RateV3Request>";
if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
xmlfooter = "</IntlRateRequest>";
}
StringBuilder xmlbuffer = new StringBuilder().append(xmlheader.toString()).append(xmldatabuffer.toString()).append(xmlfooter);
LOGGER.debug("USPS QUOTE REQUEST " + xmlbuffer.toString());
// HttpClient client = new HttpClient();
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
@SuppressWarnings("deprecation") String encoded = java.net.URLEncoder.encode(xmlbuffer.toString());
String completeUri = url + "?API=RateV3&XML=" + encoded;
if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
completeUri = url + "?API=IntlRate&XML=" + encoded;
}
// ?API=RateV3
httpget = new HttpGet(protocol + "://" + host + ":" + port + completeUri);
// RequestEntity entity = new
// StringRequestEntity(xmlbuffer.toString(),"text/plain","UTF-8");
// httpget.setRequestEntity(entity);
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
LOGGER.error("Communication Error with ups quote " + status);
throw new ClientProtocolException("UPS quote communication error " + status);
}
};
String data = httpclient.execute(httpget, responseHandler);
/* int result = client.executeMethod(httpget);
if (result != 200) {
LOGGER.error("Communication Error with usps quote " + result + " "
+ protocol + "://" + host + ":" + port + url);
throw new Exception("USPS quote communication error " + result);
}*/
// data = httpget.getResponseBodyAsString();
LOGGER.debug("usps quote response " + data);
USPSParsedElements parsed = new USPSParsedElements();
/**
* <RateV3Response> <Package ID="1ST">
* <ZipOrigination>44106</ZipOrigination>
* <ZipDestination>20770</ZipDestination>
*/
Digester digester = new Digester();
digester.push(parsed);
if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
digester.addCallMethod("Error/Description", "setError", 0);
digester.addCallMethod("RateV3Response/Package/Error/Description", "setError", 0);
digester.addObjectCreate("RateV3Response/Package/Postage", ShippingOption.class);
digester.addSetProperties("RateV3Response/Package/Postage", "CLASSID", "optionId");
digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionName", 0);
digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionCode", 0);
digester.addCallMethod("RateV3Response/Package/Postage/Rate", "setOptionPriceText", 0);
// digester
// .addCallMethod(
// "RateV3Response/Package/Postage/Commitment/CommitmentDate",
// "estimatedNumberOfDays", 0);
digester.addSetNext("RateV3Response/Package/Postage", "addOption");
} else {
digester.addCallMethod("Error/Description", "setError", 0);
digester.addCallMethod("IntlRateResponse/Package/Error/Description", "setError", 0);
digester.addObjectCreate("IntlRateResponse/Package/Service", ShippingOption.class);
digester.addSetProperties("IntlRateResponse/Package/Service", "ID", "optionId");
digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionName", 0);
digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionCode", 0);
digester.addCallMethod("IntlRateResponse/Package/Service/Postage", "setOptionPriceText", 0);
// digester.addCallMethod(
// "IntlRateResponse/Package/Service/SvcCommitments",
// "setEstimatedNumberOfDays", 0);
digester.addSetNext("IntlRateResponse/Package/Service", "addOption");
}
// <?xml
// version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
// Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
// XML document is well formed but the document is not
// valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>
// <?xml version="1.0"?>
// <IntlRateResponse><Package ID="1"><Error><Number>-2147218046</Number>
// <Source>IntlPostage;clsIntlPostage.GetCountryAndRestirctedServiceId;clsIntlPostage.CalcAllPostageDimensionsXML;IntlRate.ProcessRequest</Source>
// <Description>Invalid Country Name</Description><HelpFile></HelpFile><HelpContext>1000440</HelpContext></Error></Package></IntlRateResponse>
xmlreader = new StringReader(data);
digester.parse(xmlreader);
if (!StringUtils.isBlank(parsed.getError())) {
LOGGER.error("Can't process USPS message= " + parsed.getError());
throw new IntegrationException(parsed.getError());
}
if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
LOGGER.error("Can't process USPS statusCode=" + parsed.getStatusCode() + " message= " + parsed.getError());
throw new IntegrationException(parsed.getError());
}
if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
LOGGER.warn("No options returned from USPS");
throw new IntegrationException(parsed.getError());
}
/* String carrier = getShippingMethodDescription(locale);
// cost is in USD, need to do conversion
MerchantConfiguration rtdetails = config
.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
if (rtdetails != null) {
if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
// or
// not
// quotes
try {
displayQuoteDeliveryTime = Integer.parseInt(rtdetails
.getConfigurationValue1());
} catch (Exception e) {
log.error("Display quote is not an integer value ["
+ rtdetails.getConfigurationValue1() + "]");
}
}
}
LabelUtil labelUtil = LabelUtil.getInstance();*/
// Map serviceMap =
// com.salesmanager.core.util.ShippingUtil.buildServiceMap("usps",locale);
@SuppressWarnings("unchecked") List<ShippingOption> shippingOptions = parsed.getOptions();
return shippingOptions;
}
} catch (Exception e1) {
LOGGER.error("Error in USPS shipping quote ", e1);
throw new IntegrationException(e1);
} finally {
if (xmlreader != null) {
try {
xmlreader.close();
} catch (Exception ignore) {
}
}
if (httpget != null) {
httpget.releaseConnection();
}
}
}
Aggregations