Search in sources :

Example 11 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class ShoppingCartController method addShoppingCartItem.

/**
 * Add an item to the ShoppingCart (AJAX exposed method)
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/addShoppingCartItem" }, method = RequestMethod.POST)
@ResponseBody
public ShoppingCartData addShoppingCartItem(@RequestBody final ShoppingCartItem item, final HttpServletRequest request, final HttpServletResponse response, final Locale locale) throws Exception {
    ShoppingCartData shoppingCart = null;
    // Look in the HttpSession to see if a customer is logged in
    MerchantStore store = getSessionAttribute(Constants.MERCHANT_STORE, request);
    Language language = (Language) request.getAttribute(Constants.LANGUAGE);
    Customer customer = getSessionAttribute(Constants.CUSTOMER, request);
    if (customer != null) {
        com.salesmanager.core.model.shoppingcart.ShoppingCart customerCart = shoppingCartService.getShoppingCart(customer);
        if (customerCart != null) {
            // if this cart has been fulfilled create a new cart
            if (customerCart.getOrderId() != null && customerCart.getOrderId().longValue() > 0) {
                customerCart = shoppingCartFacade.createCartModel(null, store, customer);
                // set new shopping cart code to item
                item.setCode(customerCart.getShoppingCartCode());
            }
            shoppingCart = shoppingCartFacade.getShoppingCartData(customerCart, language);
        } else {
            /**
             * BUG that used a previous customer cart
             */
            item.setCode(null);
        }
    }
    if (shoppingCart == null && !StringUtils.isBlank(item.getCode())) {
        shoppingCart = shoppingCartFacade.getShoppingCartData(item.getCode(), store, language);
    }
    if (shoppingCart != null) {
        if (shoppingCart.getOrderId() != null && shoppingCart.getOrderId().longValue() > 0) {
            // has been ordered, can't continue to use
            shoppingCart = null;
        }
    }
    // if shoppingCart is null create a new one
    if (shoppingCart == null) {
        shoppingCart = new ShoppingCartData();
        String code = UUID.randomUUID().toString().replaceAll("-", "");
        shoppingCart.setCode(code);
        item.setCode(code);
    }
    shoppingCart = shoppingCartFacade.addItemsToShoppingCart(shoppingCart, item, store, language, customer);
    request.getSession().setAttribute(Constants.SHOPPING_CART, shoppingCart.getCode());
    return shoppingCart;
}
Also used : Language(com.salesmanager.core.model.reference.language.Language) Customer(com.salesmanager.core.model.customer.Customer) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 12 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class ShoppingCartController method displayShoppingCart.

@RequestMapping(value = { "/shoppingCartByCode" }, method = { RequestMethod.GET })
public String displayShoppingCart(@ModelAttribute String shoppingCartCode, final Model model, HttpServletRequest request, HttpServletResponse response, final Locale locale) throws Exception {
    MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Customer customer = getSessionAttribute(Constants.CUSTOMER, request);
    Language language = (Language) request.getAttribute(Constants.LANGUAGE);
    if (StringUtils.isBlank(shoppingCartCode)) {
        return "redirect:/shop";
    }
    ShoppingCartData cart = shoppingCartFacade.getShoppingCartData(customer, merchantStore, shoppingCartCode, language);
    if (cart == null) {
        return "redirect:/shop";
    }
    Language lang = languageUtils.getRequestLanguage(request, response);
    // Filter unavailables
    List<ShoppingCartItem> unavailables = new ArrayList<ShoppingCartItem>();
    List<ShoppingCartItem> availables = new ArrayList<ShoppingCartItem>();
    // Take out items no more available
    List<ShoppingCartItem> items = cart.getShoppingCartItems();
    for (ShoppingCartItem item : items) {
        String code = item.getProductCode();
        Product p = productService.getByCode(code, lang);
        if (!p.isAvailable()) {
            unavailables.add(item);
        } else {
            availables.add(item);
        }
    }
    cart.setShoppingCartItems(availables);
    cart.setUnavailables(unavailables);
    // meta information
    PageInformation pageInformation = new PageInformation();
    pageInformation.setPageTitle(messages.getMessage("label.cart.placeorder", locale));
    request.setAttribute(Constants.REQUEST_PAGE_INFORMATION, pageInformation);
    request.getSession().setAttribute(Constants.SHOPPING_CART, cart.getCode());
    model.addAttribute("cart", cart);
    /**
     * template *
     */
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.ShoppingCart.shoppingCart).append(".").append(merchantStore.getStoreTemplate());
    return template.toString();
}
Also used : Language(com.salesmanager.core.model.reference.language.Language) Customer(com.salesmanager.core.model.customer.Customer) PageInformation(com.salesmanager.shop.model.shop.PageInformation) ArrayList(java.util.ArrayList) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.shop.model.shoppingcart.ShoppingCartItem) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class MiniCartController method displayMiniCart.

