Search in sources :

Example 31 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class ReadableCustomerDeliveryAddressPopulator method populate.

@Override
public ReadableDelivery populate(Delivery source, ReadableDelivery target, MerchantStore store, Language language) throws ConversionException {
    if (countryService == null) {
        throw new ConversionException("countryService must be set");
    }
    if (zoneService == null) {
        throw new ConversionException("zoneService must be set");
    }
    target.setLatitude(source.getLatitude());
    target.setLongitude(source.getLongitude());
    if (StringUtils.isNotBlank(source.getCity())) {
        target.setCity(source.getCity());
    }
    if (StringUtils.isNotBlank(source.getCompany())) {
        target.setCompany(source.getCompany());
    }
    if (StringUtils.isNotBlank(source.getAddress())) {
        target.setAddress(source.getAddress());
    }
    if (StringUtils.isNotBlank(source.getFirstName())) {
        target.setFirstName(source.getFirstName());
    }
    if (StringUtils.isNotBlank(source.getLastName())) {
        target.setLastName(source.getLastName());
    }
    if (StringUtils.isNotBlank(source.getPostalCode())) {
        target.setPostalCode(source.getPostalCode());
    }
    if (StringUtils.isNotBlank(source.getTelephone())) {
        target.setPhone(source.getTelephone());
    }
    target.setStateProvince(source.getState());
    if (source.getTelephone() == null) {
        target.setPhone(source.getTelephone());
    }
    target.setAddress(source.getAddress());
    if (source.getCountry() != null) {
        target.setCountry(source.getCountry().getIsoCode());
        // resolve country name
        try {
            Map<String, Country> countries = countryService.getCountriesMap(language);
            Country c = countries.get(source.getCountry().getIsoCode());
            if (c != null) {
                target.setCountryName(c.getName());
            }
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            throw new ConversionException(e);
        }
    }
    if (source.getZone() != null) {
        target.setZone(source.getZone().getCode());
        // resolve zone name
        try {
            Map<String, Zone> zones = zoneService.getZones(language);
            Zone z = zones.get(source.getZone().getCode());
            if (z != null) {
                target.setProvinceName(z.getName());
            }
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            throw new ConversionException(e);
        }
    }
    return target;
}
Also used : ConversionException(com.salesmanager.core.business.exception.ConversionException) ServiceException(com.salesmanager.core.business.exception.ServiceException) Zone(com.salesmanager.core.model.reference.zone.Zone) Country(com.salesmanager.core.model.reference.country.Country)

Example 32 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class ShoppingOrderConfirmationController method displayConfirmation.

