use of com.salesmanager.core.model.shipping.ShippingOrigin 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();
}
}
}
use of com.salesmanager.core.model.shipping.ShippingOrigin 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.ShippingOrigin in project shopizer by shopizer-ecommerce.
the class ShippingFacadeImpl method getShippingOrigin.
@Override
public ReadableAddress getShippingOrigin(MerchantStore store) {
ShippingOrigin o = shippingOriginService.getByStore(store);
if (o == null) {
throw new ResourceNotFoundException("Shipping origin does not exists for store [" + store.getCode() + "]");
}
ReadableAddress address = new ReadableAddress();
address.setAddress(o.getAddress());
address.setActive(o.isActive());
address.setCity(o.getCity());
address.setPostalCode(o.getPostalCode());
if (o.getCountry() != null) {
address.setCountry(o.getCountry().getIsoCode());
}
Zone z = o.getZone();
if (z != null) {
address.setStateProvince(z.getCode());
} else {
address.setStateProvince(o.getState());
}
return address;
}
use of com.salesmanager.core.model.shipping.ShippingOrigin 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();
}
}
}
use of com.salesmanager.core.model.shipping.ShippingOrigin in project shopizer by shopizer-ecommerce.
the class ShippingFacadeImpl method saveShippingOrigin.
@Override
public void saveShippingOrigin(PersistableAddress address, MerchantStore store) {
Validate.notNull(address, "PersistableAddress cannot be null");
try {
ShippingOrigin o = shippingOriginService.getByStore(store);
if (o == null) {
o = new ShippingOrigin();
}
o.setAddress(address.getAddress());
o.setCity(address.getCity());
o.setCountry(countryService.getByCode(address.getCountry()));
o.setMerchantStore(store);
o.setActive(address.isActive());
o.setPostalCode(address.getPostalCode());
Zone zone = zoneService.getByCode(address.getStateProvince());
if (zone == null) {
o.setState(address.getStateProvince());
} else {
o.setZone(zone);
}
shippingOriginService.save(o);
} catch (ServiceException e) {
LOGGER.error("Error while getting shipping origin for country [" + address.getCountry() + "]", e);
throw new ServiceRuntimeException("Error while getting shipping origin for country [" + address.getCountry() + "]", e);
}
}
Aggregations