use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class ShippingServiceImpl method getShippingQuote.
@Override
public ShippingQuote getShippingQuote(Long shoppingCartId, MerchantStore store, Delivery delivery, List<ShippingProduct> products, Language language) throws ServiceException {
// ShippingConfiguration -> Global configuration of a given store
// IntegrationConfiguration -> Configuration of a given module
// IntegrationModule -> The concrete module as defined in integrationmodules.properties
// delivery without postal code is accepted
Validate.notNull(store, "MerchantStore must not be null");
Validate.notNull(delivery, "Delivery must not be null");
Validate.notEmpty(products, "products must not be empty");
Validate.notNull(language, "Language must not be null");
ShippingQuote shippingQuote = new ShippingQuote();
ShippingQuoteModule shippingQuoteModule = null;
try {
if (StringUtils.isBlank(delivery.getPostalCode())) {
shippingQuote.getWarnings().add("No postal code in delivery address");
shippingQuote.setShippingReturnCode(ShippingQuote.NO_POSTAL_CODE);
}
// get configuration
ShippingConfiguration shippingConfiguration = getShippingConfiguration(store);
ShippingType shippingType = ShippingType.INTERNATIONAL;
/**
* get shipping origin *
*/
ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store);
if (shippingOrigin == null || !shippingOrigin.isActive()) {
shippingOrigin = new ShippingOrigin();
shippingOrigin.setAddress(store.getStoreaddress());
shippingOrigin.setCity(store.getStorecity());
shippingOrigin.setCountry(store.getCountry());
shippingOrigin.setPostalCode(store.getStorepostalcode());
shippingOrigin.setState(store.getStorestateprovince());
shippingOrigin.setZone(store.getZone());
}
if (shippingConfiguration == null) {
shippingConfiguration = new ShippingConfiguration();
}
if (shippingConfiguration.getShippingType() != null) {
shippingType = shippingConfiguration.getShippingType();
}
// look if customer country code excluded
Country shipCountry = delivery.getCountry();
// a ship to country is required
Validate.notNull(shipCountry, "Ship to Country cannot be null");
Validate.notNull(store.getCountry(), "Store Country canot be null");
if (shippingType.name().equals(ShippingType.NATIONAL.name())) {
// customer country must match store country
if (!shipCountry.getIsoCode().equals(store.getCountry().getIsoCode())) {
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
return shippingQuote;
}
} else if (shippingType.name().equals(ShippingType.INTERNATIONAL.name())) {
// customer shipping country code must be in accepted list
List<String> supportedCountries = this.getSupportedCountries(store);
if (!supportedCountries.contains(shipCountry.getIsoCode())) {
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
return shippingQuote;
}
}
// must have a shipping module configured
Map<String, IntegrationConfiguration> modules = this.getShippingModulesConfigured(store);
if (modules == null) {
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
return shippingQuote;
}
/**
* uses this module name *
*/
String moduleName = null;
IntegrationConfiguration configuration = null;
for (String module : modules.keySet()) {
moduleName = module;
configuration = modules.get(module);
// use the first active module
if (configuration.isActive()) {
shippingQuoteModule = shippingModules.get(module);
if (shippingQuoteModule instanceof ShippingQuotePrePostProcessModule) {
shippingQuoteModule = null;
continue;
} else {
break;
}
}
}
if (shippingQuoteModule == null) {
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
return shippingQuote;
}
/**
* merchant module configs *
*/
List<IntegrationModule> shippingMethods = this.getShippingMethods(store);
IntegrationModule shippingModule = null;
for (IntegrationModule mod : shippingMethods) {
if (mod.getCode().equals(moduleName)) {
shippingModule = mod;
break;
}
}
/**
* general module configs *
*/
if (shippingModule == null) {
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
return shippingQuote;
}
// calculate order total
BigDecimal orderTotal = calculateOrderTotal(products, store);
List<PackageDetails> packages = getPackagesDetails(products, store);
// free shipping ?
boolean freeShipping = false;
if (shippingConfiguration.isFreeShippingEnabled()) {
BigDecimal freeShippingAmount = shippingConfiguration.getOrderTotalFreeShipping();
if (freeShippingAmount != null) {
if (orderTotal.doubleValue() > freeShippingAmount.doubleValue()) {
if (shippingConfiguration.getFreeShippingType() == ShippingType.NATIONAL) {
if (store.getCountry().getIsoCode().equals(shipCountry.getIsoCode())) {
freeShipping = true;
shippingQuote.setFreeShipping(true);
shippingQuote.setFreeShippingAmount(freeShippingAmount);
return shippingQuote;
}
} else {
// international all
freeShipping = true;
shippingQuote.setFreeShipping(true);
shippingQuote.setFreeShippingAmount(freeShippingAmount);
return shippingQuote;
}
}
}
}
// handling fees
BigDecimal handlingFees = shippingConfiguration.getHandlingFees();
if (handlingFees != null) {
shippingQuote.setHandlingFees(handlingFees);
}
// tax basis
shippingQuote.setApplyTaxOnShipping(shippingConfiguration.isTaxOnShipping());
Locale locale = languageService.toLocale(language, store);
// also available distance calculation
if (!CollectionUtils.isEmpty(shippingModulePreProcessors)) {
for (ShippingQuotePrePostProcessModule preProcessor : shippingModulePreProcessors) {
// System.out.println("Using pre-processor " + preProcessor.getModuleCode());
preProcessor.prePostProcessShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, configuration, shippingModule, shippingConfiguration, shippingMethods, locale);
// TODO switch module if required
if (shippingQuote.getCurrentShippingModule() != null && !shippingQuote.getCurrentShippingModule().getCode().equals(shippingModule.getCode())) {
// determines the shipping module
shippingModule = shippingQuote.getCurrentShippingModule();
configuration = modules.get(shippingModule.getCode());
if (configuration != null) {
if (configuration.isActive()) {
moduleName = shippingModule.getCode();
shippingQuoteModule = this.shippingModules.get(shippingModule.getCode());
configuration = modules.get(shippingModule.getCode());
}
// TODO use default
}
}
}
}
// invoke module
List<ShippingOption> shippingOptions = null;
try {
shippingOptions = shippingQuoteModule.getShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, configuration, shippingModule, shippingConfiguration, locale);
} catch (Exception e) {
LOGGER.error("Error while calculating shipping : " + e.getMessage(), e);
/* merchantLogService.save(
new MerchantLog(store,
"Can't process " + shippingModule.getModule()
+ " -> "
+ e.getMessage()));
shippingQuote.setQuoteError(e.getMessage());
shippingQuote.setShippingReturnCode(ShippingQuote.ERROR);
return shippingQuote;*/
}
if (shippingOptions == null && !StringUtils.isBlank(delivery.getPostalCode())) {
// absolutely need to use in this case store pickup or other default shipping quote
shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY);
}
shippingQuote.setShippingModuleCode(moduleName);
// filter shipping options
ShippingOptionPriceType shippingOptionPriceType = shippingConfiguration.getShippingOptionPriceType();
ShippingOption selectedOption = null;
if (shippingOptions != null) {
for (ShippingOption option : shippingOptions) {
if (selectedOption == null) {
selectedOption = option;
}
// set price text
String priceText = pricingService.getDisplayAmount(option.getOptionPrice(), store);
option.setOptionPriceText(priceText);
option.setShippingModuleCode(moduleName);
if (StringUtils.isBlank(option.getOptionName())) {
String countryName = delivery.getCountry().getName();
if (countryName == null) {
Map<String, Country> deliveryCountries = countryService.getCountriesMap(language);
Country dCountry = deliveryCountries.get(delivery.getCountry().getIsoCode());
if (dCountry != null) {
countryName = dCountry.getName();
} else {
countryName = delivery.getCountry().getIsoCode();
}
}
option.setOptionName(countryName);
}
if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.HIGHEST.name())) {
if (option.getOptionPrice().longValue() > selectedOption.getOptionPrice().longValue()) {
selectedOption = option;
}
}
if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.LEAST.name())) {
if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
selectedOption = option;
}
}
if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {
if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
selectedOption = option;
}
}
}
shippingQuote.setSelectedShippingOption(selectedOption);
if (selectedOption != null && !shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {
shippingOptions = new ArrayList<ShippingOption>();
shippingOptions.add(selectedOption);
}
}
/**
* set final delivery address *
*/
shippingQuote.setDeliveryAddress(delivery);
shippingQuote.setShippingOptions(shippingOptions);
// invoke pre processors
if (!CollectionUtils.isEmpty(shippingModulePostProcessors)) {
for (ShippingQuotePrePostProcessModule postProcessor : shippingModulePostProcessors) {
// get module info
// get module configuration
IntegrationConfiguration integrationConfiguration = modules.get(postProcessor.getModuleCode());
IntegrationModule postProcessModule = null;
for (IntegrationModule mod : shippingMethods) {
if (mod.getCode().equals(postProcessor.getModuleCode())) {
postProcessModule = mod;
break;
}
}
IntegrationModule module = postProcessModule;
if (integrationConfiguration != null) {
postProcessor.prePostProcessShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, integrationConfiguration, module, shippingConfiguration, shippingMethods, locale);
}
}
}
String ipAddress = null;
UserContext context = UserContext.getCurrentInstance();
if (context != null) {
ipAddress = context.getIpAddress();
}
if (shippingQuote != null && CollectionUtils.isNotEmpty(shippingQuote.getShippingOptions())) {
// save SHIPPING OPTIONS
List<ShippingOption> finalShippingOptions = shippingQuote.getShippingOptions();
for (ShippingOption option : finalShippingOptions) {
// transform to Quote
Quote q = new Quote();
q.setCartId(shoppingCartId);
q.setDelivery(delivery);
if (!StringUtils.isBlank(ipAddress)) {
q.setIpAddress(ipAddress);
}
if (!StringUtils.isBlank(option.getEstimatedNumberOfDays())) {
try {
q.setEstimatedNumberOfDays(Integer.valueOf(option.getEstimatedNumberOfDays()));
} catch (Exception e) {
LOGGER.error("Cannot cast to integer " + option.getEstimatedNumberOfDays());
}
}
if (freeShipping) {
q.setFreeShipping(true);
q.setPrice(new BigDecimal(0));
q.setModule("FREE");
q.setOptionCode("FREE");
q.setOptionName("FREE");
} else {
q.setModule(option.getShippingModuleCode());
q.setOptionCode(option.getOptionCode());
if (!StringUtils.isBlank(option.getOptionDeliveryDate())) {
try {
q.setOptionDeliveryDate(DateUtil.formatDate(option.getOptionDeliveryDate()));
} catch (Exception e) {
LOGGER.error("Cannot transform to date " + option.getOptionDeliveryDate());
}
}
q.setOptionName(option.getOptionName());
q.setOptionShippingDate(new Date());
q.setPrice(option.getOptionPrice());
}
if (handlingFees != null) {
q.setHandling(handlingFees);
}
q.setQuoteDate(new Date());
shippingQuoteService.save(q);
option.setShippingQuoteOptionId(q.getId());
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new ServiceException(e);
}
return shippingQuote;
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class OrderShippingApi method shipping.
/**
* Get shipping quote for a given shopping cart
*
* @param id
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = { "/auth/cart/{code}/shipping" }, method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableShippingSummary shipping(@PathVariable final String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) {
try {
Locale locale = request.getLocale();
Principal principal = request.getUserPrincipal();
String userName = principal.getName();
// get customer id
Customer customer = customerService.getByNick(userName);
if (customer == null) {
response.sendError(503, "Error while getting user details to calculate shipping quote");
}
ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(code, merchantStore);
if (cart == null) {
response.sendError(404, "Cart code " + code + " does not exist");
}
if (cart.getCustomerId() == null) {
response.sendError(404, "Cart code " + code + " does not exist for exist for user " + userName);
}
if (cart.getCustomerId().longValue() != customer.getId().longValue()) {
response.sendError(404, "Cart code " + code + " does not exist for exist for user " + userName);
}
ShippingQuote quote = orderFacade.getShippingQuote(customer, cart, merchantStore, language);
ShippingSummary summary = orderFacade.getShippingSummary(quote, merchantStore, language);
ReadableShippingSummary shippingSummary = new ReadableShippingSummary();
ReadableShippingSummaryPopulator populator = new ReadableShippingSummaryPopulator();
populator.setPricingService(pricingService);
populator.populate(summary, shippingSummary, merchantStore, language);
List<ShippingOption> options = quote.getShippingOptions();
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(), new String[] { merchantStore.getStorename() }, 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("No shipping code found for " + optionCodeBuilder.toString());
}
}
}
shippingSummary.setShippingOptions(options);
}
return shippingSummary;
} catch (Exception e) {
LOGGER.error("Error while getting shipping quote", e);
try {
response.sendError(503, "Error while getting shipping quote" + e.getMessage());
} catch (Exception ignore) {
}
return null;
}
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class OrderShippingApi method shipping.
/**
* Get shipping quote based on postal code
* @param code
* @param address
* @param merchantStore
* @param language
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = { "/cart/{code}/shipping" }, method = RequestMethod.POST)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableShippingSummary shipping(@PathVariable final String code, @RequestBody AddressLocation address, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
Locale locale = request.getLocale();
ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(code, merchantStore);
if (cart == null) {
response.sendError(404, "Cart id " + code + " does not exist");
}
Delivery addr = new Delivery();
addr.setPostalCode(address.getPostalCode());
Country c = countryService.getByCode(address.getCountryCode());
if (c == null) {
c = merchantStore.getCountry();
}
addr.setCountry(c);
Customer temp = new Customer();
temp.setAnonymous(true);
temp.setDelivery(addr);
ShippingQuote quote = orderFacade.getShippingQuote(temp, cart, merchantStore, language);
ShippingSummary summary = orderFacade.getShippingSummary(quote, merchantStore, language);
ReadableShippingSummary shippingSummary = new ReadableShippingSummary();
ReadableShippingSummaryPopulator populator = new ReadableShippingSummaryPopulator();
populator.setPricingService(pricingService);
populator.populate(summary, shippingSummary, merchantStore, language);
List<ShippingOption> options = quote.getShippingOptions();
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(), new String[] { merchantStore.getStorename() }, 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(), new String[] { merchantStore.getStorename() }, locale);
shipOption.setOptionName(optionName);
} catch (Exception e) {
// label not found
LOGGER.warn("No shipping code found for " + optionCodeBuilder.toString());
}
}
}
shippingSummary.setShippingOptions(options);
}
return shippingSummary;
} catch (Exception e) {
LOGGER.error("Error while getting shipping quote", e);
try {
response.sendError(503, "Error while getting shipping quote" + e.getMessage());
} catch (Exception ignore) {
}
return null;
}
}
use of com.salesmanager.core.model.shipping.ShippingOption in project shopizer by shopizer-ecommerce.
the class PriceByDistanceShippingQuoteRules 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;
// look if distance has been calculated
if (Objects.nonNull(quote) && Objects.nonNull(quote.getQuoteInformations())) {
if (quote.getQuoteInformations().containsKey(Constants.DISTANCE_KEY)) {
distance = (Double) quote.getQuoteInformations().get(Constants.DISTANCE_KEY);
}
}
if (distance == null) {
return null;
}
// maximum distance TODO configure from admin
if (distance > 150D) {
return null;
}
List<ShippingOption> options = quote.getShippingOptions();
if (options == null) {
options = new ArrayList<>();
quote.setShippingOptions(options);
}
BigDecimal price = null;
if (distance <= 20) {
// TODO from the admin
price = new BigDecimal(2);
} else {
// TODO from the admin
price = new BigDecimal(3);
}
BigDecimal total = new BigDecimal(distance).multiply(price);
if (distance < 1) {
// minimum 1 unit
distance = 1D;
}
ShippingOption shippingOption = new ShippingOption();
shippingOption.setOptionPrice(total);
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 UPSParsedElements 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 {
Validate.notNull(configuration, "IntegrationConfiguration must not be null for USPS shipping module");
if (StringUtils.isBlank(delivery.getPostalCode())) {
return null;
}
BigDecimal total = orderTotal;
if (packages == null) {
return null;
}
List<ShippingOption> options = null;
// only applies to Canada and US
Country country = delivery.getCountry();
if (!(country.getIsoCode().equals("US") || country.getIsoCode().equals("CA"))) {
return null;
// throw new IntegrationException("UPS 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();
}
String pack = configuration.getIntegrationOptions().get("packages").get(0);
Map<String, String> keys = configuration.getIntegrationKeys();
String accessKey = keys.get("accessKey");
String userId = keys.get("userId");
String password = keys.get("password");
String host = null;
String protocol = null;
String port = null;
String url = null;
StringBuilder xmlbuffer = new StringBuilder();
HttpPost httppost = null;
BufferedReader reader = null;
try {
String env = configuration.getEnvironment();
Set<String> regions = module.getRegionsSet();
if (!regions.contains(store.getCountry().getIsoCode())) {
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 xmlreqbuffer = new StringBuilder();
xmlreqbuffer.append("<?xml version=\"1.0\"?>");
xmlreqbuffer.append("<AccessRequest>");
xmlreqbuffer.append("<AccessLicenseNumber>");
xmlreqbuffer.append(accessKey);
xmlreqbuffer.append("</AccessLicenseNumber>");
xmlreqbuffer.append("<UserId>");
xmlreqbuffer.append(userId);
xmlreqbuffer.append("</UserId>");
xmlreqbuffer.append("<Password>");
xmlreqbuffer.append(password);
xmlreqbuffer.append("</Password>");
xmlreqbuffer.append("</AccessRequest>");
String xmlhead = xmlreqbuffer.toString();
String weightCode = store.getWeightunitcode();
String measureCode = store.getSeizeunitcode();
if (weightCode.equals("KG")) {
weightCode = "KGS";
} else {
weightCode = "LBS";
}
String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>Shopizer</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>";
StringBuilder xmldatabuffer = new StringBuilder();
/**
* <Shipment>
*
* <Shipper> <Address> <City></City>
* <StateProvinceCode>QC</StateProvinceCode>
* <CountryCode>CA</CountryCode> <PostalCode></PostalCode>
* </Address> </Shipper>
*
* <ShipTo> <Address> <City>Redwood Shores</City>
* <StateProvinceCode>CA</StateProvinceCode>
* <CountryCode>US</CountryCode> <PostalCode></PostalCode>
* <ResidentialAddressIndicator/> </Address> </ShipTo>
*
* <Package> <PackagingType> <Code>21</Code> </PackagingType>
* <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code>
* </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight>
* <PackageServiceOptions> <InsuredValue>
* <CurrencyCode>CAD</CurrencyCode>
* <MonetaryValue>100</MonetaryValue> </InsuredValue>
* </PackageServiceOptions> </Package>
*
* </Shipment>
*
* <CustomerClassification> <Code>03</Code>
* </CustomerClassification> </RatingServiceSelectionRequest>
* *
*/
/**
*Map countriesMap = (Map) RefCache.getAllcountriesmap(LanguageUtil
* .getLanguageNumberCode(locale.getLanguage()));
* Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil
* .getLanguageNumberCode(locale.getLanguage()));
*
* Country storeCountry = (Country) countriesMap.get(store
* .getCountry());
*
* Country customerCountry = (Country) countriesMap.get(customer
* .getCustomerCountryId());
*
* int sZone = -1;
* try {
* sZone = Integer.parseInt(store.getZone());
* } catch (Exception e) {
* // TODO: handle exception
* }
*
* Zone storeZone = (Zone) zonesMap.get(sZone);
* Zone customerZone = (Zone) zonesMap.get(customer
* .getCustomerZoneId());*
*/
xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>");
// xmldatabuffer.append("<Description>Daily Pickup</Description>");
xmldatabuffer.append("<Shipment><Shipper>");
xmldatabuffer.append("<Address>");
xmldatabuffer.append("<City>");
xmldatabuffer.append(store.getStorecity());
xmldatabuffer.append("</City>");
// if(!StringUtils.isBlank(store.getStorestateprovince())) {
if (store.getZone() != null) {
xmldatabuffer.append("<StateProvinceCode>");
// zone code
xmldatabuffer.append(store.getZone().getCode());
xmldatabuffer.append("</StateProvinceCode>");
}
xmldatabuffer.append("<CountryCode>");
xmldatabuffer.append(store.getCountry().getIsoCode());
xmldatabuffer.append("</CountryCode>");
xmldatabuffer.append("<PostalCode>");
xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
xmldatabuffer.append("</PostalCode></Address></Shipper>");
// ship to
xmldatabuffer.append("<ShipTo>");
xmldatabuffer.append("<Address>");
xmldatabuffer.append("<City>");
xmldatabuffer.append(delivery.getCity());
xmldatabuffer.append("</City>");
// if(!StringUtils.isBlank(customer.getCustomerState())) {
if (delivery.getZone() != null) {
xmldatabuffer.append("<StateProvinceCode>");
// zone code
xmldatabuffer.append(delivery.getZone().getCode());
xmldatabuffer.append("</StateProvinceCode>");
}
xmldatabuffer.append("<CountryCode>");
xmldatabuffer.append(delivery.getCountry().getIsoCode());
xmldatabuffer.append("</CountryCode>");
xmldatabuffer.append("<PostalCode>");
xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
xmldatabuffer.append("</PostalCode></Address></ShipTo>");
for (PackageDetails packageDetail : packages) {
xmldatabuffer.append("<Package>");
xmldatabuffer.append("<PackagingType>");
xmldatabuffer.append("<Code>");
xmldatabuffer.append(pack);
xmldatabuffer.append("</Code>");
xmldatabuffer.append("</PackagingType>");
// weight
xmldatabuffer.append("<PackageWeight>");
xmldatabuffer.append("<UnitOfMeasurement>");
xmldatabuffer.append("<Code>");
xmldatabuffer.append(weightCode);
xmldatabuffer.append("</Code>");
xmldatabuffer.append("</UnitOfMeasurement>");
xmldatabuffer.append("<Weight>");
xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP));
xmldatabuffer.append("</Weight>");
xmldatabuffer.append("</PackageWeight>");
// dimension
xmldatabuffer.append("<Dimensions>");
xmldatabuffer.append("<UnitOfMeasurement>");
xmldatabuffer.append("<Code>");
xmldatabuffer.append(measureCode);
xmldatabuffer.append("</Code>");
xmldatabuffer.append("</UnitOfMeasurement>");
xmldatabuffer.append("<Length>");
xmldatabuffer.append(new BigDecimal(packageDetail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
xmldatabuffer.append("</Length>");
xmldatabuffer.append("<Width>");
xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
xmldatabuffer.append("</Width>");
xmldatabuffer.append("<Height>");
xmldatabuffer.append(new BigDecimal(packageDetail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP));
xmldatabuffer.append("</Height>");
xmldatabuffer.append("</Dimensions>");
xmldatabuffer.append("</Package>");
}
xmldatabuffer.append("</Shipment>");
xmldatabuffer.append("</RatingServiceSelectionRequest>");
xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString());
LOGGER.debug("UPS QUOTE REQUEST " + xmlbuffer.toString());
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// HttpClient client = new HttpClient();
httppost = new HttpPost(protocol + "://" + host + ":" + port + url);
StringEntity entity = new StringEntity(xmlbuffer.toString(), ContentType.APPLICATION_ATOM_XML);
// RequestEntity entity = new StringRequestEntity(
// xmlbuffer.toString(), "text/plain", "UTF-8");
httppost.setEntity(entity);
// Create a custom response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity1 = response.getEntity();
return entity1 != null ? EntityUtils.toString(entity1) : null;
} else {
LOGGER.error("Communication Error with ups quote " + status);
throw new ClientProtocolException("UPS quote communication error " + status);
}
};
String data = httpclient.execute(httppost, responseHandler);
// int result = response.getStatusLine().getStatusCode();
// int result = client.executeMethod(httppost);
/* if (result != 200) {
LOGGER.error("Communication Error with ups quote " + result + " "
+ protocol + "://" + host + ":" + port + url);
throw new Exception("UPS quote communication error " + result);
}*/
LOGGER.debug("ups quote response " + data);
UPSParsedElements parsed = new UPSParsedElements();
Digester digester = new Digester();
digester.push(parsed);
digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0);
digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0);
digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode", 0);
digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription", "setStatusMessage", 0);
digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0);
digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", ShippingOption.class);
// digester.addSetProperties(
// "RatingServiceSelectionResponse/RatedShipment", "sequence",
// "optionId" );
digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0);
digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue", "setOptionPriceText", 0);
// digester
// .addCallMethod(
// "RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode",
// "setCurrency", 0);
digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0);
digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery", "setEstimatedNumberOfDays", 0);
digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "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>
Reader xmlreader = new StringReader(data);
digester.parse(xmlreader);
if (!StringUtils.isBlank(parsed.getErrorCode())) {
LOGGER.error("Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
throw new IntegrationException(parsed.getError());
}
if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
throw new IntegrationException(parsed.getError());
}
if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
throw new IntegrationException("No shipping options available for the configuration");
}
/*String carrier = getShippingMethodDescription(locale);
// cost is in CAD, need to do conversion
boolean requiresCurrencyConversion = false; String storeCurrency
= store.getCurrency();
if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
requiresCurrencyConversion = true; }
LabelUtil labelUtil = LabelUtil.getInstance();
Map serviceMap = com.salesmanager.core.util.ShippingUtil
.buildServiceMap("upsxml", locale);
*/
/**
* Details on whit RT quote information to display *
*/
/*
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() + "]");
}
}
}*/
List<ShippingOption> shippingOptions = parsed.getOptions();
if (shippingOptions != null) {
Map<String, String> details = module.getDetails();
for (ShippingOption option : shippingOptions) {
String name = details.get(option.getOptionCode());
option.setOptionName(name);
if (option.getOptionPrice() == null) {
String priceText = option.getOptionPriceText();
if (StringUtils.isBlank(priceText)) {
throw new IntegrationException("Price text is null for option " + name);
}
try {
BigDecimal price = new BigDecimal(priceText);
option.setOptionPrice(price);
} catch (Exception e) {
throw new IntegrationException("Can't convert to numeric price " + priceText);
}
}
}
}
return shippingOptions;
}
} catch (Exception e1) {
LOGGER.error("UPS quote error", e1);
throw new IntegrationException(e1);
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception ignore) {
}
}
if (httppost != null) {
httppost.releaseConnection();
}
}
}
Aggregations