use of com.salesmanager.core.model.order.OrderTotal in project shopizer by shopizer-ecommerce.
the class EmailTemplatesUtils method sendOrderEmail.
/**
* Sends an email to the customer after a completed order
* @param customer
* @param order
* @param customerLocale
* @param language
* @param merchantStore
* @param contextPath
*/
@Async
public void sendOrderEmail(String toEmail, Customer customer, Order order, Locale customerLocale, Language language, MerchantStore merchantStore, String contextPath) {
/**
* issue with putting that elsewhere *
*/
LOGGER.info("Sending welcome email to customer");
try {
Map<String, Zone> zones = zoneService.getZones(language);
Map<String, Country> countries = countryService.getCountriesMap(language);
// format Billing address
StringBuilder billing = new StringBuilder();
if (StringUtils.isBlank(order.getBilling().getCompany())) {
billing.append(order.getBilling().getFirstName()).append(" ").append(order.getBilling().getLastName()).append(LINE_BREAK);
} else {
billing.append(order.getBilling().getCompany()).append(LINE_BREAK);
}
billing.append(order.getBilling().getAddress()).append(LINE_BREAK);
billing.append(order.getBilling().getCity()).append(", ");
if (order.getBilling().getZone() != null) {
Zone zone = zones.get(order.getBilling().getZone().getCode());
if (zone != null) {
billing.append(zone.getName());
}
billing.append(LINE_BREAK);
} else if (!StringUtils.isBlank(order.getBilling().getState())) {
billing.append(order.getBilling().getState()).append(LINE_BREAK);
}
Country country = countries.get(order.getBilling().getCountry().getIsoCode());
if (country != null) {
billing.append(country.getName()).append(" ");
}
billing.append(order.getBilling().getPostalCode());
// format shipping address
StringBuilder shipping = null;
if (order.getDelivery() != null && !StringUtils.isBlank(order.getDelivery().getFirstName())) {
shipping = new StringBuilder();
if (StringUtils.isBlank(order.getDelivery().getCompany())) {
shipping.append(order.getDelivery().getFirstName()).append(" ").append(order.getDelivery().getLastName()).append(LINE_BREAK);
} else {
shipping.append(order.getDelivery().getCompany()).append(LINE_BREAK);
}
shipping.append(order.getDelivery().getAddress()).append(LINE_BREAK);
shipping.append(order.getDelivery().getCity()).append(", ");
if (order.getDelivery().getZone() != null) {
Zone zone = zones.get(order.getDelivery().getZone().getCode());
if (zone != null) {
shipping.append(zone.getName());
}
shipping.append(LINE_BREAK);
} else if (!StringUtils.isBlank(order.getDelivery().getState())) {
shipping.append(order.getDelivery().getState()).append(LINE_BREAK);
}
Country deliveryCountry = countries.get(order.getDelivery().getCountry().getIsoCode());
if (country != null) {
shipping.append(deliveryCountry.getName()).append(" ");
}
shipping.append(order.getDelivery().getPostalCode());
}
if (shipping == null && StringUtils.isNotBlank(order.getShippingModuleCode())) {
// TODO IF HAS NO SHIPPING
shipping = billing;
}
// format order
// String storeUri = FilePathUtils.buildStoreUri(merchantStore, contextPath);
StringBuilder orderTable = new StringBuilder();
orderTable.append(TABLE);
for (OrderProduct product : order.getOrderProducts()) {
// Product productModel = productService.getByCode(product.getSku(), language);
orderTable.append(TR);
orderTable.append(TD).append(product.getProductName()).append(" - ").append(product.getSku()).append(CLOSING_TD);
orderTable.append(TD).append(messages.getMessage("label.quantity", customerLocale)).append(": ").append(product.getProductQuantity()).append(CLOSING_TD);
orderTable.append(TD).append(pricingService.getDisplayAmount(product.getOneTimeCharge(), merchantStore)).append(CLOSING_TD);
orderTable.append(CLOSING_TR);
}
// order totals
for (OrderTotal total : order.getOrderTotal()) {
orderTable.append(TR_BORDER);
// orderTable.append(TD);
// orderTable.append(CLOSING_TD);
orderTable.append(TD);
orderTable.append(CLOSING_TD);
orderTable.append(TD);
orderTable.append("<strong>");
if (total.getModule().equals("tax")) {
orderTable.append(total.getText()).append(": ");
} else {
// if(total.getModule().equals("total") || total.getModule().equals("subtotal")) {
// }
orderTable.append(messages.getMessage(total.getOrderTotalCode(), customerLocale)).append(": ");
// if(total.getModule().equals("total") || total.getModule().equals("subtotal")) {
// }
}
orderTable.append("</strong>");
orderTable.append(CLOSING_TD);
orderTable.append(TD);
orderTable.append("<strong>");
orderTable.append(pricingService.getDisplayAmount(total.getValue(), merchantStore));
orderTable.append("</strong>");
orderTable.append(CLOSING_TD);
orderTable.append(CLOSING_TR);
}
orderTable.append(CLOSING_TABLE);
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(contextPath, merchantStore, messages, customerLocale);
templateTokens.put(EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", customerLocale));
templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, order.getBilling().getFirstName());
templateTokens.put(EmailConstants.EMAIL_CUSTOMER_LASTNAME, order.getBilling().getLastName());
String[] params = { String.valueOf(order.getId()) };
String[] dt = { DateUtil.formatDate(order.getDatePurchased()) };
templateTokens.put(EmailConstants.EMAIL_ORDER_NUMBER, messages.getMessage("email.order.confirmation", params, customerLocale));
templateTokens.put(EmailConstants.EMAIL_ORDER_DATE, messages.getMessage("email.order.ordered", dt, customerLocale));
templateTokens.put(EmailConstants.EMAIL_ORDER_THANKS, messages.getMessage("email.order.thanks", customerLocale));
templateTokens.put(EmailConstants.ADDRESS_BILLING, billing.toString());
templateTokens.put(EmailConstants.ORDER_PRODUCTS_DETAILS, orderTable.toString());
templateTokens.put(EmailConstants.EMAIL_ORDER_DETAILS_TITLE, messages.getMessage("label.order.details", customerLocale));
templateTokens.put(EmailConstants.ADDRESS_BILLING_TITLE, messages.getMessage("label.customer.billinginformation", customerLocale));
templateTokens.put(EmailConstants.PAYMENT_METHOD_TITLE, messages.getMessage("label.order.paymentmode", customerLocale));
templateTokens.put(EmailConstants.PAYMENT_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("payment.type.").append(order.getPaymentType().name()).toString(), customerLocale, order.getPaymentType().name()));
if (StringUtils.isNotBlank(order.getShippingModuleCode())) {
// templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("module.shipping.").append(order.getShippingModuleCode()).toString(),customerLocale,order.getShippingModuleCode()));
templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, messages.getMessage(new StringBuilder().append("module.shipping.").append(order.getShippingModuleCode()).toString(), new String[] { merchantStore.getStorename() }, customerLocale));
templateTokens.put(EmailConstants.ADDRESS_SHIPPING_TITLE, messages.getMessage("label.order.shippingmethod", customerLocale));
templateTokens.put(EmailConstants.ADDRESS_DELIVERY_TITLE, messages.getMessage("label.customer.shippinginformation", customerLocale));
templateTokens.put(EmailConstants.SHIPPING_METHOD_TITLE, messages.getMessage("label.customer.shippinginformation", customerLocale));
templateTokens.put(EmailConstants.ADDRESS_DELIVERY, shipping.toString());
} else {
templateTokens.put(EmailConstants.SHIPPING_METHOD_DETAILS, "");
templateTokens.put(EmailConstants.ADDRESS_SHIPPING_TITLE, "");
templateTokens.put(EmailConstants.ADDRESS_DELIVERY_TITLE, "");
templateTokens.put(EmailConstants.SHIPPING_METHOD_TITLE, "");
templateTokens.put(EmailConstants.ADDRESS_DELIVERY, "");
}
String status = messages.getMessage("label.order." + order.getStatus().name(), customerLocale, order.getStatus().name());
String[] statusMessage = { DateUtil.formatDate(order.getDatePurchased()), status };
templateTokens.put(EmailConstants.ORDER_STATUS, messages.getMessage("email.order.status", statusMessage, customerLocale));
String[] title = { merchantStore.getStorename(), String.valueOf(order.getId()) };
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.order.title", title, customerLocale));
email.setTo(toEmail);
email.setTemplateName(EmailConstants.EMAIL_ORDER_TPL);
email.setTemplateTokens(templateTokens);
LOGGER.debug("Sending email to {} for order id {} ", customer.getEmailAddress(), order.getId());
emailService.sendHtmlEmail(merchantStore, email);
} catch (Exception e) {
LOGGER.error("Error occured while sending order confirmation email ", e);
}
}
use of com.salesmanager.core.model.order.OrderTotal 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;
}
use of com.salesmanager.core.model.order.OrderTotal 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