Search in sources :

Example 26 with Language

use of com.salesmanager.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.

the class StoreFilter method preHandle.

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    request.setCharacterEncoding("UTF-8");
    /**
     * if url contains /services exit from here !
     */
    if (request.getRequestURL().toString().toLowerCase().contains(SERVICES_URL_PATTERN) || request.getRequestURL().toString().toLowerCase().contains(REFERENCE_URL_PATTERN)) {
        return true;
    }
    try {
        /**
         * merchant store *
         */
        MerchantStore store = (MerchantStore) request.getSession().getAttribute(Constants.MERCHANT_STORE);
        String storeCode = request.getParameter(STORE_REQUEST_PARAMETER);
        // remove link set from controllers for declaring active - inactive
        // links
        request.removeAttribute(Constants.LINK_CODE);
        if (!StringUtils.isBlank(storeCode)) {
            if (store != null) {
                if (!store.getCode().equals(storeCode)) {
                    store = setMerchantStoreInSession(request, storeCode);
                }
            } else {
                // when url sm-shop/shop is being loaded for first time
                // store is null
                store = setMerchantStoreInSession(request, storeCode);
            }
        }
        if (store == null) {
            store = setMerchantStoreInSession(request, MerchantStore.DEFAULT_STORE);
        }
        if (StringUtils.isBlank(store.getStoreTemplate())) {
            store.setStoreTemplate(Constants.DEFAULT_TEMPLATE);
        }
        request.setAttribute(Constants.MERCHANT_STORE, store);
        /*
			//remote ip address
			String remoteAddress = "";
			try {
				
				if (request != null) {
					remoteAddress = request.getHeader("X-Forwarded-For");
					if (remoteAddress == null || "".equals(remoteAddress)) {
						remoteAddress = request.getRemoteAddr();
					}
				}
				remoteAddress = remoteAddress != null && remoteAddress.contains(",") ? remoteAddress.split(",")[0] : remoteAddress;
				LOGGER.info("remote ip addres {}", remoteAddress);
			} catch (Exception e) {
				LOGGER.error("Error while getting user remote address");
			}
			*/
        String ipAddress = GeoLocationUtils.getClientIpAddress(request);
        UserContext userContext = UserContext.create();
        userContext.setIpAddress(ipAddress);
        /**
         * customer *
         */
        Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
        if (customer != null) {
            if (customer.getMerchantStore().getId().intValue() != store.getId().intValue()) {
                request.getSession().removeAttribute(Constants.CUSTOMER);
            }
            if (!customer.isAnonymous()) {
                if (!request.isUserInRole("AUTH_CUSTOMER")) {
                    request.removeAttribute(Constants.CUSTOMER);
                }
            }
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            request.setAttribute(Constants.CUSTOMER, customer);
        }
        if (customer == null) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
                customer = customerService.getByNick(auth.getName());
                if (customer != null) {
                    request.setAttribute(Constants.CUSTOMER, customer);
                }
            }
        }
        AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getSession().getAttribute(Constants.ANONYMOUS_CUSTOMER);
        if (anonymousCustomer == null) {
            Address address = null;
            try {
                if (!StringUtils.isBlank(ipAddress)) {
                    com.salesmanager.core.model.common.Address geoAddress = customerService.getCustomerAddress(store, ipAddress);
                    if (geoAddress != null) {
                        address = new Address();
                        address.setCountry(geoAddress.getCountry());
                        address.setCity(geoAddress.getCity());
                        address.setZone(geoAddress.getZone());
                    /**
                     * no postal code *
                     */
                    // address.setPostalCode(geoAddress.getPostalCode());
                    }
                }
            } catch (Exception ce) {
                LOGGER.error("Cannot get geo ip component ", ce);
            }
            if (address == null) {
                address = new Address();
                address.setCountry(store.getCountry().getIsoCode());
                if (store.getZone() != null) {
                    address.setZone(store.getZone().getCode());
                } else {
                    address.setStateProvince(store.getStorestateprovince());
                }
            /**
             * no postal code *
             */
            // address.setPostalCode(store.getStorepostalcode());
            }
            anonymousCustomer = new AnonymousCustomer();
            anonymousCustomer.setBilling(address);
            request.getSession().setAttribute(Constants.ANONYMOUS_CUSTOMER, anonymousCustomer);
        } else {
            request.setAttribute(Constants.ANONYMOUS_CUSTOMER, anonymousCustomer);
        }
        /**
         * language & locale *
         */
        Language language = languageUtils.getRequestLanguage(request, response);
        request.setAttribute(Constants.LANGUAGE, language);
        Locale locale = languageService.toLocale(language, store);
        request.setAttribute(Constants.LOCALE, locale);
        // Locale locale = LocaleContextHolder.getLocale();
        LocaleContextHolder.setLocale(locale);
        /**
         * Breadcrumbs *
         */
        setBreadcrumb(request, locale);
        /**
         * Get global objects Themes are built on a similar way displaying
         * Header, Body and Footer Header and Footer are displayed on each
         * page Some themes also contain side bars which may include similar
         * emements
         *
         * Elements from Header : - CMS links - Customer - Mini shopping
         * cart - Store name / logo - Top categories - Search
         *
         * Elements from Footer : - CMS links - Store address - Global
         * payment information - Global shipping information
         */
        // get from the cache first
        /**
         * The cache for each object contains 2 objects, a Cache and a
         * Missed-Cache Get objects from the cache If not null use those
         * objects If null, get entry from missed-cache If missed-cache not
         * null then nothing exist If missed-cache null, add missed-cache
         * entry and load from the database If objects from database not
         * null store in cache
         */
        /**
         ***** CMS Objects *******
         */
        this.getContentObjects(store, language, request);
        /**
         ***** CMS Page names *********
         */
        this.getContentPageNames(store, language, request);
        /**
         ***** Top Categories *******
         */
        // this.getTopCategories(store, language, request);
        this.setTopCategories(store, language, request);
        /**
         ***** Default metatags ******
         */
        /**
         * Title Description Keywords
         */
        PageInformation pageInformation = new PageInformation();
        pageInformation.setPageTitle(store.getStorename());
        pageInformation.setPageDescription(store.getStorename());
        pageInformation.setPageKeywords(store.getStorename());
        @SuppressWarnings("unchecked") Map<String, ContentDescription> contents = (Map<String, ContentDescription>) request.getAttribute(Constants.REQUEST_CONTENT_OBJECTS);
        if (contents != null) {
            // for(String key : contents.keySet()) {
            // List<ContentDescription> contentsList = contents.get(key);
            // for(Content content : contentsList) {
            // if(key.equals(Constants.CONTENT_LANDING_PAGE)) {
            // List<ContentDescription> descriptions =
            // content.getDescriptions();
            ContentDescription contentDescription = contents.get(Constants.CONTENT_LANDING_PAGE);
            if (contentDescription != null) {
                // for(ContentDescription contentDescription : descriptions)
                // {
                // if(contentDescription.getLanguage().getCode().equals(language.getCode()))
                // {
                pageInformation.setPageTitle(contentDescription.getName());
                pageInformation.setPageDescription(contentDescription.getMetatagDescription());
                pageInformation.setPageKeywords(contentDescription.getMetatagKeywords());
            // }
            }
        // }
        // }
        // }
        }
        request.setAttribute(Constants.REQUEST_PAGE_INFORMATION, pageInformation);
        /**
         ***** Configuration objects ******
         */
        /**
         * SHOP configuration type Should contain - Different configuration
         * flags - Google analytics - Facebook page - Twitter handle - Show
         * customer login - ...
         */
        this.getMerchantConfigurations(store, request);
        /**
         ***** Shopping Cart ********
         */
        String shoppingCarCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
        if (shoppingCarCode != null) {
            request.setAttribute(Constants.REQUEST_SHOPPING_CART, shoppingCarCode);
        }
    } catch (Exception e) {
        LOGGER.error("Error in StoreFilter", e);
    }
    return true;
}
Also used : Address(com.salesmanager.shop.model.customer.address.Address) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Customer(com.salesmanager.core.model.customer.Customer) UserContext(com.salesmanager.core.model.common.UserContext) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Language(com.salesmanager.core.model.reference.language.Language) PageInformation(com.salesmanager.shop.model.shop.PageInformation) Authentication(org.springframework.security.core.Authentication) ContentDescription(com.salesmanager.core.model.content.ContentDescription) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 27 with Language

