use of com.salesmanager.shop.model.customer.AnonymousCustomer 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.shop.model.customer.AnonymousCustomer in project shopizer by shopizer-ecommerce.
the class StoreFilter method preHandle.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setCharacterEncoding("UTF-8");
/**
* if url contains /services exit from here !
*/
if (request.getRequestURL().toString().toLowerCase().contains(SERVICES_URL_PATTERN) || request.getRequestURL().toString().toLowerCase().contains(REFERENCE_URL_PATTERN)) {
return true;
}
try {
/**
* merchant store *
*/
MerchantStore store = (MerchantStore) request.getSession().getAttribute(Constants.MERCHANT_STORE);
String storeCode = request.getParameter(STORE_REQUEST_PARAMETER);
// remove link set from controllers for declaring active - inactive
// links
request.removeAttribute(Constants.LINK_CODE);
if (!StringUtils.isBlank(storeCode)) {
if (store != null) {
if (!store.getCode().equals(storeCode)) {
store = setMerchantStoreInSession(request, storeCode);
}
} else {
// when url sm-shop/shop is being loaded for first time
// store is null
store = setMerchantStoreInSession(request, storeCode);
}
}
if (store == null) {
store = setMerchantStoreInSession(request, MerchantStore.DEFAULT_STORE);
}
if (StringUtils.isBlank(store.getStoreTemplate())) {
store.setStoreTemplate(Constants.DEFAULT_TEMPLATE);
}
request.setAttribute(Constants.MERCHANT_STORE, store);
/*
//remote ip address
String remoteAddress = "";
try {
if (request != null) {
remoteAddress = request.getHeader("X-Forwarded-For");
if (remoteAddress == null || "".equals(remoteAddress)) {
remoteAddress = request.getRemoteAddr();
}
}
remoteAddress = remoteAddress != null && remoteAddress.contains(",") ? remoteAddress.split(",")[0] : remoteAddress;
LOGGER.info("remote ip addres {}", remoteAddress);
} catch (Exception e) {
LOGGER.error("Error while getting user remote address");
}
*/
String ipAddress = GeoLocationUtils.getClientIpAddress(request);
UserContext userContext = UserContext.create();
userContext.setIpAddress(ipAddress);
/**
* customer *
*/
Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
if (customer != null) {
if (customer.getMerchantStore().getId().intValue() != store.getId().intValue()) {
request.getSession().removeAttribute(Constants.CUSTOMER);
}
if (!customer.isAnonymous()) {
if (!request.isUserInRole("AUTH_CUSTOMER")) {
request.removeAttribute(Constants.CUSTOMER);
}
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
request.setAttribute(Constants.CUSTOMER, customer);
}
if (customer == null) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
customer = customerService.getByNick(auth.getName());
if (customer != null) {
request.setAttribute(Constants.CUSTOMER, customer);
}
}
}
AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getSession().getAttribute(Constants.ANONYMOUS_CUSTOMER);
if (anonymousCustomer == null) {
Address address = null;
try {
if (!StringUtils.isBlank(ipAddress)) {
com.salesmanager.core.model.common.Address geoAddress = customerService.getCustomerAddress(store, ipAddress);
if (geoAddress != null) {
address = new Address();
address.setCountry(geoAddress.getCountry());
address.setCity(geoAddress.getCity());
address.setZone(geoAddress.getZone());
/**
* no postal code *
*/
// address.setPostalCode(geoAddress.getPostalCode());
}
}
} catch (Exception ce) {
LOGGER.error("Cannot get geo ip component ", ce);
}
if (address == null) {
address = new Address();
address.setCountry(store.getCountry().getIsoCode());
if (store.getZone() != null) {
address.setZone(store.getZone().getCode());
} else {
address.setStateProvince(store.getStorestateprovince());
}
/**
* no postal code *
*/
// address.setPostalCode(store.getStorepostalcode());
}
anonymousCustomer = new AnonymousCustomer();
anonymousCustomer.setBilling(address);
request.getSession().setAttribute(Constants.ANONYMOUS_CUSTOMER, anonymousCustomer);
} else {
request.setAttribute(Constants.ANONYMOUS_CUSTOMER, anonymousCustomer);
}
/**
* language & locale *
*/
Language language = languageUtils.getRequestLanguage(request, response);
request.setAttribute(Constants.LANGUAGE, language);
Locale locale = languageService.toLocale(language, store);
request.setAttribute(Constants.LOCALE, locale);
// Locale locale = LocaleContextHolder.getLocale();
LocaleContextHolder.setLocale(locale);
/**
* Breadcrumbs *
*/
setBreadcrumb(request, locale);
/**
* Get global objects Themes are built on a similar way displaying
* Header, Body and Footer Header and Footer are displayed on each
* page Some themes also contain side bars which may include similar
* emements
*
* Elements from Header : - CMS links - Customer - Mini shopping
* cart - Store name / logo - Top categories - Search
*
* Elements from Footer : - CMS links - Store address - Global
* payment information - Global shipping information
*/
// get from the cache first
/**
* The cache for each object contains 2 objects, a Cache and a
* Missed-Cache Get objects from the cache If not null use those
* objects If null, get entry from missed-cache If missed-cache not
* null then nothing exist If missed-cache null, add missed-cache
* entry and load from the database If objects from database not
* null store in cache
*/
/**
***** CMS Objects *******
*/
this.getContentObjects(store, language, request);
/**
***** CMS Page names *********
*/
this.getContentPageNames(store, language, request);
/**
***** Top Categories *******
*/
// this.getTopCategories(store, language, request);
this.setTopCategories(store, language, request);
/**
***** Default metatags ******
*/
/**
* Title Description Keywords
*/
PageInformation pageInformation = new PageInformation();
pageInformation.setPageTitle(store.getStorename());
pageInformation.setPageDescription(store.getStorename());
pageInformation.setPageKeywords(store.getStorename());
@SuppressWarnings("unchecked") Map<String, ContentDescription> contents = (Map<String, ContentDescription>) request.getAttribute(Constants.REQUEST_CONTENT_OBJECTS);
if (contents != null) {
// for(String key : contents.keySet()) {
// List<ContentDescription> contentsList = contents.get(key);
// for(Content content : contentsList) {
// if(key.equals(Constants.CONTENT_LANDING_PAGE)) {
// List<ContentDescription> descriptions =
// content.getDescriptions();
ContentDescription contentDescription = contents.get(Constants.CONTENT_LANDING_PAGE);
if (contentDescription != null) {
// for(ContentDescription contentDescription : descriptions)
// {
// if(contentDescription.getLanguage().getCode().equals(language.getCode()))
// {
pageInformation.setPageTitle(contentDescription.getName());
pageInformation.setPageDescription(contentDescription.getMetatagDescription());
pageInformation.setPageKeywords(contentDescription.getMetatagKeywords());
// }
}
// }
// }
// }
}
request.setAttribute(Constants.REQUEST_PAGE_INFORMATION, pageInformation);
/**
***** Configuration objects ******
*/
/**
* SHOP configuration type Should contain - Different configuration
* flags - Google analytics - Facebook page - Twitter handle - Show
* customer login - ...
*/
this.getMerchantConfigurations(store, request);
/**
***** Shopping Cart ********
*/
String shoppingCarCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
if (shoppingCarCode != null) {
request.setAttribute(Constants.REQUEST_SHOPPING_CART, shoppingCarCode);
}
} catch (Exception e) {
LOGGER.error("Error in StoreFilter", e);
}
return true;
}
use of com.salesmanager.shop.model.customer.AnonymousCustomer in project shopizer by shopizer-ecommerce.
the class CustomerRegistrationController method displayRegistration.
@RequestMapping(value = "/registration.html", method = RequestMethod.GET)
public String displayRegistration(final Model model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
model.addAttribute("recapatcha_public_key", siteKeyKey);
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
if (anonymousCustomer != null) {
customer.setBilling(anonymousCustomer.getBilling());
}
model.addAttribute("customer", customer);
/**
* template *
*/
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.register).append(".").append(store.getStoreTemplate());
return template.toString();
}
Aggregations