use of com.salesmanager.core.model.customer.Customer 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.customer.Customer 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.customer.Customer in project shopizer by shopizer-ecommerce.
the class CustomerAccountController method saveCustomerAttributes.
/**
* Manage the edition of customer attributes
* @param request
* @param locale
* @return
* @throws Exception
*/
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping(value = { "/attributes/save.html" }, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> saveCustomerAttributes(HttpServletRequest request, Locale locale) throws Exception {
AjaxResponse resp = new AjaxResponse();
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
// 1=1&2=on&3=eeee&4=on&customer=1
@SuppressWarnings("rawtypes") Enumeration parameterNames = request.getParameterNames();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Customer customer = null;
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
customer = customerFacade.getCustomerByUserName(auth.getName(), store);
}
if (customer == null) {
LOGGER.error("Customer id [customer] is not defined in the parameters");
resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
String returnString = resp.toJSONString();
return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK);
}
if (customer.getMerchantStore().getId().intValue() != store.getId().intValue()) {
LOGGER.error("Customer id does not belong to current store");
resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
String returnString = resp.toJSONString();
return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK);
}
List<CustomerAttribute> customerAttributes = customerAttributeService.getByCustomer(store, customer);
Map<Long, CustomerAttribute> customerAttributesMap = new HashMap<Long, CustomerAttribute>();
for (CustomerAttribute attr : customerAttributes) {
customerAttributesMap.put(attr.getCustomerOption().getId(), attr);
}
parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
String parameterValue = request.getParameter(parameterName);
try {
String[] parameterKey = parameterName.split("-");
com.salesmanager.core.model.customer.attribute.CustomerOption customerOption = null;
com.salesmanager.core.model.customer.attribute.CustomerOptionValue customerOptionValue = null;
if (CUSTOMER_ID_PARAMETER.equals(parameterName)) {
continue;
}
if (parameterKey.length > 1) {
// parse key - value
String key = parameterKey[0];
String value = parameterKey[1];
// should be on
customerOption = customerOptionService.getById(new Long(key));
customerOptionValue = customerOptionValueService.getById(new Long(value));
} else {
customerOption = customerOptionService.getById(new Long(parameterName));
customerOptionValue = customerOptionValueService.getById(new Long(parameterValue));
}
// get the attribute
// CustomerAttribute attribute = customerAttributeService.getByCustomerOptionId(store, customer.getId(), customerOption.getId());
CustomerAttribute attribute = customerAttributesMap.get(customerOption.getId());
if (attribute == null) {
attribute = new CustomerAttribute();
attribute.setCustomer(customer);
attribute.setCustomerOption(customerOption);
} else {
customerAttributes.remove(attribute);
}
if (customerOption.getCustomerOptionType().equals(CustomerOptionType.Text.name())) {
if (!StringUtils.isBlank(parameterValue)) {
attribute.setCustomerOptionValue(customerOptionValue);
attribute.setTextValue(parameterValue);
} else {
attribute.setTextValue(null);
}
} else {
attribute.setCustomerOptionValue(customerOptionValue);
}
if (attribute.getId() != null && attribute.getId().longValue() > 0) {
if (attribute.getCustomerOptionValue() == null) {
customerAttributeService.delete(attribute);
} else {
customerAttributeService.update(attribute);
}
} else {
customerAttributeService.save(attribute);
}
} catch (Exception e) {
LOGGER.error("Cannot get parameter information " + parameterName, e);
}
}
// and now the remaining to be removed
for (CustomerAttribute attr : customerAttributes) {
customerAttributeService.delete(attr);
}
// refresh customer
Customer c = customerService.getById(customer.getId());
super.setSessionAttribute(Constants.CUSTOMER, c, request);
resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
String returnString = resp.toJSONString();
return new ResponseEntity<String>(returnString, httpHeaders, HttpStatus.OK);
}
use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.
the class CustomerAccountController method updateCustomerAddress.
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping(value = "/updateAddress.html", method = { RequestMethod.GET, RequestMethod.POST })
public String updateCustomerAddress(@Valid @ModelAttribute("address") Address address, BindingResult bindingResult, final Model model, final HttpServletRequest request, @RequestParam(value = "billingAddress", required = false) Boolean billingAddress) throws Exception {
MerchantStore store = getSessionAttribute(Constants.MERCHANT_STORE, request);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Customer customer = null;
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
customer = customerFacade.getCustomerByUserName(auth.getName(), store);
}
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.EditAddress).append(".").append(store.getStoreTemplate());
if (customer == null) {
return "redirect:/" + Constants.SHOP_URI;
}
model.addAttribute("address", address);
model.addAttribute("customerId", customer.getId());
if (bindingResult.hasErrors()) {
LOGGER.info("found {} error(s) while validating customer address ", bindingResult.getErrorCount());
return template.toString();
}
Language language = getSessionAttribute(Constants.LANGUAGE, request);
customerFacade.updateAddress(customer.getId(), store, address, language);
Customer c = customerService.getById(customer.getId());
super.setSessionAttribute(Constants.CUSTOMER, c, request);
model.addAttribute("success", "success");
return template.toString();
}
use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.
the class CustomerAccountController method displayCustomerBillingAddress.
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
// @Secured("AUTH_CUSTOMER")
@RequestMapping(value = "/billing.html", method = RequestMethod.GET)
public String displayCustomerBillingAddress(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
MerchantStore store = getSessionAttribute(Constants.MERCHANT_STORE, request);
Language language = getSessionAttribute(Constants.LANGUAGE, request);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Customer customer = null;
if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
customer = customerFacade.getCustomerByUserName(auth.getName(), store);
}
if (customer == null) {
return "redirect:/" + Constants.SHOP_URI;
}
CustomerEntity customerEntity = customerFacade.getCustomerDataByUserName(customer.getNick(), store, language);
if (customer != null) {
model.addAttribute("customer", customerEntity);
}
/**
* template *
*/
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.Billing).append(".").append(store.getStoreTemplate());
return template.toString();
}
Aggregations