use of com.salesmanager.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.

the class StoreFilter method setTopCategories.

@SuppressWarnings("unchecked")
private void setTopCategories(MerchantStore store, Language language, HttpServletRequest request) throws Exception {
    StringBuilder categoriesKey = new StringBuilder();
    categoriesKey.append(store.getId()).append("_").append(Constants.CATEGORIES_CACHE_KEY).append("-").append(language.getCode());
    StringBuilder categoriesKeyMissed = new StringBuilder();
    categoriesKeyMissed.append(categoriesKey.toString()).append(Constants.MISSED_CACHE_KEY);
    // language code - List of category
    Map<String, List<ReadableCategory>> objects = null;
    List<ReadableCategory> loadedCategories = null;
    if (store.isUseCache()) {
        objects = (Map<String, List<ReadableCategory>>) webApplicationCache.getFromCache(categoriesKey.toString());
        if (objects == null) {
            // load categories
            ReadableCategoryList categoryList = categoryFacade.getCategoryHierarchy(store, null, 0, language, null, 0, // null
            200);
            loadedCategories = categoryList.getCategories();
            // filter out invisible category
            loadedCategories.stream().filter(cat -> cat.isVisible() == true).collect(Collectors.toList());
            objects = new ConcurrentHashMap<String, List<ReadableCategory>>();
            objects.put(language.getCode(), loadedCategories);
            webApplicationCache.putInCache(categoriesKey.toString(), objects);
        } else {
            loadedCategories = objects.get(language.getCode());
        }
    } else {
        ReadableCategoryList categoryList = categoryFacade.getCategoryHierarchy(store, null, 0, language, null, 0, // null // filter
        200);
        loadedCategories = categoryList.getCategories();
    }
    if (loadedCategories != null) {
        request.setAttribute(Constants.REQUEST_TOP_CATEGORIES, loadedCategories);
    }
}
Also used : ContentDescription(com.salesmanager.core.model.content.ContentDescription) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) LoggerFactory(org.slf4j.LoggerFactory) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) StringUtils(org.apache.commons.lang3.StringUtils) LanguageService(com.salesmanager.core.business.services.reference.language.LanguageService) HandlerInterceptorAdapter(org.springframework.web.servlet.handler.HandlerInterceptorAdapter) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Content(com.salesmanager.core.model.content.Content) UserContext(com.salesmanager.core.model.common.UserContext) ContentType(com.salesmanager.core.model.content.ContentType) ReadableCategoryPopulator(com.salesmanager.shop.populator.catalog.ReadableCategoryPopulator) CategoryService(com.salesmanager.core.business.services.catalog.category.CategoryService) MerchantStoreService(com.salesmanager.core.business.services.merchant.MerchantStoreService) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) CustomerService(com.salesmanager.core.business.services.customer.CustomerService) Breadcrumb(com.salesmanager.shop.model.shop.Breadcrumb) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) CategoryDescription(com.salesmanager.core.model.catalog.category.CategoryDescription) ModelAndView(org.springframework.web.servlet.ModelAndView) BreadcrumbItem(com.salesmanager.shop.model.shop.BreadcrumbItem) CacheUtils(com.salesmanager.core.business.utils.CacheUtils) MerchantConfiguration(com.salesmanager.core.model.system.MerchantConfiguration) LanguageUtils(com.salesmanager.shop.utils.LanguageUtils) GeoLocationUtils(com.salesmanager.shop.utils.GeoLocationUtils) CoreConfiguration(com.salesmanager.core.business.utils.CoreConfiguration) ReadableCategory(com.salesmanager.shop.model.catalog.category.ReadableCategory) Address(com.salesmanager.shop.model.customer.address.Address) Authentication(org.springframework.security.core.Authentication) WebApplicationCacheUtils(com.salesmanager.shop.utils.WebApplicationCacheUtils) ProductService(com.salesmanager.core.business.services.catalog.product.ProductService) java.util(java.util) CategoryFacade(com.salesmanager.shop.store.controller.category.facade.CategoryFacade) Constants(com.salesmanager.shop.constants.Constants) CollectionUtils(org.apache.commons.collections4.CollectionUtils) Language(com.salesmanager.core.model.reference.language.Language) Inject(javax.inject.Inject) BreadcrumbItemType(com.salesmanager.shop.model.shop.BreadcrumbItemType) HttpServletRequest(javax.servlet.http.HttpServletRequest) LabelUtils(com.salesmanager.shop.utils.LabelUtils) PageInformation(com.salesmanager.shop.model.shop.PageInformation) Nullable(javax.annotation.Nullable) Product(com.salesmanager.core.model.catalog.product.Product) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Customer(com.salesmanager.core.model.customer.Customer) MerchantConfig(com.salesmanager.core.model.system.MerchantConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) MerchantConfigurationService(com.salesmanager.core.business.services.system.MerchantConfigurationService) ReadableCategoryList(com.salesmanager.shop.model.catalog.category.ReadableCategoryList) ContentService(com.salesmanager.core.business.services.content.ContentService) Category(com.salesmanager.core.model.catalog.category.Category) MerchantConfigurationType(com.salesmanager.core.model.system.MerchantConfigurationType) ReadableCategory(com.salesmanager.shop.model.catalog.category.ReadableCategory) ReadableCategoryList(com.salesmanager.shop.model.catalog.category.ReadableCategoryList) ReadableCategoryList(com.salesmanager.shop.model.catalog.category.ReadableCategoryList)

