Search in sources :

Example 1 with UserContext

use of com.salesmanager.core.model.common.UserContext 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 2 with UserContext

use of com.salesmanager.core.model.common.UserContext in project shopizer by shopizer-ecommerce.

the class ShippingServiceImpl method getShippingQuote.

@Override
public ShippingQuote getShippingQuote(Long shoppingCartId, MerchantStore store, Delivery delivery, List<ShippingProduct> products, Language language) throws ServiceException {
    // ShippingConfiguration -> Global configuration of a given store
    // IntegrationConfiguration -> Configuration of a given module
    // IntegrationModule -> The concrete module as defined in integrationmodules.properties
    // delivery without postal code is accepted
    Validate.notNull(store, "MerchantStore must not be null");
    Validate.notNull(delivery, "Delivery must not be null");
    Validate.notEmpty(products, "products must not be empty");
    Validate.notNull(language, "Language must not be null");
    ShippingQuote shippingQuote = new ShippingQuote();
    ShippingQuoteModule shippingQuoteModule = null;
    try {
        if (StringUtils.isBlank(delivery.getPostalCode())) {
            shippingQuote.getWarnings().add("No postal code in delivery address");
            shippingQuote.setShippingReturnCode(ShippingQuote.NO_POSTAL_CODE);
        }
        // get configuration
        ShippingConfiguration shippingConfiguration = getShippingConfiguration(store);
        ShippingType shippingType = ShippingType.INTERNATIONAL;
        /**
         * get shipping origin *
         */
        ShippingOrigin shippingOrigin = shippingOriginService.getByStore(store);
        if (shippingOrigin == null || !shippingOrigin.isActive()) {
            shippingOrigin = new ShippingOrigin();
            shippingOrigin.setAddress(store.getStoreaddress());
            shippingOrigin.setCity(store.getStorecity());
            shippingOrigin.setCountry(store.getCountry());
            shippingOrigin.setPostalCode(store.getStorepostalcode());
            shippingOrigin.setState(store.getStorestateprovince());
            shippingOrigin.setZone(store.getZone());
        }
        if (shippingConfiguration == null) {
            shippingConfiguration = new ShippingConfiguration();
        }
        if (shippingConfiguration.getShippingType() != null) {
            shippingType = shippingConfiguration.getShippingType();
        }
        // look if customer country code excluded
        Country shipCountry = delivery.getCountry();
        // a ship to country is required
        Validate.notNull(shipCountry, "Ship to Country cannot be null");
        Validate.notNull(store.getCountry(), "Store Country canot be null");
        if (shippingType.name().equals(ShippingType.NATIONAL.name())) {
            // customer country must match store country
            if (!shipCountry.getIsoCode().equals(store.getCountry().getIsoCode())) {
                shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
                return shippingQuote;
            }
        } else if (shippingType.name().equals(ShippingType.INTERNATIONAL.name())) {
            // customer shipping country code must be in accepted list
            List<String> supportedCountries = this.getSupportedCountries(store);
            if (!supportedCountries.contains(shipCountry.getIsoCode())) {
                shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY + " " + shipCountry.getIsoCode());
                return shippingQuote;
            }
        }
        // must have a shipping module configured
        Map<String, IntegrationConfiguration> modules = this.getShippingModulesConfigured(store);
        if (modules == null) {
            shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
            return shippingQuote;
        }
        /**
         * uses this module name *
         */
        String moduleName = null;
        IntegrationConfiguration configuration = null;
        for (String module : modules.keySet()) {
            moduleName = module;
            configuration = modules.get(module);
            // use the first active module
            if (configuration.isActive()) {
                shippingQuoteModule = shippingModules.get(module);
                if (shippingQuoteModule instanceof ShippingQuotePrePostProcessModule) {
                    shippingQuoteModule = null;
                    continue;
                } else {
                    break;
                }
            }
        }
        if (shippingQuoteModule == null) {
            shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
            return shippingQuote;
        }
        /**
         * merchant module configs *
         */
        List<IntegrationModule> shippingMethods = this.getShippingMethods(store);
        IntegrationModule shippingModule = null;
        for (IntegrationModule mod : shippingMethods) {
            if (mod.getCode().equals(moduleName)) {
                shippingModule = mod;
                break;
            }
        }
        /**
         * general module configs *
         */
        if (shippingModule == null) {
            shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED);
            return shippingQuote;
        }
        // calculate order total
        BigDecimal orderTotal = calculateOrderTotal(products, store);
        List<PackageDetails> packages = getPackagesDetails(products, store);
        // free shipping ?
        boolean freeShipping = false;
        if (shippingConfiguration.isFreeShippingEnabled()) {
            BigDecimal freeShippingAmount = shippingConfiguration.getOrderTotalFreeShipping();
            if (freeShippingAmount != null) {
                if (orderTotal.doubleValue() > freeShippingAmount.doubleValue()) {
                    if (shippingConfiguration.getFreeShippingType() == ShippingType.NATIONAL) {
                        if (store.getCountry().getIsoCode().equals(shipCountry.getIsoCode())) {
                            freeShipping = true;
                            shippingQuote.setFreeShipping(true);
                            shippingQuote.setFreeShippingAmount(freeShippingAmount);
                            return shippingQuote;
                        }
                    } else {
                        // international all
                        freeShipping = true;
                        shippingQuote.setFreeShipping(true);
                        shippingQuote.setFreeShippingAmount(freeShippingAmount);
                        return shippingQuote;
                    }
                }
            }
        }
        // handling fees
        BigDecimal handlingFees = shippingConfiguration.getHandlingFees();
        if (handlingFees != null) {
            shippingQuote.setHandlingFees(handlingFees);
        }
        // tax basis
        shippingQuote.setApplyTaxOnShipping(shippingConfiguration.isTaxOnShipping());
        Locale locale = languageService.toLocale(language, store);
        // also available distance calculation
        if (!CollectionUtils.isEmpty(shippingModulePreProcessors)) {
            for (ShippingQuotePrePostProcessModule preProcessor : shippingModulePreProcessors) {
                // System.out.println("Using pre-processor " + preProcessor.getModuleCode());
                preProcessor.prePostProcessShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, configuration, shippingModule, shippingConfiguration, shippingMethods, locale);
                // TODO switch module if required
                if (shippingQuote.getCurrentShippingModule() != null && !shippingQuote.getCurrentShippingModule().getCode().equals(shippingModule.getCode())) {
                    // determines the shipping module
                    shippingModule = shippingQuote.getCurrentShippingModule();
                    configuration = modules.get(shippingModule.getCode());
                    if (configuration != null) {
                        if (configuration.isActive()) {
                            moduleName = shippingModule.getCode();
                            shippingQuoteModule = this.shippingModules.get(shippingModule.getCode());
                            configuration = modules.get(shippingModule.getCode());
                        }
                    // TODO use default
                    }
                }
            }
        }
        // invoke module
        List<ShippingOption> shippingOptions = null;
        try {
            shippingOptions = shippingQuoteModule.getShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, configuration, shippingModule, shippingConfiguration, locale);
        } catch (Exception e) {
            LOGGER.error("Error while calculating shipping : " + e.getMessage(), e);
        /*				merchantLogService.save(
						new MerchantLog(store,
								"Can't process " + shippingModule.getModule()
								+ " -> "
								+ e.getMessage()));
				shippingQuote.setQuoteError(e.getMessage());
				shippingQuote.setShippingReturnCode(ShippingQuote.ERROR);
				return shippingQuote;*/
        }
        if (shippingOptions == null && !StringUtils.isBlank(delivery.getPostalCode())) {
            // absolutely need to use in this case store pickup or other default shipping quote
            shippingQuote.setShippingReturnCode(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY);
        }
        shippingQuote.setShippingModuleCode(moduleName);
        // filter shipping options
        ShippingOptionPriceType shippingOptionPriceType = shippingConfiguration.getShippingOptionPriceType();
        ShippingOption selectedOption = null;
        if (shippingOptions != null) {
            for (ShippingOption option : shippingOptions) {
                if (selectedOption == null) {
                    selectedOption = option;
                }
                // set price text
                String priceText = pricingService.getDisplayAmount(option.getOptionPrice(), store);
                option.setOptionPriceText(priceText);
                option.setShippingModuleCode(moduleName);
                if (StringUtils.isBlank(option.getOptionName())) {
                    String countryName = delivery.getCountry().getName();
                    if (countryName == null) {
                        Map<String, Country> deliveryCountries = countryService.getCountriesMap(language);
                        Country dCountry = deliveryCountries.get(delivery.getCountry().getIsoCode());
                        if (dCountry != null) {
                            countryName = dCountry.getName();
                        } else {
                            countryName = delivery.getCountry().getIsoCode();
                        }
                    }
                    option.setOptionName(countryName);
                }
                if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.HIGHEST.name())) {
                    if (option.getOptionPrice().longValue() > selectedOption.getOptionPrice().longValue()) {
                        selectedOption = option;
                    }
                }
                if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.LEAST.name())) {
                    if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
                        selectedOption = option;
                    }
                }
                if (shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {
                    if (option.getOptionPrice().longValue() < selectedOption.getOptionPrice().longValue()) {
                        selectedOption = option;
                    }
                }
            }
            shippingQuote.setSelectedShippingOption(selectedOption);
            if (selectedOption != null && !shippingOptionPriceType.name().equals(ShippingOptionPriceType.ALL.name())) {
                shippingOptions = new ArrayList<ShippingOption>();
                shippingOptions.add(selectedOption);
            }
        }
        /**
         * set final delivery address *
         */
        shippingQuote.setDeliveryAddress(delivery);
        shippingQuote.setShippingOptions(shippingOptions);
        // invoke pre processors
        if (!CollectionUtils.isEmpty(shippingModulePostProcessors)) {
            for (ShippingQuotePrePostProcessModule postProcessor : shippingModulePostProcessors) {
                // get module info
                // get module configuration
                IntegrationConfiguration integrationConfiguration = modules.get(postProcessor.getModuleCode());
                IntegrationModule postProcessModule = null;
                for (IntegrationModule mod : shippingMethods) {
                    if (mod.getCode().equals(postProcessor.getModuleCode())) {
                        postProcessModule = mod;
                        break;
                    }
                }
                IntegrationModule module = postProcessModule;
                if (integrationConfiguration != null) {
                    postProcessor.prePostProcessShippingQuotes(shippingQuote, packages, orderTotal, delivery, shippingOrigin, store, integrationConfiguration, module, shippingConfiguration, shippingMethods, locale);
                }
            }
        }
        String ipAddress = null;
        UserContext context = UserContext.getCurrentInstance();
        if (context != null) {
            ipAddress = context.getIpAddress();
        }
        if (shippingQuote != null && CollectionUtils.isNotEmpty(shippingQuote.getShippingOptions())) {
            // save SHIPPING OPTIONS
            List<ShippingOption> finalShippingOptions = shippingQuote.getShippingOptions();
            for (ShippingOption option : finalShippingOptions) {
                // transform to Quote
                Quote q = new Quote();
                q.setCartId(shoppingCartId);
                q.setDelivery(delivery);
                if (!StringUtils.isBlank(ipAddress)) {
                    q.setIpAddress(ipAddress);
                }
                if (!StringUtils.isBlank(option.getEstimatedNumberOfDays())) {
                    try {
                        q.setEstimatedNumberOfDays(Integer.valueOf(option.getEstimatedNumberOfDays()));
                    } catch (Exception e) {
                        LOGGER.error("Cannot cast to integer " + option.getEstimatedNumberOfDays());
                    }
                }
                if (freeShipping) {
                    q.setFreeShipping(true);
                    q.setPrice(new BigDecimal(0));
                    q.setModule("FREE");
                    q.setOptionCode("FREE");
                    q.setOptionName("FREE");
                } else {
                    q.setModule(option.getShippingModuleCode());
                    q.setOptionCode(option.getOptionCode());
                    if (!StringUtils.isBlank(option.getOptionDeliveryDate())) {
                        try {
                            q.setOptionDeliveryDate(DateUtil.formatDate(option.getOptionDeliveryDate()));
                        } catch (Exception e) {
                            LOGGER.error("Cannot transform to date " + option.getOptionDeliveryDate());
                        }
                    }
                    q.setOptionName(option.getOptionName());
                    q.setOptionShippingDate(new Date());
                    q.setPrice(option.getOptionPrice());
                }
                if (handlingFees != null) {
                    q.setHandling(handlingFees);
                }
                q.setQuoteDate(new Date());
                shippingQuoteService.save(q);
                option.setShippingQuoteOptionId(q.getId());
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ServiceException(e);
    }
    return shippingQuote;
}
Also used : Locale(java.util.Locale) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) ShippingType(com.salesmanager.core.model.shipping.ShippingType) UserContext(com.salesmanager.core.model.common.UserContext) CustomIntegrationConfiguration(com.salesmanager.core.model.system.CustomIntegrationConfiguration) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) BigDecimal(java.math.BigDecimal) ServiceException(com.salesmanager.core.business.exception.ServiceException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) Date(java.util.Date) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Quote(com.salesmanager.core.model.shipping.Quote) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ShippingOptionPriceType(com.salesmanager.core.model.shipping.ShippingOptionPriceType) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingQuoteModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuoteModule) Country(com.salesmanager.core.model.reference.country.Country) ShippingQuotePrePostProcessModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuotePrePostProcessModule) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails)

