Search in sources :

Example 11 with ShippingSummary

use of com.salesmanager.core.model.shipping.ShippingSummary in project shopizer by shopizer-ecommerce.

the class TaxServiceImpl method calculateTax.

@Override
public List<TaxItem> calculateTax(OrderSummary orderSummary, Customer customer, MerchantStore store, Language language) throws ServiceException {
    if (customer == null) {
        return null;
    }
    List<ShoppingCartItem> items = orderSummary.getProducts();
    List<TaxItem> taxLines = new ArrayList<TaxItem>();
    if (items == null) {
        return taxLines;
    }
    // determine tax calculation basis
    TaxConfiguration taxConfiguration = this.getTaxConfiguration(store);
    if (taxConfiguration == null) {
        taxConfiguration = new TaxConfiguration();
        taxConfiguration.setTaxBasisCalculation(TaxBasisCalculation.SHIPPINGADDRESS);
    }
    Country country = customer.getBilling().getCountry();
    Zone zone = customer.getBilling().getZone();
    String stateProvince = customer.getBilling().getState();
    TaxBasisCalculation taxBasisCalculation = taxConfiguration.getTaxBasisCalculation();
    if (taxBasisCalculation.name().equals(TaxBasisCalculation.SHIPPINGADDRESS)) {
        Delivery shipping = customer.getDelivery();
        if (shipping != null) {
            country = shipping.getCountry();
            zone = shipping.getZone();
            stateProvince = shipping.getState();
        }
    } else if (taxBasisCalculation.name().equals(TaxBasisCalculation.BILLINGADDRESS)) {
        Billing billing = customer.getBilling();
        if (billing != null) {
            country = billing.getCountry();
            zone = billing.getZone();
            stateProvince = billing.getState();
        }
    } else if (taxBasisCalculation.name().equals(TaxBasisCalculation.STOREADDRESS)) {
        country = store.getCountry();
        zone = store.getZone();
        stateProvince = store.getStorestateprovince();
    }
    // do not collect tax on other provinces of same country
    if (!taxConfiguration.isCollectTaxIfDifferentProvinceOfStoreCountry()) {
        if ((zone != null && store.getZone() != null) && (zone.getId().longValue() != store.getZone().getId().longValue())) {
            return null;
        }
        if (!StringUtils.isBlank(stateProvince)) {
            if (store.getZone() != null) {
                if (!store.getZone().getName().equals(stateProvince)) {
                    return null;
                }
            } else if (!StringUtils.isBlank(store.getStorestateprovince())) {
                if (!store.getStorestateprovince().equals(stateProvince)) {
                    return null;
                }
            }
        }
    }
    // collect tax in different countries
    if (taxConfiguration.isCollectTaxIfDifferentCountryOfStoreCountry()) {
        // use store country
        country = store.getCountry();
        zone = store.getZone();
        stateProvince = store.getStorestateprovince();
    }
    if (zone == null && StringUtils.isBlank(stateProvince)) {
        return null;
    }
    Map<Long, TaxClass> taxClasses = new HashMap<Long, TaxClass>();
    // put items in a map by tax class id
    Map<Long, BigDecimal> taxClassAmountMap = new HashMap<Long, BigDecimal>();
    for (ShoppingCartItem item : items) {
        BigDecimal itemPrice = item.getItemPrice();
        TaxClass taxClass = item.getProduct().getTaxClass();
        int quantity = item.getQuantity();
        itemPrice = itemPrice.multiply(new BigDecimal(quantity));
        if (taxClass == null) {
            taxClass = taxClassService.getByCode(DEFAULT_TAX_CLASS);
        }
        BigDecimal subTotal = taxClassAmountMap.get(taxClass.getId());
        if (subTotal == null) {
            subTotal = new BigDecimal(0);
            subTotal.setScale(2, RoundingMode.HALF_UP);
        }
        subTotal = subTotal.add(itemPrice);
        taxClassAmountMap.put(taxClass.getId(), subTotal);
        taxClasses.put(taxClass.getId(), taxClass);
    }
    // tax on shipping ?
    // ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store);
    /**
     * always calculate tax on shipping *
     */
    // if(shippingConfiguration!=null) {
    // if(shippingConfiguration.isTaxOnShipping()){
    // use default tax class for shipping
    TaxClass defaultTaxClass = taxClassService.getByCode(TaxClass.DEFAULT_TAX_CLASS);
    // taxClasses.put(defaultTaxClass.getId(), defaultTaxClass);
    BigDecimal amnt = taxClassAmountMap.get(defaultTaxClass.getId());
    if (amnt == null) {
        amnt = new BigDecimal(0);
        amnt.setScale(2, RoundingMode.HALF_UP);
    }
    ShippingSummary shippingSummary = orderSummary.getShippingSummary();
    if (shippingSummary != null && shippingSummary.getShipping() != null && shippingSummary.getShipping().doubleValue() > 0) {
        amnt = amnt.add(shippingSummary.getShipping());
        if (shippingSummary.getHandling() != null && shippingSummary.getHandling().doubleValue() > 0) {
            amnt = amnt.add(shippingSummary.getHandling());
        }
    }
    taxClassAmountMap.put(defaultTaxClass.getId(), amnt);
    // }
    // }
    List<TaxItem> taxItems = new ArrayList<TaxItem>();
    // iterate through the tax class and get appropriate rates
    for (Long taxClassId : taxClassAmountMap.keySet()) {
        // get taxRate by tax class
        List<TaxRate> taxRates = null;
        if (!StringUtils.isBlank(stateProvince) && zone == null) {
            taxRates = taxRateService.listByCountryStateProvinceAndTaxClass(country, stateProvince, taxClasses.get(taxClassId), store, language);
        } else {
            taxRates = taxRateService.listByCountryZoneAndTaxClass(country, zone, taxClasses.get(taxClassId), store, language);
        }
        if (taxRates == null || taxRates.size() == 0) {
            continue;
        }
        BigDecimal taxedItemValue = null;
        BigDecimal totalTaxedItemValue = new BigDecimal(0);
        totalTaxedItemValue.setScale(2, RoundingMode.HALF_UP);
        BigDecimal beforeTaxeAmount = taxClassAmountMap.get(taxClassId);
        for (TaxRate taxRate : taxRates) {
            // 5% ... 8% ...
            double taxRateDouble = taxRate.getTaxRate().doubleValue();
            if (taxRate.isPiggyback()) {
                // (compound)
                if (totalTaxedItemValue.doubleValue() > 0) {
                    beforeTaxeAmount = totalTaxedItemValue;
                }
            }
            // else just use nominal taxing (combine)
            double value = (beforeTaxeAmount.doubleValue() * taxRateDouble) / 100;
            double roundedValue = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue();
            taxedItemValue = new BigDecimal(roundedValue).setScale(2, RoundingMode.HALF_UP);
            totalTaxedItemValue = beforeTaxeAmount.add(taxedItemValue);
            TaxItem taxItem = new TaxItem();
            taxItem.setItemPrice(taxedItemValue);
            taxItem.setLabel(taxRate.getDescriptions().get(0).getName());
            taxItem.setTaxRate(taxRate);
            taxItems.add(taxItem);
        }
    }
    Map<String, TaxItem> taxItemsMap = new TreeMap<String, TaxItem>();
    // consolidate tax rates of same code
    for (TaxItem taxItem : taxItems) {
        TaxRate taxRate = taxItem.getTaxRate();
        if (!taxItemsMap.containsKey(taxRate.getCode())) {
            taxItemsMap.put(taxRate.getCode(), taxItem);
        }
        TaxItem item = taxItemsMap.get(taxRate.getCode());
        BigDecimal amount = item.getItemPrice();
        amount = amount.add(taxItem.getItemPrice());
    }
    if (taxItemsMap.size() == 0) {
        return null;
    }
    @SuppressWarnings("rawtypes") Collection<TaxItem> values = taxItemsMap.values();
    @SuppressWarnings("unchecked") List<TaxItem> list = new ArrayList<TaxItem>(values);
    return list;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) TaxRate(com.salesmanager.core.model.tax.taxrate.TaxRate) TaxConfiguration(com.salesmanager.core.model.tax.TaxConfiguration) Zone(com.salesmanager.core.model.reference.zone.Zone) TaxClass(com.salesmanager.core.model.tax.taxclass.TaxClass) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) TaxItem(com.salesmanager.core.model.tax.TaxItem) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) TaxBasisCalculation(com.salesmanager.core.model.tax.TaxBasisCalculation) Delivery(com.salesmanager.core.model.common.Delivery)