Example 28 with Language

use of com.salesmanager.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.

the class PersistableProductDefinitionMapper method merge.

@Override
public Product merge(PersistableProductDefinition source, Product destination, MerchantStore store, Language language) {
    Validate.notNull(destination, "Product must not be null");
    try {
        destination.setSku(source.getIdentifier());
        destination.setAvailable(source.isVisible());
        destination.setDateAvailable(new Date());
        destination.setRefSku(source.getIdentifier());
        if (source.getId() != null && source.getId().longValue() == 0) {
            destination.setId(null);
        } else {
            destination.setId(source.getId());
        }
        // MANUFACTURER
        if (!StringUtils.isBlank(source.getManufacturer())) {
            Manufacturer manufacturer = manufacturerService.getByCode(store, source.getManufacturer());
            if (manufacturer == null) {
                throw new ConversionException("Manufacturer [" + source.getManufacturer() + "] does not exist");
            }
            destination.setManufacturer(manufacturer);
        }
        // PRODUCT TYPE
        if (!StringUtils.isBlank(source.getType())) {
            ProductType type = productTypeService.getByCode(source.getType(), store, language);
            if (type == null) {
                throw new ConversionException("Product type [" + source.getType() + "] does not exist");
            }
            destination.setType(type);
        }
        if (!StringUtils.isBlank(source.getDateAvailable())) {
            destination.setDateAvailable(DateUtil.getDate(source.getDateAvailable()));
        }
        destination.setMerchantStore(store);
        List<Language> languages = new ArrayList<Language>();
        Set<ProductDescription> descriptions = new HashSet<ProductDescription>();
        if (!CollectionUtils.isEmpty(source.getDescriptions())) {
            for (com.salesmanager.shop.model.catalog.product.ProductDescription description : source.getDescriptions()) {
                ProductDescription productDescription = new ProductDescription();
                Language lang = languageService.getByCode(description.getLanguage());
                if (lang == null) {
                    throw new ConversionException("Language code " + description.getLanguage() + " is invalid, use ISO code (en, fr ...)");
                }
                if (!CollectionUtils.isEmpty(destination.getDescriptions())) {
                    for (ProductDescription desc : destination.getDescriptions()) {
                        if (desc.getLanguage().getCode().equals(description.getLanguage())) {
                            productDescription = desc;
                            break;
                        }
                    }
                }
                productDescription.setProduct(destination);
                productDescription.setDescription(description.getDescription());
                productDescription.setProductHighlight(description.getHighlights());
                productDescription.setName(description.getName());
                productDescription.setSeUrl(description.getFriendlyUrl());
                productDescription.setMetatagKeywords(description.getKeyWords());
                productDescription.setMetatagDescription(description.getMetaDescription());
                productDescription.setTitle(description.getTitle());
                languages.add(lang);
                productDescription.setLanguage(lang);
                descriptions.add(productDescription);
            }
        }
        if (descriptions.size() > 0) {
            destination.setDescriptions(descriptions);
        }
        // if(source.getRating() != null) {
        // destination.setProductReviewAvg(new BigDecimal(source.getRating()));
        // }
        // destination.setProductReviewCount(source.getRatingCount());
        /**
         * Product definition
         */
        ProductAvailability productAvailability = null;
        ProductPrice defaultPrice = null;
        if (!CollectionUtils.isEmpty(destination.getAvailabilities())) {
            for (ProductAvailability avail : destination.getAvailabilities()) {
                Set<ProductPrice> prices = avail.getPrices();
                for (ProductPrice p : prices) {
                    if (p.isDefaultPrice()) {
                        if (productAvailability == null) {
                            productAvailability = avail;
                            defaultPrice = p;
                            productAvailability.setProductQuantity(source.getQuantity());
                            productAvailability.setProductStatus(source.isCanBePurchased());
                            p.setProductPriceAmount(source.getPrice());
                            break;
                        }
                    }
                }
            }
        }
        if (productAvailability == null) {
            // create with default values
            productAvailability = new ProductAvailability(destination, store);
            destination.getAvailabilities().add(productAvailability);
            productAvailability.setProductQuantity(source.getQuantity());
            productAvailability.setProductQuantityOrderMin(1);
            productAvailability.setProductQuantityOrderMax(1);
            productAvailability.setRegion(Constants.ALL_REGIONS);
            productAvailability.setAvailable(Boolean.valueOf(destination.isAvailable()));
            productAvailability.setProductStatus(source.isCanBePurchased());
        }
        if (defaultPrice == null) {
            defaultPrice = new ProductPrice();
            defaultPrice.setDefaultPrice(true);
            defaultPrice.setProductPriceAmount(source.getPrice());
            defaultPrice.setCode(ProductPriceEntity.DEFAULT_PRICE_CODE);
            defaultPrice.setProductAvailability(productAvailability);
            productAvailability.getPrices().add(defaultPrice);
            for (Language lang : languages) {
                ProductPriceDescription ppd = new ProductPriceDescription();
                ppd.setProductPrice(defaultPrice);
                ppd.setLanguage(lang);
                ppd.setName(ProductPriceDescription.DEFAULT_PRICE_DESCRIPTION);
                defaultPrice.getDescriptions().add(ppd);
            }
        }
        if (source.getProductSpecifications() != null) {
            destination.setProductHeight(source.getProductSpecifications().getHeight());
            destination.setProductLength(source.getProductSpecifications().getLength());
            destination.setProductWeight(source.getProductSpecifications().getWeight());
            destination.setProductWidth(source.getProductSpecifications().getWidth());
            if (source.getProductSpecifications().getManufacturer() != null) {
                Manufacturer manuf = null;
                if (!StringUtils.isBlank(source.getProductSpecifications().getManufacturer())) {
                    manuf = manufacturerService.getByCode(store, source.getProductSpecifications().getManufacturer());
                }
                if (manuf == null) {
                    throw new ConversionException("Invalid manufacturer id");
                }
                if (manuf != null) {
                    if (manuf.getMerchantStore().getId().intValue() != store.getId().intValue()) {
                        throw new ConversionException("Invalid manufacturer id");
                    }
                    destination.setManufacturer(manuf);
                }
            }
        }
        destination.setSortOrder(source.getSortOrder());
        destination.setProductVirtual(source.isVirtual());
        destination.setProductShipeable(source.isShipeable());
        // attributes
        if (source.getProperties() != null) {
            for (com.salesmanager.shop.model.catalog.product.attribute.PersistableProductAttribute attr : source.getProperties()) {
                ProductAttribute attribute = persistableProductAttributeMapper.convert(attr, store, language);
                attribute.setProduct(destination);
                destination.getAttributes().add(attribute);
            }
        }
        // categories
        if (!CollectionUtils.isEmpty(source.getCategories())) {
            for (com.salesmanager.shop.model.catalog.category.Category categ : source.getCategories()) {
                Category c = null;
                if (!StringUtils.isBlank(categ.getCode())) {
                    c = categoryService.getByCode(store, categ.getCode());
                } else {
                    Validate.notNull(categ.getId(), "Category id nust not be null");
                    c = categoryService.getById(categ.getId(), store.getId());
                }
                if (c == null) {
                    throw new ConversionException("Category id " + categ.getId() + " does not exist");
                }
                if (c.getMerchantStore().getId().intValue() != store.getId().intValue()) {
                    throw new ConversionException("Invalid category id");
                }
                destination.getCategories().add(c);
            }
        }
        return destination;
    } catch (Exception e) {
        throw new ConversionRuntimeException("Error converting product mapper", e);
    }
}
Also used : Category(com.salesmanager.core.model.catalog.category.Category) ArrayList(java.util.ArrayList) ProductPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) Language(com.salesmanager.core.model.reference.language.Language) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) Manufacturer(com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer) ProductPriceDescription(com.salesmanager.core.model.catalog.product.price.ProductPriceDescription) HashSet(java.util.HashSet) ConversionRuntimeException(com.salesmanager.shop.store.api.exception.ConversionRuntimeException) ConversionException(com.salesmanager.core.business.exception.ConversionException) ProductType(com.salesmanager.core.model.catalog.product.type.ProductType) Date(java.util.Date) ConversionRuntimeException(com.salesmanager.shop.store.api.exception.ConversionRuntimeException) ConversionException(com.salesmanager.core.business.exception.ConversionException) ProductDescription(com.salesmanager.core.model.catalog.product.description.ProductDescription)