Example 3 with UserContext

use of com.salesmanager.core.model.common.UserContext in project shopizer by shopizer-ecommerce.

the class ShoppingCartServiceImpl method saveOrUpdate.

/**
 * Save or update a {@link ShoppingCart} for a given customer
 */
@Override
public void saveOrUpdate(ShoppingCart shoppingCart) throws ServiceException {
    Validate.notNull(shoppingCart, "ShoppingCart must not be null");
    Validate.notNull(shoppingCart.getMerchantStore(), "ShoppingCart.merchantStore must not be null");
    try {
        UserContext userContext = UserContext.getCurrentInstance();
        if (userContext != null) {
            shoppingCart.setIpAddress(userContext.getIpAddress());
        }
    } catch (Exception s) {
        LOGGER.error("Cannot add ip address to shopping cart ", s);
    }
    if (shoppingCart.getId() == null || shoppingCart.getId() == 0) {
        super.create(shoppingCart);
    } else {
        super.update(shoppingCart);
    }
}
Also used : UserContext(com.salesmanager.core.model.common.UserContext) ServiceException(com.salesmanager.core.business.exception.ServiceException)

Example 4 with UserContext

use of com.salesmanager.core.model.common.UserContext in project shopizer by shopizer-ecommerce.

the class OrderServiceImpl method process.

