Search in sources :

Example 1 with IntegrationModule

use of com.salesmanager.core.model.system.IntegrationModule in project shopizer by shopizer-ecommerce.

the class ShoppingOrderPaymentController method paymentAction.

/**
 * Recalculates shipping and tax following a change in country or province
 *
 * @param order
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/order/payment/{action}/{paymentmethod}.html" }, method = RequestMethod.POST)
@ResponseBody
public String paymentAction(@Valid @ModelAttribute(value = "order") ShopOrder order, @PathVariable String action, @PathVariable String paymentmethod, 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");
    AjaxResponse ajaxResponse = new AjaxResponse();
    try {
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        Set<ShoppingCartItem> items = cart.getLineItems();
        List<ShoppingCartItem> cartItems = new ArrayList<ShoppingCartItem>(items);
        order.setShoppingCartItems(cartItems);
        // validate order first
        Map<String, String> messages = new TreeMap<String, String>();
        orderFacade.validateOrder(order, new BeanPropertyBindingResult(order, "order"), messages, store, locale);
        if (CollectionUtils.isNotEmpty(messages.values())) {
            for (String key : messages.keySet()) {
                String value = messages.get(key);
                ajaxResponse.addValidationMessage(key, value);
            }
            ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_VALIDATION_FAILED);
            return ajaxResponse.toJSONString();
        }
        IntegrationConfiguration config = paymentService.getPaymentConfiguration(order.getPaymentModule(), store);
        IntegrationModule integrationModule = paymentService.getPaymentMethodByCode(store, order.getPaymentModule());
        // OrderTotalSummary orderTotalSummary =
        // orderFacade.calculateOrderTotal(store, order, language);
        OrderTotalSummary orderTotalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
        if (orderTotalSummary == null) {
            orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
            super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
        }
        ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute("SHIPPING_SUMMARY");
        if (summary != null) {
            order.setShippingSummary(summary);
        }
        if (action.equals(INIT_ACTION)) {
            if (paymentmethod.equals("PAYPAL")) {
                try {
                    PaymentModule module = paymentService.getPaymentModule("paypal-express-checkout");
                    PayPalExpressCheckoutPayment p = (PayPalExpressCheckoutPayment) module;
                    PaypalPayment payment = new PaypalPayment();
                    payment.setCurrency(store.getCurrency());
                    Transaction transaction = p.initPaypalTransaction(store, cartItems, orderTotalSummary, payment, config, integrationModule);
                    transactionService.create(transaction);
                    super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
                    StringBuilder urlAppender = new StringBuilder();
                    urlAppender.append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_REGULAR"));
                    urlAppender.append(transaction.getTransactionDetails().get("TOKEN"));
                    if (config.getEnvironment().equals(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT)) {
                        StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_PRODUCTION")).append(urlAppender.toString());
                        ajaxResponse.addEntry("url", url.toString());
                    } else {
                        StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_SANDBOX")).append(urlAppender.toString());
                        ajaxResponse.addEntry("url", url.toString());
                    }
                    // keep order in session when user comes back from pp
                    super.setSessionAttribute(Constants.ORDER, order, request);
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
                } catch (Exception e) {
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
                }
            } else if (paymentmethod.equals("stripe3")) {
                try {
                    PaymentModule module = paymentService.getPaymentModule(paymentmethod);
                    Stripe3Payment p = (Stripe3Payment) module;
                    PaypalPayment payment = new PaypalPayment();
                    payment.setCurrency(store.getCurrency());
                    Transaction transaction = p.initTransaction(store, null, orderTotalSummary.getTotal(), null, config, integrationModule);
                    transactionService.create(transaction);
                    super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
                    // keep order in session when user comes back from pp
                    super.setSessionAttribute(Constants.ORDER, order, request);
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
                    ajaxResponse.setDataMap(transaction.getTransactionDetails());
                } catch (Exception e) {
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error while performing payment action " + action + " for payment method " + paymentmethod, e);
        ajaxResponse.setErrorMessage(e);
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }
    return ajaxResponse.toJSONString();
}
Also used : Stripe3Payment(com.salesmanager.core.business.modules.integration.payment.impl.Stripe3Payment) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) PayPalExpressCheckoutPayment(com.salesmanager.core.business.modules.integration.payment.impl.PayPalExpressCheckoutPayment) PaypalPayment(com.salesmanager.core.model.payments.PaypalPayment) PaymentModule(com.salesmanager.core.modules.integration.payment.model.PaymentModule) Language(com.salesmanager.core.model.reference.language.Language) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) AjaxResponse(com.salesmanager.core.business.utils.ajax.AjaxResponse) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) TreeMap(java.util.TreeMap) Transaction(com.salesmanager.core.model.payments.Transaction) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with IntegrationModule

use of com.salesmanager.core.model.system.IntegrationModule 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();
        }
    }
}
Also used : ClientProtocolException(org.apache.http.client.ClientProtocolException) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) Date(java.util.Date) DataUtils(com.salesmanager.core.business.utils.DataUtils) LoggerFactory(org.slf4j.LoggerFactory) SimpleDateFormat(java.text.SimpleDateFormat) Delivery(com.salesmanager.core.model.common.Delivery) StringUtils(org.apache.commons.lang3.StringUtils) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ArrayList(java.util.ArrayList) EntityUtils(org.apache.http.util.EntityUtils) Inject(javax.inject.Inject) Language(com.salesmanager.core.model.reference.language.Language) BigDecimal(java.math.BigDecimal) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Calendar(java.util.Calendar) Locale(java.util.Locale) CustomIntegrationConfiguration(com.salesmanager.core.model.system.CustomIntegrationConfiguration) Map(java.util.Map) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) Constants(com.salesmanager.core.business.constants.Constants) MeasureUnit(com.salesmanager.core.constants.MeasureUnit) CountryService(com.salesmanager.core.business.services.reference.country.CountryService) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Logger(org.slf4j.Logger) Country(com.salesmanager.core.model.reference.country.Country) Digester(org.apache.commons.digester.Digester) HttpEntity(org.apache.http.HttpEntity) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) IOException(java.io.IOException) Reader(java.io.Reader) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) List(java.util.List) StringReader(java.io.StringReader) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) ResponseHandler(org.apache.http.client.ResponseHandler) ShippingQuoteModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuoteModule) HttpClients(org.apache.http.impl.client.HttpClients) ProductPriceUtils(com.salesmanager.core.business.utils.ProductPriceUtils) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) Reader(java.io.Reader) StringReader(java.io.StringReader) ClientProtocolException(org.apache.http.client.ClientProtocolException) Language(com.salesmanager.core.model.reference.language.Language) Digester(org.apache.commons.digester.Digester) StringReader(java.io.StringReader) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) Calendar(java.util.Calendar) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) Date(java.util.Date) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Country(com.salesmanager.core.model.reference.country.Country) SimpleDateFormat(java.text.SimpleDateFormat) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails)

Example 3 with IntegrationModule

use of com.salesmanager.core.model.system.IntegrationModule in project shopizer by shopizer-ecommerce.

the class ShippingMethodDecisionTest method validateShippingMethod.

@Test
@Ignore
public void validateShippingMethod() throws Exception {
    ShippingQuote quote = new ShippingQuote();
    PackageDetails pDetail = new PackageDetails();
    pDetail.setShippingHeight(20);
    pDetail.setShippingLength(10);
    pDetail.setShippingWeight(70);
    pDetail.setShippingWidth(78);
    List<PackageDetails> details = new ArrayList<PackageDetails>();
    details.add(pDetail);
    Delivery delivery = new Delivery();
    delivery.setAddress("358 Du Languedoc");
    delivery.setCity("Boucherville");
    delivery.setPostalCode("J4B 8J9");
    Country country = new Country();
    country.setIsoCode("CA");
    country.setName("Canada");
    // country.setIsoCode("US");
    // country.setName("United States");
    delivery.setCountry(country);
    Zone zone = new Zone();
    zone.setCode("QC");
    zone.setName("Quebec");
    // zone.setCode("NY");
    // zone.setName("New York");
    delivery.setZone(zone);
    IntegrationModule currentModule = new IntegrationModule();
    currentModule.setCode("canadapost");
    quote.setCurrentShippingModule(currentModule);
    quote.setShippingModuleCode(currentModule.getCode());
    IntegrationModule canadapost = new IntegrationModule();
    canadapost.setCode("canadapost");
    IntegrationModule ups = new IntegrationModule();
    ups.setCode("ups");
    IntegrationModule inhouse = new IntegrationModule();
    inhouse.setCode("customQuotesRules");
    List<IntegrationModule> allModules = new ArrayList<IntegrationModule>();
    allModules.add(canadapost);
    allModules.add(ups);
    allModules.add(inhouse);
    shippingMethodDecisionProcess.prePostProcessShippingQuotes(quote, details, null, delivery, null, null, null, currentModule, null, allModules, Locale.CANADA);
    System.out.println("Done : " + quote.getCurrentShippingModule() != null ? quote.getCurrentShippingModule().getCode() : currentModule.getCode());
}
Also used : ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Zone(com.salesmanager.core.model.reference.zone.Zone) ArrayList(java.util.ArrayList) Country(com.salesmanager.core.model.reference.country.Country) Delivery(com.salesmanager.core.model.common.Delivery) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 4 with IntegrationModule

use of com.salesmanager.core.model.system.IntegrationModule in project shopizer by shopizer-ecommerce.

the class ImportIntegrationModule method importSpecificIntegrationModule.

/**
 * Import a specific integration module. Will delete and recreate the module
 * if it already exists
 * @throws Exception
 */