@RequestMapping(value = { "/displayMiniCartByCode" }, method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public ShoppingCartData displayMiniCart(final String shoppingCartCode, HttpServletRequest request, Model model) {
    Language language = (Language) request.getAttribute(Constants.LANGUAGE);
    try {
        MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
        Customer customer = getSessionAttribute(Constants.CUSTOMER, request);
        ShoppingCartData cart = shoppingCartFacade.getShoppingCartData(customer, merchantStore, shoppingCartCode, language);
        if (cart != null) {
            request.getSession().setAttribute(Constants.SHOPPING_CART, cart.getCode());
        } else {
            // make sure there is no cart here
            request.getSession().removeAttribute(Constants.SHOPPING_CART);
            // create an empty cart
            cart = new ShoppingCartData();
        }
        return cart;
    } catch (Exception e) {
        LOG.error("Error while getting the shopping cart", e);
    }
    return null;
}
Also used : Language(com.salesmanager.core.model.reference.language.Language) Customer(com.salesmanager.core.model.customer.Customer) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 14 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class ShoppingOrderDownloadController method downloadFile.

/**
 * Virtual product(s) download link
 * @param id
 * @param model
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping("/download/{orderId}/{id}.html")
@ResponseBody
public byte[] downloadFile(@PathVariable Long orderId, @PathVariable Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    FileContentType fileType = FileContentType.PRODUCT_DIGITAL;
    // get customer and check order
    Order order = orderService.getById(orderId);
    if (order == null) {
        LOGGER.warn("Order is null for id " + orderId);
        response.sendError(404, "Image not found");
        return null;
    }
    // order belongs to customer
    Customer customer = (Customer) super.getSessionAttribute(Constants.CUSTOMER, request);
    if (customer == null) {
        response.sendError(404, "Image not found");
        return null;
    }
    // get it from OrderProductDownlaod
    String fileName = null;
    OrderProductDownload download = orderProductDownloadService.getById(id);
    if (download == null) {
        LOGGER.warn("OrderProductDownload is null for id " + id);
        response.sendError(404, "Image not found");
        return null;
    }
    fileName = download.getOrderProductFilename();
    // needs to query the new API
    OutputContentFile file = contentService.getContentFile(store.getCode(), fileType, fileName);
    if (file != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        return file.getFile().toByteArray();
    } else {
        LOGGER.warn("Image not found for OrderProductDownload id " + id);
        response.sendError(404, "Image not found");
        return null;
    }
// product image
// example -> /download/12345/120.html
}
Also used : Order(com.salesmanager.core.model.order.Order) Customer(com.salesmanager.core.model.customer.Customer) OutputContentFile(com.salesmanager.core.model.content.OutputContentFile) OrderProductDownload(com.salesmanager.core.model.order.orderproduct.OrderProductDownload) FileContentType(com.salesmanager.core.model.content.FileContentType) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 15 with Customer

use of com.salesmanager.core.model.customer.Customer 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)

Aggregations

Customer (com.salesmanager.core.model.customer.Customer)71 PersistableCustomer (com.salesmanager.shop.model.customer.PersistableCustomer)33 ReadableCustomer (com.salesmanager.shop.model.customer.ReadableCustomer)32 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)31 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)30 Language (com.salesmanager.core.model.reference.language.Language)26 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)17 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)17 ConversionException (com.salesmanager.core.business.exception.ConversionException)16 ServiceException (com.salesmanager.core.business.exception.ServiceException)16 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)16 ShoppingCart (com.salesmanager.core.model.shoppingcart.ShoppingCart)12 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)12 Authentication (org.springframework.security.core.Authentication)12 Date (java.util.Date)11 ConversionRuntimeException (com.salesmanager.shop.store.api.exception.ConversionRuntimeException)10 ArrayList (java.util.ArrayList)10 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)10 Product (com.salesmanager.core.model.catalog.product.Product)9 Country (com.salesmanager.core.model.reference.country.Country)9