/**
 * Invoked once the payment is complete and order is fulfilled
 * @param model
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@RequestMapping("/confirmation.html")
public String displayConfirmation(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Long orderId = super.getSessionAttribute(Constants.ORDER_ID, request);
    if (orderId == null) {
        return new StringBuilder().append("redirect:").append(Constants.SHOP_URI).toString();
    }
    // get the order
    Order order = orderService.getById(orderId);
    if (order == null) {
        LOGGER.warn("Order id [" + orderId + "] does not exist");
        throw new Exception("Order id [" + orderId + "] does not exist");
    }
    if (order.getMerchant().getId().intValue() != store.getId().intValue()) {
        LOGGER.warn("Store id [" + store.getId() + "] differs from order.store.id [" + order.getMerchant().getId() + "]");
        return new StringBuilder().append("redirect:").append(Constants.SHOP_URI).toString();
    }
    if (super.getSessionAttribute(Constants.ORDER_ID_TOKEN, request) != null) {
        // set this unique token for performing unique operations in the confirmation
        model.addAttribute("confirmation", "confirmation");
    }
    // remove unique token
    super.removeAttribute(Constants.ORDER_ID_TOKEN, request);
    String[] orderMessageParams = { store.getStorename() };
    String orderMessage = messages.getMessage("label.checkout.text", orderMessageParams, locale);
    model.addAttribute("ordermessage", orderMessage);
    String[] orderIdParams = { String.valueOf(order.getId()) };
    String orderMessageId = messages.getMessage("label.checkout.orderid", orderIdParams, locale);
    model.addAttribute("ordermessageid", orderMessageId);
    String[] orderEmailParams = { order.getCustomerEmailAddress() };
    String orderEmailMessage = messages.getMessage("label.checkout.email", orderEmailParams, locale);
    model.addAttribute("orderemail", orderEmailMessage);
    ReadableOrder readableOrder = orderFacade.getReadableOrder(orderId, store, language);
    // resolve country and Zone for GA
    String countryCode = readableOrder.getCustomer().getBilling().getCountry();
    Map<String, Country> countriesMap = countryService.getCountriesMap(language);
    Country billingCountry = countriesMap.get(countryCode);
    if (billingCountry != null) {
        readableOrder.getCustomer().getBilling().setCountry(billingCountry.getName());
    }
    String zoneCode = readableOrder.getCustomer().getBilling().getZone();
    Map<String, Zone> zonesMap = zoneService.getZones(language);
    Zone billingZone = zonesMap.get(zoneCode);
    if (billingZone != null) {
        readableOrder.getCustomer().getBilling().setZone(billingZone.getName());
    }
    model.addAttribute("order", readableOrder);
    // check if any downloads exist for this order
    List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(order.getId());
    if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
        ReadableOrderProductDownloadPopulator populator = new ReadableOrderProductDownloadPopulator();
        List<ReadableOrderProductDownload> downloads = new ArrayList<ReadableOrderProductDownload>();
        for (OrderProductDownload download : orderProductDownloads) {
            ReadableOrderProductDownload view = new ReadableOrderProductDownload();
            populator.populate(download, view, store, language);
            downloads.add(view);
        }
        model.addAttribute("downloads", downloads);
    }
    /**
     * template *
     */
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.confirmation).append(".").append(store.getStoreTemplate());
    return template.toString();
}
Also used : Order(com.salesmanager.core.model.order.Order) ReadableOrder(com.salesmanager.shop.model.order.v0.ReadableOrder) ReadableOrderProductDownloadPopulator(com.salesmanager.shop.populator.order.ReadableOrderProductDownloadPopulator) Zone(com.salesmanager.core.model.reference.zone.Zone) ReadableOrderProductDownload(com.salesmanager.shop.model.order.ReadableOrderProductDownload) ArrayList(java.util.ArrayList) ReadableOrder(com.salesmanager.shop.model.order.v0.ReadableOrder) Language(com.salesmanager.core.model.reference.language.Language) Country(com.salesmanager.core.model.reference.country.Country) OrderProductDownload(com.salesmanager.core.model.order.orderproduct.OrderProductDownload) ReadableOrderProductDownload(com.salesmanager.shop.model.order.ReadableOrderProductDownload) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 33 with Country

use of com.salesmanager.core.model.reference.country.Country in project shopizer by shopizer-ecommerce.

the class ShoppingOrderController method commitOrder.

