Search in sources :

Example 1 with ReadableOrderTotal

use of com.salesmanager.shop.model.order.total.ReadableOrderTotal in project shopizer by shopizer-ecommerce.

the class ShoppingOrderController method calculateOrderTotal.

/**
 * Calculates the order total following price variation like changing a shipping option
 * @param order
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/calculateOrderTotal.json" }, method = RequestMethod.POST)
@ResponseBody
public ReadableShopOrder calculateOrderTotal(@ModelAttribute(value = "order") ShopOrder order, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
    Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
    ReadableShopOrder readableOrder = new ReadableShopOrder();
    try {
        // re-generate cart
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        ReadableShopOrderPopulator populator = new ReadableShopOrderPopulator();
        populator.populate(order, readableOrder, store, language);
        ReadableDelivery readableDelivery = super.getSessionAttribute(Constants.KEY_SESSION_ADDRESS, request);
        if (order.getSelectedShippingOption() != null) {
            ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute(Constants.SHIPPING_SUMMARY);
            @SuppressWarnings("unchecked") List<ShippingOption> options = (List<ShippingOption>) request.getSession().getAttribute(Constants.SHIPPING_OPTIONS);
            // for total calculation
            order.setShippingSummary(summary);
            ReadableShippingSummary readableSummary = new ReadableShippingSummary();
            ReadableShippingSummaryPopulator readableSummaryPopulator = new ReadableShippingSummaryPopulator();
            readableSummaryPopulator.setPricingService(pricingService);
            readableSummaryPopulator.populate(summary, readableSummary, store, language);
            // override summary
            readableSummary.setDelivery(readableDelivery);
            if (!CollectionUtils.isEmpty(options)) {
                // get submitted shipping option
                ShippingOption quoteOption = null;
                ShippingOption selectedOption = order.getSelectedShippingOption();
                // check if selectedOption exist
                for (ShippingOption shipOption : options) {
                    StringBuilder moduleName = new StringBuilder();
                    moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                    String carrier = messages.getMessage(moduleName.toString(), locale);
                    String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
                    shipOption.setNote(note);
                    shipOption.setDescription(carrier);
                    if (!StringUtils.isBlank(shipOption.getOptionId()) && shipOption.getOptionId().equals(selectedOption.getOptionId())) {
                        quoteOption = shipOption;
                    }
                    // 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());
                            optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
                            String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                            shipOption.setOptionName(optionName);
                        } catch (Exception e) {
                            // label not found
                            LOGGER.warn("calculateOrderTotal No shipping code found for " + optionCodeBuilder.toString());
                        }
                    }
                }
                if (quoteOption == null) {
                    quoteOption = options.get(0);
                }
                readableSummary.setSelectedShippingOption(quoteOption);
                readableSummary.setShippingOptions(options);
                summary.setShippingOption(quoteOption.getOptionId());
                summary.setShippingOptionCode(quoteOption.getOptionCode());
                summary.setShipping(quoteOption.getOptionPrice());
                // override with new summary
                order.setShippingSummary(summary);
                @SuppressWarnings("unchecked") Map<String, String> informations = (Map<String, String>) request.getSession().getAttribute("SHIPPING_INFORMATIONS");
                readableSummary.setQuoteInformations(informations);
            }
            // TODO readable address format
            readableOrder.setShippingSummary(readableSummary);
            readableOrder.setDelivery(readableDelivery);
        }
        // set list of shopping cart items for core price calculation
        List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(cart.getLineItems());
        order.setShoppingCartItems(items);
        order.setCartCode(shoppingCartCode);
        // order total calculation
        OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
        super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
        ReadableOrderTotalPopulator totalPopulator = new ReadableOrderTotalPopulator();
        totalPopulator.setMessages(messages);
        totalPopulator.setPricingService(pricingService);
        List<ReadableOrderTotal> subtotals = new ArrayList<ReadableOrderTotal>();
        for (OrderTotal total : orderTotalSummary.getTotals()) {
            if (total.getOrderTotalCode() == null || !total.getOrderTotalCode().equals("order.total.total")) {
                ReadableOrderTotal t = new ReadableOrderTotal();
                totalPopulator.populate(total, t, store, language);
                subtotals.add(t);
            } else {
                // grand total
                ReadableOrderTotal ot = new ReadableOrderTotal();
                totalPopulator.populate(total, ot, store, language);
                readableOrder.setGrandTotal(ot.getTotal());
            }
        }
        readableOrder.setSubTotals(subtotals);
    } catch (Exception e) {
        LOGGER.error("Error while getting shipping quotes", e);
        readableOrder.setErrorMessage(messages.getMessage("message.error", locale));
    }
    return readableOrder;
}
Also used : OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ReadableShippingSummaryPopulator(com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator) Language(com.salesmanager.core.model.reference.language.Language) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) List(java.util.List) ArrayList(java.util.ArrayList) ReadableShopOrderPopulator(com.salesmanager.shop.populator.order.ReadableShopOrderPopulator) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) ReadableOrderTotalPopulator(com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with ReadableOrderTotal

use of com.salesmanager.shop.model.order.total.ReadableOrderTotal in project shopizer by shopizer-ecommerce.

the class ReadableOrderSummaryPopulator method populate.

@Override
public ReadableOrderTotalSummary populate(OrderTotalSummary source, ReadableOrderTotalSummary target, MerchantStore store, Language language) throws ConversionException {
    Validate.notNull(pricingService, "PricingService must be set");
    Validate.notNull(messages, "LabelUtils must be set");
    if (target == null) {
        target = new ReadableOrderTotalSummary();
    }
    try {
        if (source.getSubTotal() != null) {
            target.setSubTotal(pricingService.getDisplayAmount(source.getSubTotal(), store));
        }
        if (source.getTaxTotal() != null) {
            target.setTaxTotal(pricingService.getDisplayAmount(source.getTaxTotal(), store));
        }
        if (source.getTotal() != null) {
            target.setTotal(pricingService.getDisplayAmount(source.getTotal(), store));
        }
        if (!CollectionUtils.isEmpty(source.getTotals())) {
            ReadableOrderTotalPopulator orderTotalPopulator = new ReadableOrderTotalPopulator();
            orderTotalPopulator.setMessages(messages);
            orderTotalPopulator.setPricingService(pricingService);
            for (OrderTotal orderTotal : source.getTotals()) {
                ReadableOrderTotal t = new ReadableOrderTotal();
                orderTotalPopulator.populate(orderTotal, t, store, language);
                target.getTotals().add(t);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error during amount formatting " + e.getMessage());
        throw new ConversionException(e);
    }
    return target;
}
Also used : ConversionException(com.salesmanager.core.business.exception.ConversionException) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal) ReadableOrderTotalSummary(com.salesmanager.shop.model.order.ReadableOrderTotalSummary) ConversionException(com.salesmanager.core.business.exception.ConversionException)

Example 3 with ReadableOrderTotal

use of com.salesmanager.shop.model.order.total.ReadableOrderTotal in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method orderConfirmation.

@Override
public ReadableOrderConfirmation orderConfirmation(Order order, Customer customer, MerchantStore store, Language language) {
    Validate.notNull(order, "Order cannot be null");
    Validate.notNull(customer, "Customer cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    ReadableOrderConfirmation orderConfirmation = new ReadableOrderConfirmation();
    ReadableCustomer readableCustomer = readableCustomerMapper.convert(customer, store, language);
    orderConfirmation.setBilling(readableCustomer.getBilling());
    orderConfirmation.setDelivery(readableCustomer.getDelivery());
    ReadableTotal readableTotal = new ReadableTotal();
    Set<OrderTotal> totals = order.getOrderTotal();
    List<ReadableOrderTotal> readableTotals = totals.stream().sorted(Comparator.comparingInt(OrderTotal::getSortOrder)).map(tot -> convertOrderTotal(tot, store, language)).collect(Collectors.toList());
    readableTotal.setTotals(readableTotals);
    Optional<ReadableOrderTotal> grandTotal = readableTotals.stream().filter(tot -> tot.getCode().equals("order.total.total")).findFirst();
    if (grandTotal.isPresent()) {
        readableTotal.setGrandTotal(grandTotal.get().getText());
    }
    orderConfirmation.setTotal(readableTotal);
    List<ReadableOrderProduct> products = order.getOrderProducts().stream().map(pr -> convertOrderProduct(pr, store, language)).collect(Collectors.toList());
    orderConfirmation.setProducts(products);
    if (!StringUtils.isBlank(order.getShippingModuleCode())) {
        StringBuilder optionCodeBuilder = new StringBuilder();
        try {
            optionCodeBuilder.append("module.shipping.").append(order.getShippingModuleCode());
            String shippingName = messages.getMessage(optionCodeBuilder.toString(), new String[] { store.getStorename() }, languageService.toLocale(language, store));
            orderConfirmation.setShipping(shippingName);
        } catch (Exception e) {
            // label not found
            LOGGER.warn("No shipping code found for " + optionCodeBuilder.toString());
        }
    }
    if (order.getPaymentType() != null) {
        orderConfirmation.setPayment(order.getPaymentType().name());
    }
    /**
     * Confirmation may be formatted
     */
    orderConfirmation.setId(order.getId());
    return orderConfirmation;
}
Also used : ReadableOrderTotalMapper(com.salesmanager.shop.mapper.order.ReadableOrderTotalMapper) Order(com.salesmanager.core.model.order.Order) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) ReadableCustomerMapper(com.salesmanager.shop.mapper.customer.ReadableCustomerMapper) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) LanguageService(com.salesmanager.core.business.services.reference.language.LanguageService) Language(com.salesmanager.core.model.reference.language.Language) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) LabelUtils(com.salesmanager.shop.utils.LabelUtils) Service(org.springframework.stereotype.Service) Logger(org.slf4j.Logger) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) Customer(com.salesmanager.core.model.customer.Customer) ReadableOrderConfirmation(com.salesmanager.shop.model.order.v1.ReadableOrderConfirmation) Set(java.util.Set) Collectors(java.util.stream.Collectors) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) List(java.util.List) Validate(org.apache.commons.lang3.Validate) OrderFacade(com.salesmanager.shop.store.controller.order.facade.v1.OrderFacade) Optional(java.util.Optional) Comparator(java.util.Comparator) ReadableOrderProductMapper(com.salesmanager.shop.mapper.order.ReadableOrderProductMapper) ReadableTotal(com.salesmanager.shop.model.order.total.ReadableTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal) ReadableTotal(com.salesmanager.shop.model.order.total.ReadableTotal) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) ReadableOrderConfirmation(com.salesmanager.shop.model.order.v1.ReadableOrderConfirmation) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal)

