use of com.salesmanager.core.model.payments.PaymentMethod 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();
}
use of com.salesmanager.core.model.payments.PaymentMethod in project shopizer by shopizer-ecommerce.
the class PaymentConfigurationFacadeImpl method configuration.
@Override
public ReadableConfiguration configuration(String module, MerchantStore store) {
try {
ReadableConfiguration config = null;
List<PaymentMethod> methods = paymentService.getAcceptedPaymentMethods(store);
Optional<ReadableConfiguration> configuration = methods.stream().filter(m -> module.equals(m.getModule().getCode())).map(m -> this.configuration(m.getInformations(), store)).findFirst();
if (configuration.isPresent()) {
config = configuration.get();
}
return config;
} catch (ServiceException e) {
throw new ServiceRuntimeException("Error while getting payment configuration [" + module + "]", e);
}
}
use of com.salesmanager.core.model.payments.PaymentMethod in project shopizer by shopizer-ecommerce.
the class PaymentConfigurationFacadeImpl method configurations.
@Override
public List<ReadableConfiguration> configurations(MerchantStore store) {
try {
List<PaymentMethod> methods = paymentService.getAcceptedPaymentMethods(store);
List<ReadableConfiguration> configurations = methods.stream().map(m -> configuration(m.getInformations(), store)).collect(Collectors.toList());
return configurations;
} catch (ServiceException e) {
throw new ServiceRuntimeException("Error while getting payment configurations", e);
}
}
use of com.salesmanager.core.model.payments.PaymentMethod in project shopizer by shopizer-ecommerce.
the class PaymentServiceImpl method getAcceptedPaymentMethods.
@Override
public List<PaymentMethod> getAcceptedPaymentMethods(MerchantStore store) throws ServiceException {
Map<String, IntegrationConfiguration> modules = this.getPaymentModulesConfigured(store);
List<PaymentMethod> returnModules = new ArrayList<PaymentMethod>();
for (String module : modules.keySet()) {
IntegrationConfiguration config = modules.get(module);
if (config.isActive()) {
IntegrationModule md = this.getPaymentMethodByCode(store, config.getModuleCode());
if (md == null) {
continue;
}
PaymentMethod paymentMethod = new PaymentMethod();
paymentMethod.setDefaultSelected(config.isDefaultSelected());
paymentMethod.setPaymentMethodCode(config.getModuleCode());
paymentMethod.setModule(md);
paymentMethod.setInformations(config);
PaymentType type = PaymentType.fromString(md.getType());
paymentMethod.setPaymentType(type);
returnModules.add(paymentMethod);
}
}
return returnModules;
}
use of com.salesmanager.core.model.payments.PaymentMethod 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";
}
Aggregations