@SuppressWarnings("unchecked")
@RequestMapping("/commitOrder.html")
public String commitOrder(@CookieValue("cart") String cookie, @Valid @ModelAttribute(value = "order") ShopOrder order, BindingResult bindingResult, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = (Language) request.getAttribute("LANGUAGE");
    // validate if session has expired
    model.addAttribute("googleMapsKey", googleMapsKey);
    // display hacks
    if (!StringUtils.isBlank(googleMapsKey)) {
        model.addAttribute("disabled", "true");
        model.addAttribute("cssClass", "");
    } else {
        model.addAttribute("disabled", "false");
        model.addAttribute("cssClass", "required");
    }
    model.addAttribute("order", order);
    Map<String, Object> configs = (Map<String, Object>) request.getAttribute(Constants.REQUEST_CONFIGS);
    if (configs != null && configs.containsKey(Constants.DEBUG_MODE)) {
        Boolean debugMode = (Boolean) configs.get(Constants.DEBUG_MODE);
        if (debugMode) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                String jsonInString = mapper.writeValueAsString(order);
                LOGGER.debug("Commit order -> " + jsonInString);
            } catch (Exception de) {
                LOGGER.error(de.getMessage());
            }
        }
    }
    try {
        /**
         * Retrieve shopping cart and metadata
         * (information required to process order)
         *
         * - Cart rerieved from cookie or from user session
         * - Retrieves payment metadata
         */
        ShippingMetaData shippingMetaData = shippingService.getShippingMetaData(store);
        model.addAttribute("shippingMetaData", shippingMetaData);
        // basic stuff
        String shoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
        if (shoppingCartCode == null) {
            if (cookie == null) {
                // session expired and cookie null, nothing to do
                StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Pages.timeout).append(".").append(store.getStoreTemplate());
                return template.toString();
            }
            String[] merchantCookie = cookie.split("_");
            String merchantStoreCode = merchantCookie[0];
            if (!merchantStoreCode.equals(store.getCode())) {
                StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Pages.timeout).append(".").append(store.getStoreTemplate());
                return template.toString();
            }
            shoppingCartCode = merchantCookie[1];
        }
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = null;
        if (StringUtils.isBlank(shoppingCartCode)) {
            StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Pages.timeout).append(".").append(store.getStoreTemplate());
            return template.toString();
        }
        cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        // readable shopping cart items for order summary box
        ShoppingCartData shoppingCart = shoppingCartFacade.getShoppingCartData(cart, language);
        model.addAttribute("cart", shoppingCart);
        boolean freeShoppingCart = true;
        Set<ShoppingCartItem> items = cart.getLineItems();
        List<ShoppingCartItem> cartItems = new ArrayList<ShoppingCartItem>(items);
        order.setShoppingCartItems(cartItems);
        for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
            Long id = item.getProduct().getId();
            Product p = productService.getById(id);
            FinalPrice finalPrice = pricingService.calculateProductPrice(p);
            if (finalPrice.getFinalPrice().longValue() > 0) {
                freeShoppingCart = false;
            }
        }
        // get payment methods
        List<PaymentMethod> paymentMethods = paymentService.getAcceptedPaymentMethods(store);
        // not free and no payment methods
        if (CollectionUtils.isEmpty(paymentMethods) && !freeShoppingCart) {
            LOGGER.error("No payment method configured");
            model.addAttribute("errorMessages", "No payments configured");
        }
        if (!CollectionUtils.isEmpty(paymentMethods)) {
            // select default payment method
            PaymentMethod defaultPaymentSelected = null;
            for (PaymentMethod paymentMethod : paymentMethods) {
                if (paymentMethod.isDefaultSelected()) {
                    defaultPaymentSelected = paymentMethod;
                    break;
                }
            }
            if (defaultPaymentSelected == null) {
                // forced default selection
                defaultPaymentSelected = paymentMethods.get(0);
                defaultPaymentSelected.setDefaultSelected(true);
            }
        }
        /**
         * Prepare failure data
         * - Get another shipping quote
         */
        ShippingQuote quote = orderFacade.getShippingQuote(order.getCustomer(), cart, order, store, language);
        if (quote != null) {
            // save quotes in HttpSession
            List<ShippingOption> options = quote.getShippingOptions();
            request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
            if (!CollectionUtils.isEmpty(options)) {
                for (ShippingOption shipOption : options) {
                    LOGGER.info("Looking at shipping option " + shipOption.getOptionCode());
                    StringBuilder moduleName = new StringBuilder();
                    moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                    String carrier = messages.getMessage(moduleName.toString(), new String[] { store.getStorename() }, locale);
                    shipOption.setDescription(carrier);
                    // option name
                    if (!StringUtils.isBlank(shipOption.getOptionCode())) {
                        // try to get the translate
                        StringBuilder optionCodeBuilder = new StringBuilder();
                        try {
                            optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode()).append(".").append(shipOption.getOptionCode());
                            String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                            shipOption.setOptionName(optionName);
                        } catch (Exception e) {
                            // label not found
                            LOGGER.warn("commitOrder No shipping code found for " + optionCodeBuilder.toString());
                        }
                    }
                }
            }
            if (quote.getDeliveryAddress() != null) {
                ReadableCustomerDeliveryAddressPopulator addressPopulator = new ReadableCustomerDeliveryAddressPopulator();
                addressPopulator.setCountryService(countryService);
                addressPopulator.setZoneService(zoneService);
                ReadableDelivery deliveryAddress = new ReadableDelivery();
                addressPopulator.populate(quote.getDeliveryAddress(), deliveryAddress, store, language);
                model.addAttribute("deliveryAddress", deliveryAddress);
            }
        }
        model.addAttribute("shippingQuote", quote);
        model.addAttribute("paymentMethods", paymentMethods);
        if (quote != null) {
            List<Country> shippingCountriesList = orderFacade.getShipToCountry(store, language);
            model.addAttribute("countries", shippingCountriesList);
        } else {
            // get all countries
            List<Country> countries = countryService.getCountries(language);
            model.addAttribute("countries", countries);
        }
        // set shipping summary
        if (order.getSelectedShippingOption() != null) {
            ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute(Constants.SHIPPING_SUMMARY);
            List<ShippingOption> options = (List<ShippingOption>) request.getSession().getAttribute(Constants.SHIPPING_OPTIONS);
            if (summary == null) {
                summary = orderFacade.getShippingSummary(quote, store, language);
                request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, options);
            }
            if (options == null) {
                options = quote.getShippingOptions();
                request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
            }
            ReadableShippingSummary readableSummary = new ReadableShippingSummary();
            ReadableShippingSummaryPopulator readableSummaryPopulator = new ReadableShippingSummaryPopulator();
            readableSummaryPopulator.setPricingService(pricingService);
            readableSummaryPopulator.populate(summary, readableSummary, store, language);
            if (!CollectionUtils.isEmpty(options)) {
                // get submitted shipping option
                ShippingOption quoteOption = null;
                ShippingOption selectedOption = order.getSelectedShippingOption();
                // check if selectedOption exist
                for (ShippingOption shipOption : options) {
                    if (!StringUtils.isBlank(shipOption.getOptionId()) && shipOption.getOptionId().equals(selectedOption.getOptionId())) {
                        quoteOption = shipOption;
                    }
                }
                if (quoteOption == null) {
                    quoteOption = options.get(0);
                }
                readableSummary.setSelectedShippingOption(quoteOption);
                readableSummary.setShippingOptions(options);
                summary.setShippingOption(quoteOption.getOptionId());
                summary.setShipping(quoteOption.getOptionPrice());
            }
            order.setShippingSummary(summary);
        }
        /**
         * Calculate order total summary
         */
        OrderTotalSummary totalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
        if (totalSummary == null) {
            totalSummary = orderFacade.calculateOrderTotal(store, order, language);
            super.setSessionAttribute(Constants.ORDER_SUMMARY, totalSummary, request);
        }
        order.setOrderTotalSummary(totalSummary);
        orderFacade.validateOrder(order, bindingResult, new HashMap<String, String>(), store, locale);
        if (bindingResult.hasErrors()) {
            LOGGER.info("found {} validation error while validating in customer registration ", bindingResult.getErrorCount());
            String message = null;
            List<ObjectError> errors = bindingResult.getAllErrors();
            if (!CollectionUtils.isEmpty(errors)) {
                for (ObjectError error : errors) {
                    message = error.getDefaultMessage();
                    break;
                }
            }
            model.addAttribute("errorMessages", message);
            StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
            return template.toString();
        }
        @SuppressWarnings("unused") Order modelOrder = commitOrder(order, request, locale);
    } catch (ServiceException se) {
        LOGGER.error("Error while creating an order ", se);
        String defaultMessage = messages.getMessage("message.error", locale);
        model.addAttribute("errorMessages", defaultMessage);
        if (se.getExceptionType() == ServiceException.EXCEPTION_VALIDATION) {
            if (!StringUtils.isBlank(se.getMessageCode())) {
                String messageLabel = messages.getMessage(se.getMessageCode(), locale, defaultMessage);
                model.addAttribute("errorMessages", messageLabel);
            }
        } else if (se.getExceptionType() == ServiceException.EXCEPTION_PAYMENT_DECLINED) {
            String paymentDeclinedMessage = messages.getMessage("message.payment.declined", locale);
            if (!StringUtils.isBlank(se.getMessageCode())) {
                String messageLabel = messages.getMessage(se.getMessageCode(), locale, paymentDeclinedMessage);
                model.addAttribute("errorMessages", messageLabel);
            } else {
                model.addAttribute("errorMessages", paymentDeclinedMessage);
            }
        }
        StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
        return template.toString();
    } catch (Exception e) {
        LOGGER.error("Error while commiting order", e);
        throw e;
    }
    // redirect to completd
    return "redirect:/shop/order/confirmation.html";
}
Also used : OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ReadableShippingSummaryPopulator(com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator) Language(com.salesmanager.core.model.reference.language.Language) ReadableCustomerDeliveryAddressPopulator(com.salesmanager.shop.populator.customer.ReadableCustomerDeliveryAddressPopulator) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) List(java.util.List) ArrayList(java.util.ArrayList) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ShippingMetaData(com.salesmanager.core.model.shipping.ShippingMetaData) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ObjectError(org.springframework.validation.ObjectError) ServiceException(com.salesmanager.core.business.exception.ServiceException) PaymentMethod(com.salesmanager.core.model.payments.PaymentMethod) Country(com.salesmanager.core.model.reference.country.Country) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Country (com.salesmanager.core.model.reference.country.Country)33 Zone (com.salesmanager.core.model.reference.zone.Zone)21 Language (com.salesmanager.core.model.reference.language.Language)18 ArrayList (java.util.ArrayList)15 ServiceException (com.salesmanager.core.business.exception.ServiceException)14 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)11 Delivery (com.salesmanager.core.model.common.Delivery)10 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)9 BigDecimal (java.math.BigDecimal)8 List (java.util.List)7 ConversionException (com.salesmanager.core.business.exception.ConversionException)6 Billing (com.salesmanager.core.model.common.Billing)6 Customer (com.salesmanager.core.model.customer.Customer)6 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)5 ShippingConfiguration (com.salesmanager.core.model.shipping.ShippingConfiguration)5 ShippingOrigin (com.salesmanager.core.model.shipping.ShippingOrigin)5 IntegrationConfiguration (com.salesmanager.core.model.system.IntegrationConfiguration)5 Date (java.util.Date)5