use of com.salesmanager.core.model.reference.language.Language 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.reference.language.Language in project shopizer by shopizer-ecommerce.
the class ShoppingOrderController method commitPreAuthorizedOrder.
@RequestMapping("/commitPreAuthorized.html")
public String commitPreAuthorizedOrder(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
Language language = (Language) request.getAttribute("LANGUAGE");
ShopOrder order = super.getSessionAttribute(Constants.ORDER, request);
if (order == null) {
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Pages.timeout).append(".").append(store.getStoreTemplate());
return template.toString();
}
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");
}
@SuppressWarnings("unchecked") 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 pre-authorized order -> " + jsonInString);
} catch (Exception de) {
LOGGER.error(de.getMessage());
}
}
}
try {
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);
// already validated, proceed with commit
Order orderModel = this.commitOrder(order, request, locale);
super.setSessionAttribute(Constants.ORDER_ID, orderModel.getId(), request);
return "redirect:/shop/order/confirmation.html";
} catch (Exception e) {
LOGGER.error("Error while commiting order", e);
throw e;
}
}
use of com.salesmanager.core.model.reference.language.Language 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.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.
the class ShoppingOrderController method commitOrder.
private Order commitOrder(ShopOrder order, HttpServletRequest request, Locale locale) throws Exception, ServiceException {
LOGGER.info("Entering comitOrder");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
Language language = (Language) request.getAttribute("LANGUAGE");
String userName = null;
String password = null;
PersistableCustomer customer = order.getCustomer();
/**
* set username and password to persistable object *
*/
LOGGER.info("Set username and password to customer");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Customer authCustomer = null;
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
LOGGER.info("Customer authenticated");
authCustomer = customerFacade.getCustomerByUserName(auth.getName(), store);
// set id and authentication information
customer.setUserName(authCustomer.getNick());
// customer.setEncodedPassword(authCustomer.getPassword());
customer.setId(authCustomer.getId());
} else {
// set customer id to null
customer.setId(null);
}
// if the customer is new, generate a password
LOGGER.info("New customer generate password");
if (customer.getId() == null || customer.getId() == 0) {
// new customer
// password = UserReset.generateRandomString();
// String encodedPassword = passwordEncoder.encode(password);
// customer.setEncodedPassword(encodedPassword);
}
if (order.isShipToBillingAdress()) {
customer.setDelivery(customer.getBilling());
}
LOGGER.info("Before creating new volatile");
Customer modelCustomer = null;
try {
// set groups
if (authCustomer == null) {
// not authenticated, create a new volatile user
modelCustomer = customerFacade.getCustomerModel(customer, store, language);
customerFacade.setCustomerModelDefaultProperties(modelCustomer, store);
userName = modelCustomer.getNick();
LOGGER.debug("About to persist volatile customer to database.");
if (modelCustomer.getDefaultLanguage() == null) {
modelCustomer.setDefaultLanguage(languageService.toLanguage(locale));
}
customerService.saveOrUpdate(modelCustomer);
} else {
// use existing customer
LOGGER.info("Populate customer model");
modelCustomer = customerFacade.populateCustomerModel(authCustomer, customer, store, language);
}
} catch (Exception e) {
throw new ServiceException(e);
}
LOGGER.debug("About to save transaction");
Order modelOrder = null;
Transaction initialTransaction = (Transaction) super.getSessionAttribute(Constants.INIT_TRANSACTION_KEY, request);
if (initialTransaction != null) {
modelOrder = orderFacade.processOrder(order, modelCustomer, initialTransaction, store, language);
} else {
modelOrder = orderFacade.processOrder(order, modelCustomer, store, language);
}
// save order id in session
super.setSessionAttribute(Constants.ORDER_ID, modelOrder.getId(), request);
// set a unique token for confirmation
super.setSessionAttribute(Constants.ORDER_ID_TOKEN, modelOrder.getId(), request);
LOGGER.debug("Transaction ended and order saved");
LOGGER.debug("Remove cart");
// get cart
String cartCode = super.getSessionAttribute(Constants.SHOPPING_CART, request);
if (StringUtils.isNotBlank(cartCode)) {
try {
shoppingCartFacade.setOrderId(cartCode, modelOrder.getId(), store);
} catch (Exception e) {
LOGGER.error("Cannot update cart " + cartCode, e);
throw new ServiceException(e);
}
}
// cleanup the order objects
super.removeAttribute(Constants.ORDER, request);
super.removeAttribute(Constants.ORDER_SUMMARY, request);
super.removeAttribute(Constants.INIT_TRANSACTION_KEY, request);
super.removeAttribute(Constants.SHIPPING_OPTIONS, request);
super.removeAttribute(Constants.SHIPPING_SUMMARY, request);
super.removeAttribute(Constants.SHOPPING_CART, request);
LOGGER.debug("Refresh customer");
try {
// refresh customer --
modelCustomer = customerFacade.getCustomerByUserName(modelCustomer.getNick(), store);
// if has downloads, authenticate
// check if any downloads exist for this order6
List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(modelOrder.getId());
if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
LOGGER.debug("Is user authenticated ? ", auth.isAuthenticated());
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
// already authenticated
} else {
// authenticate
customerFacade.authenticate(modelCustomer, userName, password);
super.setSessionAttribute(Constants.CUSTOMER, modelCustomer, request);
}
// send new user registration template
if (order.getCustomer().getId() == null || order.getCustomer().getId().longValue() == 0) {
// send email for new customer
// set clear password for email
customer.setPassword(password);
customer.setUserName(userName);
emailTemplatesUtils.sendRegistrationEmail(customer, store, locale, request.getContextPath());
}
}
// send order confirmation email to customer
emailTemplatesUtils.sendOrderEmail(modelCustomer.getEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
if (orderService.hasDownloadFiles(modelOrder)) {
emailTemplatesUtils.sendOrderDownloadEmail(modelCustomer, modelOrder, store, locale, request.getContextPath());
}
// send order confirmation email to merchant
emailTemplatesUtils.sendOrderEmail(store.getStoreEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
} catch (Exception e) {
LOGGER.error("Error while post processing order", e);
}
return modelOrder;
}
use of com.salesmanager.core.model.reference.language.Language in project shopizer by shopizer-ecommerce.
the class ShoppingOrderPaymentController method paymentAction.
/**
* Recalculates shipping and tax following a change in country or province
*
* @param order
* @param request
* @param response
* @param locale
* @return
* @throws Exception
*/
@RequestMapping(value = { "/order/payment/{action}/{paymentmethod}.html" }, method = RequestMethod.POST)
@ResponseBody
public String paymentAction(@Valid @ModelAttribute(value = "order") ShopOrder order, @PathVariable String action, @PathVariable String paymentmethod, 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");
AjaxResponse ajaxResponse = new AjaxResponse();
try {
com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
Set<ShoppingCartItem> items = cart.getLineItems();
List<ShoppingCartItem> cartItems = new ArrayList<ShoppingCartItem>(items);
order.setShoppingCartItems(cartItems);
// validate order first
Map<String, String> messages = new TreeMap<String, String>();
orderFacade.validateOrder(order, new BeanPropertyBindingResult(order, "order"), messages, store, locale);
if (CollectionUtils.isNotEmpty(messages.values())) {
for (String key : messages.keySet()) {
String value = messages.get(key);
ajaxResponse.addValidationMessage(key, value);
}
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_VALIDATION_FAILED);
return ajaxResponse.toJSONString();
}
IntegrationConfiguration config = paymentService.getPaymentConfiguration(order.getPaymentModule(), store);
IntegrationModule integrationModule = paymentService.getPaymentMethodByCode(store, order.getPaymentModule());
// OrderTotalSummary orderTotalSummary =
// orderFacade.calculateOrderTotal(store, order, language);
OrderTotalSummary orderTotalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
if (orderTotalSummary == null) {
orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
}
ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute("SHIPPING_SUMMARY");
if (summary != null) {
order.setShippingSummary(summary);
}
if (action.equals(INIT_ACTION)) {
if (paymentmethod.equals("PAYPAL")) {
try {
PaymentModule module = paymentService.getPaymentModule("paypal-express-checkout");
PayPalExpressCheckoutPayment p = (PayPalExpressCheckoutPayment) module;
PaypalPayment payment = new PaypalPayment();
payment.setCurrency(store.getCurrency());
Transaction transaction = p.initPaypalTransaction(store, cartItems, orderTotalSummary, payment, config, integrationModule);
transactionService.create(transaction);
super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
StringBuilder urlAppender = new StringBuilder();
urlAppender.append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_REGULAR"));
urlAppender.append(transaction.getTransactionDetails().get("TOKEN"));
if (config.getEnvironment().equals(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT)) {
StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_PRODUCTION")).append(urlAppender.toString());
ajaxResponse.addEntry("url", url.toString());
} else {
StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_SANDBOX")).append(urlAppender.toString());
ajaxResponse.addEntry("url", url.toString());
}
// keep order in session when user comes back from pp
super.setSessionAttribute(Constants.ORDER, order, request);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
} catch (Exception e) {
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
} else if (paymentmethod.equals("stripe3")) {
try {
PaymentModule module = paymentService.getPaymentModule(paymentmethod);
Stripe3Payment p = (Stripe3Payment) module;
PaypalPayment payment = new PaypalPayment();
payment.setCurrency(store.getCurrency());
Transaction transaction = p.initTransaction(store, null, orderTotalSummary.getTotal(), null, config, integrationModule);
transactionService.create(transaction);
super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
// keep order in session when user comes back from pp
super.setSessionAttribute(Constants.ORDER, order, request);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
ajaxResponse.setDataMap(transaction.getTransactionDetails());
} catch (Exception e) {
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
}
}
} catch (Exception e) {
LOGGER.error("Error while performing payment action " + action + " for payment method " + paymentmethod, e);
ajaxResponse.setErrorMessage(e);
ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
return ajaxResponse.toJSONString();
}
Aggregations