private Order process(Order order, Customer customer, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, Transaction transaction, MerchantStore store) throws ServiceException {
    Validate.notNull(order, "Order cannot be null");
    Validate.notNull(customer, "Customer cannot be null (even if anonymous order)");
    Validate.notEmpty(items, "ShoppingCart items cannot be null");
    Validate.notNull(payment, "Payment cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    Validate.notNull(summary, "Order total Summary cannot be null");
    UserContext context = UserContext.getCurrentInstance();
    if (context != null) {
        String ipAddress = context.getIpAddress();
        if (!StringUtils.isBlank(ipAddress)) {
            order.setIpAddress(ipAddress);
        }
    }
    // first process payment
    Transaction processTransaction = paymentService.processPayment(customer, store, payment, items, order);
    if (order.getOrderHistory() == null || order.getOrderHistory().size() == 0 || order.getStatus() == null) {
        OrderStatus status = order.getStatus();
        if (status == null) {
            status = OrderStatus.ORDERED;
            order.setStatus(status);
        }
        Set<OrderStatusHistory> statusHistorySet = new HashSet<OrderStatusHistory>();
        OrderStatusHistory statusHistory = new OrderStatusHistory();
        statusHistory.setStatus(status);
        statusHistory.setDateAdded(new Date());
        statusHistory.setOrder(order);
        statusHistorySet.add(statusHistory);
        order.setOrderHistory(statusHistorySet);
    }
    if (customer.getId() == null || customer.getId() == 0) {
        customerService.create(customer);
    }
    order.setCustomerId(customer.getId());
    this.create(order);
    if (transaction != null) {
        transaction.setOrder(order);
        if (transaction.getId() == null || transaction.getId() == 0) {
            transactionService.create(transaction);
        } else {
            transactionService.update(transaction);
        }
    }
    if (processTransaction != null) {
        processTransaction.setOrder(order);
        if (processTransaction.getId() == null || processTransaction.getId() == 0) {
            transactionService.create(processTransaction);
        } else {
            transactionService.update(processTransaction);
        }
    }
    /**
     * decrement inventory
     */
    LOGGER.debug("Update inventory");
    Set<OrderProduct> products = order.getOrderProducts();
    for (OrderProduct orderProduct : products) {
        orderProduct.getProductQuantity();
        Product p = productService.getById(orderProduct.getId());
        if (p == null)
            throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
        for (ProductAvailability availability : p.getAvailabilities()) {
            int qty = availability.getProductQuantity();
            if (qty < orderProduct.getProductQuantity()) {
                // throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
                LOGGER.error("APP-BACKEND [" + ServiceException.EXCEPTION_INVENTORY_MISMATCH + "]");
            }
            qty = qty - orderProduct.getProductQuantity();
            availability.setProductQuantity(qty);
        }
        productService.update(p);
    }
    return order;
}
Also used : OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) UserContext(com.salesmanager.core.model.common.UserContext) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Product(com.salesmanager.core.model.catalog.product.Product) Date(java.util.Date) LocalDate(java.time.LocalDate) OrderStatus(com.salesmanager.core.model.order.orderstatus.OrderStatus) Transaction(com.salesmanager.core.model.payments.Transaction) ServiceException(com.salesmanager.core.business.exception.ServiceException) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) HashSet(java.util.HashSet)