Example 4 with ReadableOrderTotal

use of com.salesmanager.shop.model.order.total.ReadableOrderTotal in project shopizer by shopizer-ecommerce.

the class ReadableShoppingCartMapper method merge.

@Override
public ReadableShoppingCart merge(ShoppingCart source, ReadableShoppingCart destination, MerchantStore store, Language language) {
    Validate.notNull(source, "ShoppingCart cannot be null");
    Validate.notNull(destination, "ReadableShoppingCart cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    Validate.notNull(language, "Language cannot be null");
    destination.setCode(source.getShoppingCartCode());
    int cartQuantity = 0;
    destination.setCustomer(source.getCustomerId());
    try {
        if (!StringUtils.isBlank(source.getPromoCode())) {
            // promo valid 1 day
            Date promoDateAdded = source.getPromoAdded();
            if (promoDateAdded == null) {
                promoDateAdded = new Date();
            }
            Instant instant = promoDateAdded.toInstant();
            ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
            LocalDate date = zdt.toLocalDate();
            // date added < date + 1 day
            LocalDate tomorrow = LocalDate.now().plusDays(1);
            if (date.isBefore(tomorrow)) {
                destination.setPromoCode(source.getPromoCode());
            }
        }
        Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = source.getLineItems();
        if (items != null) {
            for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
                ReadableShoppingCartItem shoppingCartItem = new ReadableShoppingCartItem();
                readableMinimalProductMapper.merge(item.getProduct(), shoppingCartItem, store, language);
                // ReadableProductPopulator readableProductPopulator = new
                // ReadableProductPopulator();
                // readableProductPopulator.setPricingService(pricingService);
                // readableProductPopulator.setimageUtils(imageUtils);
                // readableProductPopulator.populate(item.getProduct(), shoppingCartItem, store,
                // language);
                shoppingCartItem.setPrice(item.getItemPrice());
                shoppingCartItem.setFinalPrice(pricingService.getDisplayAmount(item.getItemPrice(), store));
                shoppingCartItem.setQuantity(item.getQuantity());
                cartQuantity = cartQuantity + item.getQuantity();
                BigDecimal subTotal = pricingService.calculatePriceQuantity(item.getItemPrice(), item.getQuantity());
                // calculate sub total (price * quantity)
                shoppingCartItem.setSubTotal(subTotal);
                shoppingCartItem.setDisplaySubTotal(pricingService.getDisplayAmount(subTotal, store));
                Set<com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem> attributes = item.getAttributes();
                if (attributes != null) {
                    for (com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attribute : attributes) {
                        ProductAttribute productAttribute = productAttributeService.getById(attribute.getProductAttributeId());
                        if (productAttribute == null) {
                            LOG.warn("Product attribute with ID " + attribute.getId() + " not found, skipping cart attribute " + attribute.getId());
                            continue;
                        }
                        ReadableShoppingCartAttribute cartAttribute = new ReadableShoppingCartAttribute();
                        cartAttribute.setId(attribute.getId());
                        ProductOption option = productAttribute.getProductOption();
                        ProductOptionValue optionValue = productAttribute.getProductOptionValue();
                        List<ProductOptionDescription> optionDescriptions = option.getDescriptionsSettoList();
                        List<ProductOptionValueDescription> optionValueDescriptions = optionValue.getDescriptionsSettoList();
                        String optName = null;
                        String optValue = null;
                        if (!CollectionUtils.isEmpty(optionDescriptions) && !CollectionUtils.isEmpty(optionValueDescriptions)) {
                            optName = optionDescriptions.get(0).getName();
                            optValue = optionValueDescriptions.get(0).getName();
                            for (ProductOptionDescription optionDescription : optionDescriptions) {
                                if (optionDescription.getLanguage() != null && optionDescription.getLanguage().getId().intValue() == language.getId().intValue()) {
                                    optName = optionDescription.getName();
                                    break;
                                }
                            }
                            for (ProductOptionValueDescription optionValueDescription : optionValueDescriptions) {
                                if (optionValueDescription.getLanguage() != null && optionValueDescription.getLanguage().getId().intValue() == language.getId().intValue()) {
                                    optValue = optionValueDescription.getName();
                                    break;
                                }
                            }
                        }
                        if (optName != null) {
                            ReadableShoppingCartAttributeOption attributeOption = new ReadableShoppingCartAttributeOption();
                            attributeOption.setCode(option.getCode());
                            attributeOption.setId(option.getId());
                            attributeOption.setName(optName);
                            cartAttribute.setOption(attributeOption);
                        }
                        if (optValue != null) {
                            ReadableShoppingCartAttributeOptionValue attributeOptionValue = new ReadableShoppingCartAttributeOptionValue();
                            attributeOptionValue.setCode(optionValue.getCode());
                            attributeOptionValue.setId(optionValue.getId());
                            attributeOptionValue.setName(optValue);
                            cartAttribute.setOptionValue(attributeOptionValue);
                        }
                        shoppingCartItem.getCartItemattributes().add(cartAttribute);
                    }
                }
                destination.getProducts().add(shoppingCartItem);
            }
        }
        // Calculate totals using shoppingCartService
        // OrderSummary contains ShoppingCart items
        OrderSummary summary = new OrderSummary();
        List<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> productsList = new ArrayList<com.salesmanager.core.model.shoppingcart.ShoppingCartItem>();
        productsList.addAll(source.getLineItems());
        summary.setProducts(productsList);
        // OrdetTotalSummary contains all calculations
        OrderTotalSummary orderSummary = shoppingCartCalculationService.calculate(source, store, language);
        if (CollectionUtils.isNotEmpty(orderSummary.getTotals())) {
            if (orderSummary.getTotals().stream().filter(t -> Constants.OT_DISCOUNT_TITLE.equals(t.getOrderTotalCode())).count() == 0) {
                // no promo coupon applied
                destination.setPromoCode(null);
            }
            List<ReadableOrderTotal> totals = new ArrayList<ReadableOrderTotal>();
            for (com.salesmanager.core.model.order.OrderTotal t : orderSummary.getTotals()) {
                ReadableOrderTotal total = new ReadableOrderTotal();
                total.setCode(t.getOrderTotalCode());
                total.setValue(t.getValue());
                total.setText(t.getText());
                totals.add(total);
            }
            destination.setTotals(totals);
        }
        destination.setSubtotal(orderSummary.getSubTotal());
        destination.setDisplaySubTotal(pricingService.getDisplayAmount(orderSummary.getSubTotal(), store));
        destination.setTotal(orderSummary.getTotal());
        destination.setDisplayTotal(pricingService.getDisplayAmount(orderSummary.getTotal(), store));
        destination.setQuantity(cartQuantity);
        destination.setId(source.getId());
        if (source.getOrderId() != null) {
            destination.setOrder(source.getOrderId());
        }
    } catch (Exception e) {
        throw new ConversionRuntimeException("An error occured while converting ReadableShoppingCart", e);
    }
    return destination;
}
Also used : ReadableShoppingCartAttribute(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartAttribute) OrderSummary(com.salesmanager.core.model.order.OrderSummary) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) LocalDate(java.time.LocalDate) ProductOptionDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription) ReadableShoppingCartItem(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartItem) ProductOptionValue(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue) ZonedDateTime(java.time.ZonedDateTime) ReadableShoppingCartAttributeOption(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartAttributeOption) ConversionRuntimeException(com.salesmanager.shop.store.api.exception.ConversionRuntimeException) ProductOption(com.salesmanager.core.model.catalog.product.attribute.ProductOption) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) Instant(java.time.Instant) Date(java.util.Date) LocalDate(java.time.LocalDate) BigDecimal(java.math.BigDecimal) ConversionRuntimeException(com.salesmanager.shop.store.api.exception.ConversionRuntimeException) ReadableShoppingCartAttributeOptionValue(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartAttributeOptionValue) ReadableShoppingCartItem(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartItem) ProductOptionValueDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription)

