use of com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator 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;
}
use of com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator 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;
}
Aggregations