Example 29 with Language

use of com.salesmanager.core.model.reference.language.Language 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 30 with Language

use of com.salesmanager.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.

the class ShippingQuoteByWeightTest method testGetCustomShippingQuotesByWeight.

@Ignore
public // @Test
void testGetCustomShippingQuotesByWeight() throws ServiceException {
    Language en = languageService.getByCode("en");
    Country country = countryService.getByCode("CA");
    Zone zone = zoneService.getByCode("QC");
    MerchantStore store = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    ProductType generalType = productTypeService.getProductType(ProductType.GENERAL_TYPE);
    // set valid store postal code
    store.setStorepostalcode("J4B-9J9");
    Product product = new Product();
    product.setProductHeight(new BigDecimal(4));
    product.setProductLength(new BigDecimal(3));
    product.setProductWidth(new BigDecimal(5));
    product.setProductWeight(new BigDecimal(8));
    product.setSku("TESTSKU");
    product.setType(generalType);
    product.setMerchantStore(store);
    // Product description
    ProductDescription description = new ProductDescription();
    description.setName("Product 1");
    description.setLanguage(en);
    description.setProduct(product);
    product.getDescriptions().add(description);
    productService.create(product);
    // productService.saveOrUpdate(product);
    // Availability
    ProductAvailability availability = new ProductAvailability();
    availability.setProductDateAvailable(new Date());
    availability.setProductQuantity(100);
    availability.setRegion("*");
    // associate with product
    availability.setProduct(product);
    product.getAvailabilities().add(availability);
    productAvailabilityService.create(availability);
    ProductPrice dprice = new ProductPrice();
    dprice.setDefaultPrice(true);
    dprice.setProductPriceAmount(new BigDecimal(29.99));
    dprice.setProductAvailability(availability);
    ProductPriceDescription dpd = new ProductPriceDescription();
    dpd.setName("Base price");
    dpd.setProductPrice(dprice);
    dpd.setLanguage(en);
    dprice.getDescriptions().add(dpd);
    availability.getPrices().add(dprice);
    productPriceService.create(dprice);
    // get product
    product = productService.getByCode("TESTSKU", en);
    // check the product
    Set<ProductAvailability> avails = product.getAvailabilities();
    for (ProductAvailability as : avails) {
        Set<ProductPrice> availabilityPrices = as.getPrices();
        for (ProductPrice ps : availabilityPrices) {
            System.out.println(ps.getProductPriceAmount().toString());
        }
    }
    // check availability
    Set<ProductPrice> availabilityPrices = availability.getPrices();
    for (ProductPrice ps : availabilityPrices) {
        System.out.println(ps.getProductPriceAmount().toString());
    }
    // configure shipping
    ShippingConfiguration shippingConfiguration = new ShippingConfiguration();
    // based on shipping or billing address
    shippingConfiguration.setShippingBasisType(ShippingBasisType.SHIPPING);
    shippingConfiguration.setShippingType(ShippingType.INTERNATIONAL);
    // individual item pricing or box packaging (see unit test above)
    shippingConfiguration.setShippingPackageType(ShippingPackageType.ITEM);
    // only if package type is package
    shippingConfiguration.setBoxHeight(5);
    shippingConfiguration.setBoxLength(5);
    shippingConfiguration.setBoxWidth(5);
    shippingConfiguration.setBoxWeight(1);
    shippingConfiguration.setMaxWeight(10);
    List<String> supportedCountries = new ArrayList<String>();
    supportedCountries.add("CA");
    supportedCountries.add("US");
    supportedCountries.add("UK");
    supportedCountries.add("FR");
    shippingService.setSupportedCountries(store, supportedCountries);
    CustomShippingQuotesConfiguration customConfiguration = new CustomShippingQuotesConfiguration();
    customConfiguration.setModuleCode("weightBased");
    customConfiguration.setActive(true);
    CustomShippingQuotesRegion northRegion = new CustomShippingQuotesRegion();
    northRegion.setCustomRegionName("NORTH");
    List<String> countries = new ArrayList<String>();
    countries.add("CA");
    countries.add("US");
    northRegion.setCountries(countries);
    CustomShippingQuoteWeightItem caQuote4 = new CustomShippingQuoteWeightItem();
    caQuote4.setMaximumWeight(4);
    caQuote4.setPrice(new BigDecimal(20));
    CustomShippingQuoteWeightItem caQuote10 = new CustomShippingQuoteWeightItem();
    caQuote10.setMaximumWeight(10);
    caQuote10.setPrice(new BigDecimal(50));
    CustomShippingQuoteWeightItem caQuote100 = new CustomShippingQuoteWeightItem();
    caQuote100.setMaximumWeight(100);
    caQuote100.setPrice(new BigDecimal(120));
    List<CustomShippingQuoteWeightItem> quotes = new ArrayList<CustomShippingQuoteWeightItem>();
    quotes.add(caQuote4);
    quotes.add(caQuote10);
    quotes.add(caQuote100);
    northRegion.setQuoteItems(quotes);
    customConfiguration.getRegions().add(northRegion);
    // create an integration configuration - USPS
    IntegrationConfiguration configuration = new IntegrationConfiguration();
    configuration.setActive(true);
    configuration.setEnvironment(Environment.TEST.name());
    configuration.setModuleCode("weightBased");
    // configure module
    shippingService.saveShippingConfiguration(shippingConfiguration, store);
    // create the basic configuration
    shippingService.saveShippingQuoteModuleConfiguration(configuration, store);
    // and the custom configuration
    shippingService.saveCustomShippingConfiguration("weightBased", customConfiguration, store);
    // now create ShippingProduct
    ShippingProduct shippingProduct1 = new ShippingProduct(product);
    FinalPrice price = pricingService.calculateProductPrice(product);
    shippingProduct1.setFinalPrice(price);
    List<ShippingProduct> shippingProducts = new ArrayList<ShippingProduct>();
    shippingProducts.add(shippingProduct1);
    Customer customer = new Customer();
    customer.setMerchantStore(store);
    customer.setEmailAddress("test@test.com");
    customer.setGender(CustomerGender.M);
    customer.setDefaultLanguage(en);
    customer.setAnonymous(true);
    customer.setCompany("ifactory");
    customer.setDateOfBirth(new Date());
    customer.setNick("My nick");
    customer.setPassword("123456");
    Delivery delivery = new Delivery();
    delivery.setAddress("Shipping address");
    delivery.setCity("Boucherville");
    delivery.setCountry(country);
    delivery.setZone(zone);
    delivery.setPostalCode("J5C-6J4");
    // overwrite delivery to US
    /*	    delivery.setPostalCode("90002");
	    delivery.setCountry(us);
	    Zone california = zoneService.getByCode("CA");
	    delivery.setZone(california);*/
    Billing billing = new Billing();
    billing.setAddress("Billing address");
    billing.setCountry(country);
    billing.setZone(zone);
    billing.setPostalCode("J4B-8J9");
    billing.setFirstName("Carl");
    billing.setLastName("Samson");
    customer.setBilling(billing);
    customer.setDelivery(delivery);
    customerService.create(customer);
    // for correlation
    Long dummyCartId = 0L;
    ShippingQuote shippingQuote = shippingService.getShippingQuote(dummyCartId, store, delivery, shippingProducts, en);
    Assert.notNull(shippingQuote);
}
Also used : Customer(com.salesmanager.core.model.customer.Customer) ArrayList(java.util.ArrayList) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) Product(com.salesmanager.core.model.catalog.product.Product) ProductPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) Language(com.salesmanager.core.model.reference.language.Language) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) CustomShippingQuoteWeightItem(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuoteWeightItem) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ProductPriceDescription(com.salesmanager.core.model.catalog.product.price.ProductPriceDescription) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) CustomShippingQuotesConfiguration(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesConfiguration) Zone(com.salesmanager.core.model.reference.zone.Zone) CustomShippingQuotesRegion(com.salesmanager.core.modules.integration.shipping.model.CustomShippingQuotesRegion) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) ProductType(com.salesmanager.core.model.catalog.product.type.ProductType) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) BigDecimal(java.math.BigDecimal) Date(java.util.Date) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) ProductDescription(com.salesmanager.core.model.catalog.product.description.ProductDescription) Delivery(com.salesmanager.core.model.common.Delivery) Ignore(org.junit.Ignore)

Aggregations

Language (com.salesmanager.core.model.reference.language.Language)148 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)115 ArrayList (java.util.ArrayList)58 List (java.util.List)56 ServiceException (com.salesmanager.core.business.exception.ServiceException)55 Collectors (java.util.stream.Collectors)50 Product (com.salesmanager.core.model.catalog.product.Product)45 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)44 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)42 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)38 Autowired (org.springframework.beans.factory.annotation.Autowired)35 ConversionException (com.salesmanager.core.business.exception.ConversionException)30 Category (com.salesmanager.core.model.catalog.category.Category)30 Validate (org.apache.commons.lang3.Validate)29 Customer (com.salesmanager.core.model.customer.Customer)28 Optional (java.util.Optional)28 Inject (javax.inject.Inject)28 Service (org.springframework.stereotype.Service)28 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)27 ImageFilePath (com.salesmanager.shop.utils.ImageFilePath)25