Search in sources :

Example 1 with ReadableDelivery

use of com.salesmanager.shop.model.customer.ReadableDelivery in project shopizer by shopizer-ecommerce.

the class ShoppingOrderController method displayCheckout.

@SuppressWarnings("unused")
@RequestMapping("/checkout.html")
public String displayCheckout(@CookieValue("cart") String cookie, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
    model.addAttribute("googleMapsKey", googleMapsKey);
    /**
     * Shopping cart
     *
     * ShoppingCart should be in the HttpSession
     * Otherwise the cart id is in the cookie
     * Otherwise the customer is in the session and a cart exist in the DB
     * Else -> Nothing to display
     */
    // check if an existing order exist
    ShopOrder order = null;
    order = super.getSessionAttribute(Constants.ORDER, request);
    // Get the cart from the DB
    String shoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
    com.salesmanager.core.model.shoppingcart.ShoppingCart cart = null;
    if (StringUtils.isBlank(shoppingCartCode)) {
        if (cookie == null) {
            // session expired and cookie null, nothing to do
            return "redirect:/shop/cart/shoppingCart.html";
        }
        String[] merchantCookie = cookie.split("_");
        String merchantStoreCode = merchantCookie[0];
        if (!merchantStoreCode.equals(store.getCode())) {
            return "redirect:/shop/cart/shoppingCart.html";
        }
        shoppingCartCode = merchantCookie[1];
    }
    cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
    if (cart == null && customer != null) {
        cart = shoppingCartFacade.getShoppingCartModel(customer, store);
    }
    boolean allAvailables = true;
    boolean requiresShipping = false;
    boolean freeShoppingCart = true;
    // Filter items, delete unavailable
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> availables = new HashSet<ShoppingCartItem>();
    if (cart == null) {
        return "redirect:/shop/cart/shoppingCart.html";
    }
    // Take out items no more available
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cart.getLineItems();
    for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
        Long id = item.getProduct().getId();
        Product p = productService.getById(id);
        if (p.isAvailable()) {
            availables.add(item);
        } else {
            allAvailables = false;
        }
        FinalPrice finalPrice = pricingService.calculateProductPrice(p);
        if (finalPrice.getFinalPrice().longValue() > 0) {
            freeShoppingCart = false;
        }
        if (p.isProductShipeable()) {
            requiresShipping = true;
        }
    }
    cart.setLineItems(availables);
    if (!allAvailables) {
        shoppingCartFacade.saveOrUpdateShoppingCart(cart);
    }
    super.setSessionAttribute(Constants.SHOPPING_CART, cart.getShoppingCartCode(), request);
    if (shoppingCartCode == null && cart == null) {
        // error
        return "redirect:/shop/cart/shoppingCart.html";
    }
    if (customer != null) {
        if (cart.getCustomerId() != customer.getId().longValue()) {
            return "redirect:/shop/shoppingCart.html";
        }
    } else {
        customer = orderFacade.initEmptyCustomer(store);
        AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
        if (anonymousCustomer != null && anonymousCustomer.getBilling() != null) {
            Billing billing = customer.getBilling();
            billing.setCity(anonymousCustomer.getBilling().getCity());
            Map<String, Country> countriesMap = countryService.getCountriesMap(language);
            Country anonymousCountry = countriesMap.get(anonymousCustomer.getBilling().getCountry());
            if (anonymousCountry != null) {
                billing.setCountry(anonymousCountry);
            }
            Map<String, Zone> zonesMap = zoneService.getZones(language);
            Zone anonymousZone = zonesMap.get(anonymousCustomer.getBilling().getZone());
            if (anonymousZone != null) {
                billing.setZone(anonymousZone);
            }
            if (anonymousCustomer.getBilling().getPostalCode() != null) {
                billing.setPostalCode(anonymousCustomer.getBilling().getPostalCode());
            }
            customer.setBilling(billing);
        }
    }
    if (CollectionUtils.isEmpty(items)) {
        return "redirect:/shop/shoppingCart.html";
    }
    if (order == null) {
        // TODO
        order = orderFacade.initializeOrder(store, customer, cart, language);
    }
    /**
     * hook for displaying or not delivery address configuration
     */
    ShippingMetaData shippingMetaData = shippingService.getShippingMetaData(store);
    model.addAttribute("shippingMetaData", shippingMetaData);
    /**
     * shipping *
     */
    ShippingQuote quote = null;
    if (requiresShipping) {
        // System.out.println("** Berfore default shipping quote **");
        // Get all applicable shipping quotes
        quote = orderFacade.getShippingQuote(customer, cart, order, store, language);
        model.addAttribute("shippingQuote", quote);
    }
    if (quote != null) {
        String shippingReturnCode = quote.getShippingReturnCode();
        if (StringUtils.isBlank(shippingReturnCode) || shippingReturnCode.equals(ShippingQuote.NO_POSTAL_CODE)) {
            if (order.getShippingSummary() == null) {
                ShippingSummary summary = orderFacade.getShippingSummary(quote, store, language);
                order.setShippingSummary(summary);
                // TODO DTO
                request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, summary);
            }
            if (order.getSelectedShippingOption() == null) {
                order.setSelectedShippingOption(quote.getSelectedShippingOption());
            }
            // save quotes in HttpSession
            List<ShippingOption> options = quote.getShippingOptions();
            // TODO DTO
            request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
            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(), 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("displayCheckout 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);
            super.setSessionAttribute(Constants.KEY_SESSION_ADDRESS, deliveryAddress, request);
        }
        // get shipping countries
        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);
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", messages.getMessage(quote.getShippingReturnCode(), locale, quote.getShippingReturnCode()));
    }
    if (quote != null && !StringUtils.isBlank(quote.getQuoteError())) {
        LOGGER.error("Shipping quote error " + quote.getQuoteError());
        model.addAttribute("errorMessages", quote.getQuoteError());
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", quote.getShippingReturnCode());
    }
    /**
     * end shipping *
     */
    // 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", messages.getMessage("payment.not.configured", locale, "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);
        }
        order.setDefaultPaymentMethodCode(defaultPaymentSelected.getPaymentMethodCode());
    }
    // readable shopping cart items for order summary box
    ShoppingCartData shoppingCart = shoppingCartFacade.getShoppingCartData(cart, language);
    model.addAttribute("cart", shoppingCart);
    order.setCartCode(shoppingCart.getCode());
    // order total
    OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
    order.setOrderTotalSummary(orderTotalSummary);
    // if order summary has to be re-used
    super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
    // display hacks
    if (!StringUtils.isBlank(googleMapsKey)) {
        model.addAttribute("fieldDisabled", "true");
        model.addAttribute("cssClass", "");
    } else {
        model.addAttribute("fieldDisabled", "false");
        model.addAttribute("cssClass", "required");
    }
    model.addAttribute("order", order);
    model.addAttribute("paymentMethods", paymentMethods);
    /**
     * template *
     */
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
    return template.toString();
}
Also used : AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) 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) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) HashSet(java.util.HashSet) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) Zone(com.salesmanager.core.model.reference.zone.Zone) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ShippingMetaData(com.salesmanager.core.model.shipping.ShippingMetaData) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) PaymentMethod(com.salesmanager.core.model.payments.PaymentMethod) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ReadableDelivery