Example 5 with UserContext

use of com.salesmanager.core.model.common.UserContext in project shopizer by shopizer-ecommerce.

the class AuthenticationTokenFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String origin = "*";
    if (!StringUtils.isBlank(request.getHeader("origin"))) {
        origin = request.getHeader("origin");
    }
    // in flight
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    response.setHeader("Access-Control-Allow-Origin", origin);
    response.setHeader("Access-Control-Allow-Headers", "X-Auth-Token, Content-Type, Authorization, Cache-Control, X-Requested-With");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    try {
        String ipAddress = GeoLocationUtils.getClientIpAddress(request);
        UserContext userContext = UserContext.create();
        userContext.setIpAddress(ipAddress);
    } catch (Exception s) {
        LOGGER.error("Error while getting ip address ", s);
    }
    String requestUrl = request.getRequestURL().toString();
    if (requestUrl.contains("/api/v1/auth")) {
        // setHeader(request,response);
        // token
        final String requestHeader = request.getHeader(this.tokenHeader);
        try {
            if (requestHeader != null && requestHeader.startsWith(BEARER_TOKEN)) {
                // Bearer
                jwtCustomCustomerAuthenticationManager.authenticateRequest(request, response);
            } else if (requestHeader != null && requestHeader.startsWith(FACEBOOK_TOKEN)) {
            // Facebook
            // facebookCustomerAuthenticationManager.authenticateRequest(request, response);
            } else {
                LOGGER.warn("couldn't find any authorization token, will ignore the header");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    if (requestUrl.contains("/api/v1/private") || requestUrl.contains("/api/v2/private")) {
        // setHeader(request,response);
        Enumeration<String> headers = request.getHeaderNames();
        // while(headers.hasMoreElements()) {
        // LOGGER.debug(headers.nextElement());
        // }
        // token
        final String requestHeader = request.getHeader(this.tokenHeader);
        try {
            if (requestHeader != null && requestHeader.startsWith(BEARER_TOKEN)) {
                // Bearer
                jwtCustomAdminAuthenticationManager.authenticateRequest(request, response);
            } else {
                LOGGER.warn("couldn't find any authorization token, will ignore the header, might be a preflight check");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    chain.doFilter(request, response);
    postFilter(request, response, chain);
}
Also used : ServletException(javax.servlet.ServletException) UserContext(com.salesmanager.core.model.common.UserContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

UserContext (com.salesmanager.core.model.common.UserContext)5 ServiceException (com.salesmanager.core.business.exception.ServiceException)3 Date (java.util.Date)2 Product (com.salesmanager.core.model.catalog.product.Product)1 ProductAvailability (com.salesmanager.core.model.catalog.product.availability.ProductAvailability)1 ContentDescription (com.salesmanager.core.model.content.ContentDescription)1 Customer (com.salesmanager.core.model.customer.Customer)1 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)1 OrderProduct (com.salesmanager.core.model.order.orderproduct.OrderProduct)1 OrderStatus (com.salesmanager.core.model.order.orderstatus.OrderStatus)1 OrderStatusHistory (com.salesmanager.core.model.order.orderstatus.OrderStatusHistory)1 Transaction (com.salesmanager.core.model.payments.Transaction)1 Country (com.salesmanager.core.model.reference.country.Country)1 Language (com.salesmanager.core.model.reference.language.Language)1 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)1 Quote (com.salesmanager.core.model.shipping.Quote)1 ShippingConfiguration (com.salesmanager.core.model.shipping.ShippingConfiguration)1 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)1 ShippingOptionPriceType (com.salesmanager.core.model.shipping.ShippingOptionPriceType)1 ShippingOrigin (com.salesmanager.core.model.shipping.ShippingOrigin)1