Example 12 with ShippingSummary

use of com.salesmanager.core.model.shipping.ShippingSummary in project shopizer by shopizer-ecommerce.

the class OrderTotalApi method payment.

/**
 * This service calculates order total for a given shopping cart This method takes in
 * consideration any applicable sales tax An optional request parameter accepts a quote id that
 * was received using shipping api
 *
 * @param quote
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/auth/cart/{id}/total" }, method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableOrderTotalSummary payment(@PathVariable final Long id, @RequestParam(value = "quote", required = false) Long quote, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) {
    try {
        Principal principal = request.getUserPrincipal();
        String userName = principal.getName();
        Customer customer = customerService.getByNick(userName);
        if (customer == null) {
            response.sendError(503, "Error while getting user details to calculate shipping quote");
        }
        ShoppingCart shoppingCart = shoppingCartFacade.getShoppingCartModel(id, merchantStore);
        if (shoppingCart == null) {
            response.sendError(404, "Cart id " + id + " does not exist");
            return null;
        }
        if (shoppingCart.getCustomerId() == null) {
            response.sendError(404, "Cart id " + id + " does not exist for exist for user " + userName);
            return null;
        }
        if (shoppingCart.getCustomerId().longValue() != customer.getId().longValue()) {
            response.sendError(404, "Cart id " + id + " does not exist for exist for user " + userName);
            return null;
        }
        ShippingSummary shippingSummary = null;
        // get shipping quote if asked for
        if (quote != null) {
            shippingSummary = shippingQuoteService.getShippingSummary(quote, merchantStore);
        }
        OrderTotalSummary orderTotalSummary = null;
        OrderSummary orderSummary = new OrderSummary();
        orderSummary.setShippingSummary(shippingSummary);
        List<ShoppingCartItem> itemsSet = new ArrayList<ShoppingCartItem>(shoppingCart.getLineItems());
        orderSummary.setProducts(itemsSet);
        orderTotalSummary = orderService.caculateOrderTotal(orderSummary, customer, merchantStore, language);
        ReadableOrderTotalSummary returnSummary = new ReadableOrderTotalSummary();
        ReadableOrderSummaryPopulator populator = new ReadableOrderSummaryPopulator();
        populator.setMessages(messages);
        populator.setPricingService(pricingService);
        populator.populate(orderTotalSummary, returnSummary, merchantStore, language);
        return returnSummary;
    } catch (Exception e) {
        LOGGER.error("Error while calculating order summary", e);
        try {
            response.sendError(503, "Error while calculating order summary " + e.getMessage());
        } catch (Exception ignore) {
        }
        return null;
    }
}
Also used : ReadableOrderSummaryPopulator(com.salesmanager.shop.populator.order.ReadableOrderSummaryPopulator) Customer(com.salesmanager.core.model.customer.Customer) ReadableOrderTotalSummary(com.salesmanager.shop.model.order.ReadableOrderTotalSummary) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) OrderSummary(com.salesmanager.core.model.order.OrderSummary) ArrayList(java.util.ArrayList) ReadableOrderTotalSummary(com.salesmanager.shop.model.order.ReadableOrderTotalSummary) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) Principal(java.security.Principal) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 13 with ShippingSummary

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

Example 14 with ShippingSummary

use of com.salesmanager.core.model.shipping.ShippingSummary 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

ShippingSummary (com.salesmanager.core.model.shipping.ShippingSummary)14 ShoppingCartItem (com.salesmanager.core.model.shoppingcart.ShoppingCartItem)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 OrderTotalSummary (com.salesmanager.core.model.order.OrderTotalSummary)8 ArrayList (java.util.ArrayList)8 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)7 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)6 ReadableShippingSummary (com.salesmanager.shop.model.order.shipping.ReadableShippingSummary)6 ServiceException (com.salesmanager.core.business.exception.ServiceException)5 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)5 Language (com.salesmanager.core.model.reference.language.Language)5 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)5 ShoppingCart (com.salesmanager.core.model.shoppingcart.ShoppingCart)5 ReadableShippingSummaryPopulator (com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator)5 Customer (com.salesmanager.core.model.customer.Customer)4 Country (com.salesmanager.core.model.reference.country.Country)4 ReadableDelivery (com.salesmanager.shop.model.customer.ReadableDelivery)4 ReadableShopOrder (com.salesmanager.shop.model.order.ReadableShopOrder)4 OrderSummary (com.salesmanager.core.model.order.OrderSummary)3 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)3