use of com.salesmanager.shop.model.customer.ReadableDelivery 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 3 with ReadableDelivery

use of com.salesmanager.shop.model.customer.ReadableDelivery in project shopizer by shopizer-ecommerce.

the class ReadableShippingSummaryPopulator method populate.

@Override
public ReadableShippingSummary populate(ShippingSummary source, ReadableShippingSummary target, MerchantStore store, Language language) throws ConversionException {
    Validate.notNull(pricingService, "PricingService must be set");
    Validate.notNull(source, "ShippingSummary cannot be null");
    try {
        target.setShippingQuote(source.isShippingQuote());
        target.setFreeShipping(source.isFreeShipping());
        target.setHandling(source.getHandling());
        target.setShipping(source.getShipping());
        target.setShippingModule(source.getShippingModule());
        target.setShippingOption(source.getShippingOption());
        target.setTaxOnShipping(source.isTaxOnShipping());
        target.setHandlingText(pricingService.getDisplayAmount(source.getHandling(), store));
        target.setShippingText(pricingService.getDisplayAmount(source.getShipping(), store));
        if (source.getDeliveryAddress() != null) {
            ReadableDelivery deliveryAddress = new ReadableDelivery();
            deliveryAddress.setAddress(source.getDeliveryAddress().getAddress());
            deliveryAddress.setPostalCode(source.getDeliveryAddress().getPostalCode());
            deliveryAddress.setCity(source.getDeliveryAddress().getCity());
            if (source.getDeliveryAddress().getZone() != null) {
                deliveryAddress.setZone(source.getDeliveryAddress().getZone().getCode());
            }
            if (source.getDeliveryAddress().getCountry() != null) {
                deliveryAddress.setCountry(source.getDeliveryAddress().getCountry().getIsoCode());
            }
            deliveryAddress.setLatitude(source.getDeliveryAddress().getLatitude());
            deliveryAddress.setLongitude(source.getDeliveryAddress().getLongitude());
            deliveryAddress.setStateProvince(source.getDeliveryAddress().getState());
            target.setDelivery(deliveryAddress);
        }
    } catch (Exception e) {
        throw new ConversionException(e);
    }
    return target;
}
Also used : ConversionException(com.salesmanager.core.business.exception.ConversionException) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ConversionException(com.salesmanager.core.business.exception.ConversionException)