Example 5 with ReadableOrderTotal

use of com.salesmanager.shop.model.order.total.ReadableOrderTotal in project shopizer by shopizer-ecommerce.

the class ShoppingOrderController method calculateShipping.

/**
 * Recalculates shipping and tax following a change in country or province
 * @param order
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping(value = { "/shippingQuotes.json" }, method = RequestMethod.POST)
@ResponseBody
public ReadableShopOrder calculateShipping(@ModelAttribute(value = "order") ShopOrder order, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
    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.info("Calculate order -> shoppingCartCode[ " + shoppingCartCode + "] -> " + jsonInString);
				} catch(Exception de) {
					LOGGER.error(de.getMessage());
				}
			}
		}*/
    Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
    ReadableShopOrder readableOrder = new ReadableShopOrder();
    try {
        // re-generate cart
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> cartItems = cart.getLineItems();
        ReadableShopOrderPopulator populator = new ReadableShopOrderPopulator();
        populator.populate(order, readableOrder, store, language);
        /**
         *	        for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : cartItems) {
         *
         *	        	Long id = item.getProduct().getId();
         *	        	Product p = productService.getById(id);
         *				if (p.isProductShipeable()) {
         *					requiresShipping = true;
         *				}
         *	        }
         */
        /**
         * shipping *
         */
        ShippingQuote quote = null;
        quote = orderFacade.getShippingQuote(order.getCustomer(), cart, order, store, language);
        if (quote != null) {
            String shippingReturnCode = quote.getShippingReturnCode();
            if (CollectionUtils.isNotEmpty(quote.getShippingOptions()) || ShippingQuote.NO_POSTAL_CODE.equals(shippingReturnCode)) {
                ShippingSummary summary = orderFacade.getShippingSummary(quote, store, language);
                // for total calculation
                order.setShippingSummary(summary);
                ReadableShippingSummary readableSummary = new ReadableShippingSummary();
                ReadableShippingSummaryPopulator readableSummaryPopulator = new ReadableShippingSummaryPopulator();
                readableSummaryPopulator.setPricingService(pricingService);
                readableSummaryPopulator.populate(summary, readableSummary, store, language);
                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);
                    readableOrder.setDelivery(deliveryAddress);
                    super.setSessionAttribute(Constants.KEY_SESSION_ADDRESS, deliveryAddress, request);
                }
                // save quotes in HttpSession
                List<ShippingOption> options = quote.getShippingOptions();
                if (!CollectionUtils.isEmpty(options)) {
                    for (ShippingOption shipOption : options) {
                        StringBuilder moduleName = new StringBuilder();
                        moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                        String carrier = messages.getMessage(moduleName.toString(), new String[] { store.getStorename() }, locale);
                        String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
                        shipOption.setDescription(carrier);
                        shipOption.setNote(note);
                        // option name
                        if (!StringUtils.isBlank(shipOption.getOptionCode())) {
                            // try to get the translate
                            StringBuilder optionCodeBuilder = new StringBuilder();
                            try {
                                optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
                                String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                                shipOption.setOptionName(optionName);
                            } catch (Exception e) {
                                // label not found
                                LOGGER.warn("calculateShipping No shipping code found for " + optionCodeBuilder.toString());
                            }
                        }
                    }
                }
                readableSummary.setSelectedShippingOption(quote.getSelectedShippingOption());
                readableSummary.setShippingOptions(options);
                // TODO add readable address
                readableOrder.setShippingSummary(readableSummary);
                request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, summary);
                request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
                request.getSession().setAttribute("SHIPPING_INFORMATIONS", readableSummary.getQuoteInformations());
                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(readableOrder);
                            LOGGER.debug("Readable order -> shoppingCartCode[ " + shoppingCartCode + "] -> " + jsonInString);
                            System.out.println("Readable order -> shoppingCartCode[ " + shoppingCartCode + "] -> " + jsonInString);
                        } catch (Exception de) {
                            LOGGER.error(de.getMessage());
                        }
                    }
                }
            }
            if (quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED)) {
                LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
                readableOrder.setErrorMessage(messages.getMessage("message.noshipping", locale));
            }
            if (quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY)) {
                if (CollectionUtils.isEmpty(quote.getShippingOptions())) {
                    // only if there are no other options
                    LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
                    readableOrder.setErrorMessage(messages.getMessage("message.noshipping", locale));
                }
            }
            if (!StringUtils.isBlank(quote.getQuoteError())) {
                LOGGER.error("Shipping quote error " + quote.getQuoteError());
                readableOrder.setErrorMessage(messages.getMessage("message.noshippingerror", locale));
            }
        }
        // set list of shopping cart items for core price calculation
        List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(cart.getLineItems());
        order.setShoppingCartItems(items);
        order.setCartCode(cart.getShoppingCartCode());
        OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
        super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
        ReadableOrderTotalPopulator totalPopulator = new ReadableOrderTotalPopulator();
        totalPopulator.setMessages(messages);
        totalPopulator.setPricingService(pricingService);
        List<ReadableOrderTotal> subtotals = new ArrayList<ReadableOrderTotal>();
        for (OrderTotal total : orderTotalSummary.getTotals()) {
            if (!total.getOrderTotalCode().equals("order.total.total")) {
                ReadableOrderTotal t = new ReadableOrderTotal();
                totalPopulator.populate(total, t, store, language);
                subtotals.add(t);
            } else {
                // grand total
                ReadableOrderTotal ot = new ReadableOrderTotal();
                totalPopulator.populate(total, ot, store, language);
                readableOrder.setGrandTotal(ot.getTotal());
            }
        }
        readableOrder.setSubTotals(subtotals);
    } catch (Exception e) {
        LOGGER.error("Error while getting shipping quotes", e);
        readableOrder.setErrorMessage(messages.getMessage("message.error", locale));
    }
    return readableOrder;
}
Also used : OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) 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) ReadableShopOrderPopulator(com.salesmanager.shop.populator.order.ReadableShopOrderPopulator) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) ReadableOrderTotalPopulator(com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

ReadableOrderTotal (com.salesmanager.shop.model.order.total.ReadableOrderTotal)5 OrderTotal (com.salesmanager.core.model.order.OrderTotal)4 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)3 OrderTotalSummary (com.salesmanager.core.model.order.OrderTotalSummary)3 Language (com.salesmanager.core.model.reference.language.Language)3 ArrayList (java.util.ArrayList)3 ServiceException (com.salesmanager.core.business.exception.ServiceException)2 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)2 ShippingSummary (com.salesmanager.core.model.shipping.ShippingSummary)2 ShoppingCartItem (com.salesmanager.core.model.shoppingcart.ShoppingCartItem)2 ReadableDelivery (com.salesmanager.shop.model.customer.ReadableDelivery)2 ReadableShopOrder (com.salesmanager.shop.model.order.ReadableShopOrder)2 ReadableShippingSummary (com.salesmanager.shop.model.order.shipping.ReadableShippingSummary)2 ReadableOrderTotalPopulator (com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator)2 ReadableShippingSummaryPopulator (com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator)2 ReadableShopOrderPopulator (com.salesmanager.shop.populator.order.ReadableShopOrderPopulator)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ConversionException (com.salesmanager.core.business.exception.ConversionException)1 LanguageService (com.salesmanager.core.business.services.reference.language.LanguageService)1 ProductAttribute (com.salesmanager.core.model.catalog.product.attribute.ProductAttribute)1