@Ignore
public // @Test
void importSpecificIntegrationModule() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    File file = new File(" /Users/carlsamson/Documents/dev/workspaces/shopizer-master/shopizer/sm-core/src/main/resources/reference/integrationmodules.json");
    try (InputStream in = new FileInputStream(file)) {
        @SuppressWarnings("rawtypes") Map[] objects = mapper.readValue(in, Map[].class);
        IntegrationModule module = null;
        // get the module to be loaded
        for (Map o : objects) {
            // load that specific module
            if (o.get("code").equals("beanstream")) {
                // get module object
                module = integrationModulesLoader.loadModule(o);
                break;
            }
        }
        if (module != null) {
            IntegrationModule m = moduleCongigurationService.getByCode(module.getCode());
            if (m != null) {
                moduleCongigurationService.delete(m);
            }
            moduleCongigurationService.create(module);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}
Also used : ServiceException(com.salesmanager.core.business.exception.ServiceException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) ServiceException(com.salesmanager.core.business.exception.ServiceException) Ignore(org.junit.Ignore)

Example 5 with IntegrationModule

use of com.salesmanager.core.model.system.IntegrationModule in project shopizer by shopizer-ecommerce.

the class ImportIntegrationModule method importNonExistingIntegrationModule.

/**
 * Import all non existing modules
 * @throws Exception
 */
@Ignore
public // @Test
void importNonExistingIntegrationModule() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    File file = new File("/Users/carlsamson/Documents/dev/workspaces/shopizer-master/shopizer/sm-core/src/main/resources/reference/integrationmodules.json");
    try (InputStream in = new FileInputStream(file)) {
        @SuppressWarnings("rawtypes") Map[] objects = mapper.readValue(in, Map[].class);
        // get the module to be loaded
        for (Map o : objects) {
            // get module object
            IntegrationModule module = integrationModulesLoader.loadModule(o);
            if (module != null) {
                IntegrationModule m = moduleCongigurationService.getByCode(module.getCode());
                if (m == null) {
                    moduleCongigurationService.create(module);
                }
            }
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}
Also used : ServiceException(com.salesmanager.core.business.exception.ServiceException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) ServiceException(com.salesmanager.core.business.exception.ServiceException) Ignore(org.junit.Ignore)

Aggregations

IntegrationModule (com.salesmanager.core.model.system.IntegrationModule)26 ServiceException (com.salesmanager.core.business.exception.ServiceException)18 IntegrationConfiguration (com.salesmanager.core.model.system.IntegrationConfiguration)16 Map (java.util.Map)13 ArrayList (java.util.ArrayList)11 List (java.util.List)9 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)8 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)8 Language (com.salesmanager.core.model.reference.language.Language)7 BigDecimal (java.math.BigDecimal)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 PaymentModule (com.salesmanager.core.modules.integration.payment.model.PaymentModule)6 IntegrationModuleConfiguration (com.salesmanager.shop.model.system.IntegrationModuleConfiguration)6 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)6 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)6 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)6 ApiOperation (io.swagger.annotations.ApiOperation)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5