Example 4 with ReadableDelivery

use of com.salesmanager.shop.model.customer.ReadableDelivery in project shopizer by shopizer-ecommerce.

the class ReadableOrderPopulator method populate.

@Override
public ReadableOrder populate(Order source, ReadableOrder target, MerchantStore store, Language language) throws ConversionException {
    target.setId(source.getId());
    target.setDatePurchased(source.getDatePurchased());
    target.setOrderStatus(source.getStatus());
    target.setCurrency(source.getCurrency().getCode());
    // target.setCurrencyModel(source.getCurrency());
    target.setPaymentType(source.getPaymentType());
    target.setPaymentModule(source.getPaymentModuleCode());
    target.setShippingModule(source.getShippingModuleCode());
    if (source.getMerchant() != null) {
        /*			ReadableMerchantStorePopulator merchantPopulator = new ReadableMerchantStorePopulator();
			merchantPopulator.setCountryService(countryService);
			merchantPopulator.setFilePath(filePath);
			merchantPopulator.setZoneService(zoneService);*/
        ReadableMerchantStore readableStore = readableMerchantStorePopulator.populate(source.getMerchant(), null, store, source.getMerchant().getDefaultLanguage());
        target.setStore(readableStore);
    }
    if (source.getCustomerAgreement() != null) {
        target.setCustomerAgreed(source.getCustomerAgreement());
    }
    if (source.getConfirmedAddress() != null) {
        target.setConfirmedAddress(source.getConfirmedAddress());
    }
    com.salesmanager.shop.model.order.total.OrderTotal taxTotal = null;
    com.salesmanager.shop.model.order.total.OrderTotal shippingTotal = null;
    if (source.getBilling() != null) {
        ReadableBilling address = new ReadableBilling();
        address.setEmail(source.getCustomerEmailAddress());
        address.setCity(source.getBilling().getCity());
        address.setAddress(source.getBilling().getAddress());
        address.setCompany(source.getBilling().getCompany());
        address.setFirstName(source.getBilling().getFirstName());
        address.setLastName(source.getBilling().getLastName());
        address.setPostalCode(source.getBilling().getPostalCode());
        address.setPhone(source.getBilling().getTelephone());
        if (source.getBilling().getCountry() != null) {
            address.setCountry(source.getBilling().getCountry().getIsoCode());
        }
        if (source.getBilling().getZone() != null) {
            address.setZone(source.getBilling().getZone().getCode());
        }
        target.setBilling(address);
    }
    if (source.getOrderAttributes() != null && source.getOrderAttributes().size() > 0) {
        for (OrderAttribute attr : source.getOrderAttributes()) {
            com.salesmanager.shop.model.order.OrderAttribute a = new com.salesmanager.shop.model.order.OrderAttribute();
            a.setKey(attr.getKey());
            a.setValue(attr.getValue());
            target.getAttributes().add(a);
        }
    }
    if (source.getDelivery() != null) {
        ReadableDelivery address = new ReadableDelivery();
        address.setCity(source.getDelivery().getCity());
        address.setAddress(source.getDelivery().getAddress());
        address.setCompany(source.getDelivery().getCompany());
        address.setFirstName(source.getDelivery().getFirstName());
        address.setLastName(source.getDelivery().getLastName());
        address.setPostalCode(source.getDelivery().getPostalCode());
        address.setPhone(source.getDelivery().getTelephone());
        if (source.getDelivery().getCountry() != null) {
            address.setCountry(source.getDelivery().getCountry().getIsoCode());
        }
        if (source.getDelivery().getZone() != null) {
            address.setZone(source.getDelivery().getZone().getCode());
        }
        target.setDelivery(address);
    }
    List<com.salesmanager.shop.model.order.total.OrderTotal> totals = new ArrayList<com.salesmanager.shop.model.order.total.OrderTotal>();
    for (OrderTotal t : source.getOrderTotal()) {
        if (t.getOrderTotalType() == null) {
            continue;
        }
        if (t.getOrderTotalType().name().equals(OrderTotalType.TOTAL.name())) {
            com.salesmanager.shop.model.order.total.OrderTotal totalTotal = createTotal(t);
            target.setTotal(totalTotal);
            totals.add(totalTotal);
        } else if (t.getOrderTotalType().name().equals(OrderTotalType.TAX.name())) {
            com.salesmanager.shop.model.order.total.OrderTotal totalTotal = createTotal(t);
            if (taxTotal == null) {
                taxTotal = totalTotal;
            } else {
                BigDecimal v = taxTotal.getValue();
                v = v.add(totalTotal.getValue());
                taxTotal.setValue(v);
            }
            target.setTax(totalTotal);
            totals.add(totalTotal);
        } else if (t.getOrderTotalType().name().equals(OrderTotalType.SHIPPING.name())) {
            com.salesmanager.shop.model.order.total.OrderTotal totalTotal = createTotal(t);
            if (shippingTotal == null) {
                shippingTotal = totalTotal;
            } else {
                BigDecimal v = shippingTotal.getValue();
                v = v.add(totalTotal.getValue());
                shippingTotal.setValue(v);
            }
            target.setShipping(totalTotal);
            totals.add(totalTotal);
        } else if (t.getOrderTotalType().name().equals(OrderTotalType.HANDLING.name())) {
            com.salesmanager.shop.model.order.total.OrderTotal totalTotal = createTotal(t);
            if (shippingTotal == null) {
                shippingTotal = totalTotal;
            } else {
                BigDecimal v = shippingTotal.getValue();
                v = v.add(totalTotal.getValue());
                shippingTotal.setValue(v);
            }
            target.setShipping(totalTotal);
            totals.add(totalTotal);
        } else if (t.getOrderTotalType().name().equals(OrderTotalType.SUBTOTAL.name())) {
            com.salesmanager.shop.model.order.total.OrderTotal subTotal = createTotal(t);
            totals.add(subTotal);
        } else {
            com.salesmanager.shop.model.order.total.OrderTotal otherTotal = createTotal(t);
            totals.add(otherTotal);
        }
    }
    target.setTotals(totals);
    return target;
}
Also used : ReadableMerchantStore(com.salesmanager.shop.model.store.ReadableMerchantStore) ArrayList(java.util.ArrayList) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) BigDecimal(java.math.BigDecimal) ReadableBilling(com.salesmanager.shop.model.customer.ReadableBilling) OrderAttribute(com.salesmanager.core.model.order.attributes.OrderAttribute) OrderTotal(com.salesmanager.core.model.order.OrderTotal)

Example 5 with ReadableDelivery

use of com.salesmanager.shop.model.customer.ReadableDelivery 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

ReadableDelivery (com.salesmanager.shop.model.customer.ReadableDelivery)6 ServiceException (com.salesmanager.core.business.exception.ServiceException)4 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)4 OrderTotalSummary (com.salesmanager.core.model.order.OrderTotalSummary)4 Language (com.salesmanager.core.model.reference.language.Language)4 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)4 ShippingSummary (com.salesmanager.core.model.shipping.ShippingSummary)4 ShoppingCartItem (com.salesmanager.core.model.shoppingcart.ShoppingCartItem)4 ReadableShopOrder (com.salesmanager.shop.model.order.ReadableShopOrder)4 ReadableShippingSummary (com.salesmanager.shop.model.order.shipping.ReadableShippingSummary)4 ArrayList (java.util.ArrayList)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 OrderTotal (com.salesmanager.core.model.order.OrderTotal)3 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)3 ReadableCustomerDeliveryAddressPopulator (com.salesmanager.shop.populator.customer.ReadableCustomerDeliveryAddressPopulator)3 ReadableShippingSummaryPopulator (com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Product (com.salesmanager.core.model.catalog.product.Product)2