use of com.salesmanager.core.model.order.orderproduct.OrderProductDownload 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.order.orderproduct.OrderProductDownload in project shopizer by shopizer-ecommerce.
the class CustomerOrdersController method orderDetails.
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping(value = "/order.html", method = { RequestMethod.GET, RequestMethod.POST })
public String orderDetails(final Model model, final HttpServletRequest request, @RequestParam(value = "orderId", required = true) final String orderId) throws Exception {
MerchantStore store = getSessionAttribute(Constants.MERCHANT_STORE, request);
Language language = (Language) request.getAttribute(Constants.LANGUAGE);
if (StringUtils.isBlank(orderId)) {
LOGGER.error("Order Id can not be null or empty");
}
LOGGER.info("Fetching order details for Id " + orderId);
// get order id
Long lOrderId = null;
try {
lOrderId = Long.parseLong(orderId);
} catch (NumberFormatException nfe) {
LOGGER.error("Cannot parse orderId to long " + orderId);
return "redirect:/" + Constants.SHOP_URI;
}
// check if order belongs to customer logged in
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;
}
ReadableOrder order = orderFacade.getReadableOrder(lOrderId, store, customer.getDefaultLanguage());
model.addAttribute("order", order);
// check if any downloads exist for this order
List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(order.getId());
if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
ReadableOrderProductDownloadPopulator populator = new ReadableOrderProductDownloadPopulator();
List<ReadableOrderProductDownload> downloads = new ArrayList<ReadableOrderProductDownload>();
for (OrderProductDownload download : orderProductDownloads) {
ReadableOrderProductDownload view = new ReadableOrderProductDownload();
populator.populate(download, view, store, language);
downloads.add(view);
}
model.addAttribute("downloads", downloads);
}
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.customerOrder).append(".").append(store.getStoreTemplate());
return template.toString();
}
use of com.salesmanager.core.model.order.orderproduct.OrderProductDownload in project shopizer by shopizer-ecommerce.
the class ShoppingOrderDownloadController method downloadFile.
/**
* Virtual product(s) download link
* @param id
* @param model
* @param request
* @param response
* @return
* @throws Exception
*/
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping("/download/{orderId}/{id}.html")
@ResponseBody
public byte[] downloadFile(@PathVariable Long orderId, @PathVariable Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
FileContentType fileType = FileContentType.PRODUCT_DIGITAL;
// get customer and check order
Order order = orderService.getById(orderId);
if (order == null) {
LOGGER.warn("Order is null for id " + orderId);
response.sendError(404, "Image not found");
return null;
}
// order belongs to customer
Customer customer = (Customer) super.getSessionAttribute(Constants.CUSTOMER, request);
if (customer == null) {
response.sendError(404, "Image not found");
return null;
}
// get it from OrderProductDownlaod
String fileName = null;
OrderProductDownload download = orderProductDownloadService.getById(id);
if (download == null) {
LOGGER.warn("OrderProductDownload is null for id " + id);
response.sendError(404, "Image not found");
return null;
}
fileName = download.getOrderProductFilename();
// needs to query the new API
OutputContentFile file = contentService.getContentFile(store.getCode(), fileType, fileName);
if (file != null) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
return file.getFile().toByteArray();
} else {
LOGGER.warn("Image not found for OrderProductDownload id " + id);
response.sendError(404, "Image not found");
return null;
}
// product image
// example -> /download/12345/120.html
}
use of com.salesmanager.core.model.order.orderproduct.OrderProductDownload in project shopizer by shopizer-ecommerce.
the class OrderProductPopulator method populate.
/**
* Converts a ShoppingCartItem carried in the ShoppingCart to an OrderProduct
* that will be saved in the system
*/
@Override
public OrderProduct populate(ShoppingCartItem source, OrderProduct target, MerchantStore store, Language language) throws ConversionException {
Validate.notNull(productService, "productService must be set");
Validate.notNull(digitalProductService, "digitalProductService must be set");
Validate.notNull(productAttributeService, "productAttributeService must be set");
try {
Product modelProduct = productService.getById(source.getProductId());
if (modelProduct == null) {
throw new ConversionException("Cannot get product with id (productId) " + source.getProductId());
}
if (modelProduct.getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ConversionException("Invalid product id " + source.getProductId());
}
DigitalProduct digitalProduct = digitalProductService.getByProduct(store, modelProduct);
if (digitalProduct != null) {
OrderProductDownload orderProductDownload = new OrderProductDownload();
orderProductDownload.setOrderProductFilename(digitalProduct.getProductFileName());
orderProductDownload.setOrderProduct(target);
orderProductDownload.setDownloadCount(0);
orderProductDownload.setMaxdays(ApplicationConstants.MAX_DOWNLOAD_DAYS);
target.getDownloads().add(orderProductDownload);
}
target.setOneTimeCharge(source.getItemPrice());
target.setProductName(source.getProduct().getDescriptions().iterator().next().getName());
target.setProductQuantity(source.getQuantity());
target.setSku(source.getProduct().getSku());
FinalPrice finalPrice = source.getFinalPrice();
if (finalPrice == null) {
throw new ConversionException("Object final price not populated in shoppingCartItem (source)");
}
// Default price
OrderProductPrice orderProductPrice = orderProductPrice(finalPrice);
orderProductPrice.setOrderProduct(target);
Set<OrderProductPrice> prices = new HashSet<OrderProductPrice>();
prices.add(orderProductPrice);
// Other prices
List<FinalPrice> otherPrices = finalPrice.getAdditionalPrices();
if (otherPrices != null) {
for (FinalPrice otherPrice : otherPrices) {
OrderProductPrice other = orderProductPrice(otherPrice);
other.setOrderProduct(target);
prices.add(other);
}
}
target.setPrices(prices);
// OrderProductAttribute
Set<ShoppingCartAttributeItem> attributeItems = source.getAttributes();
if (!CollectionUtils.isEmpty(attributeItems)) {
Set<OrderProductAttribute> attributes = new HashSet<OrderProductAttribute>();
for (ShoppingCartAttributeItem attribute : attributeItems) {
OrderProductAttribute orderProductAttribute = new OrderProductAttribute();
orderProductAttribute.setOrderProduct(target);
Long id = attribute.getProductAttributeId();
ProductAttribute attr = productAttributeService.getById(id);
if (attr == null) {
throw new ConversionException("Attribute id " + id + " does not exists");
}
if (attr.getProduct().getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ConversionException("Attribute id " + id + " invalid for this store");
}
orderProductAttribute.setProductAttributeIsFree(attr.getProductAttributeIsFree());
orderProductAttribute.setProductAttributeName(attr.getProductOption().getDescriptionsSettoList().get(0).getName());
orderProductAttribute.setProductAttributeValueName(attr.getProductOptionValue().getDescriptionsSettoList().get(0).getName());
orderProductAttribute.setProductAttributePrice(attr.getProductAttributePrice());
orderProductAttribute.setProductAttributeWeight(attr.getProductAttributeWeight());
orderProductAttribute.setProductOptionId(attr.getProductOption().getId());
orderProductAttribute.setProductOptionValueId(attr.getProductOptionValue().getId());
attributes.add(orderProductAttribute);
}
target.setOrderAttributes(attributes);
}
} catch (Exception e) {
throw new ConversionException(e);
}
return target;
}
use of com.salesmanager.core.model.order.orderproduct.OrderProductDownload in project shopizer by shopizer-ecommerce.
the class PersistableOrderProductPopulator method populate.
/**
* Converts a ShoppingCartItem carried in the ShoppingCart to an OrderProduct
* that will be saved in the system
*/
@Override
public OrderProduct populate(PersistableOrderProduct source, OrderProduct target, MerchantStore store, Language language) throws ConversionException {
Validate.notNull(productService, "productService must be set");
Validate.notNull(digitalProductService, "digitalProductService must be set");
Validate.notNull(productAttributeService, "productAttributeService must be set");
try {
Product modelProduct = productService.getById(source.getProduct().getId());
if (modelProduct == null) {
throw new ConversionException("Cannot get product with id (productId) " + source.getProduct().getId());
}
if (modelProduct.getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ConversionException("Invalid product id " + source.getProduct().getId());
}
DigitalProduct digitalProduct = digitalProductService.getByProduct(store, modelProduct);
if (digitalProduct != null) {
OrderProductDownload orderProductDownload = new OrderProductDownload();
orderProductDownload.setOrderProductFilename(digitalProduct.getProductFileName());
orderProductDownload.setOrderProduct(target);
orderProductDownload.setDownloadCount(0);
orderProductDownload.setMaxdays(ApplicationConstants.MAX_DOWNLOAD_DAYS);
target.getDownloads().add(orderProductDownload);
}
target.setOneTimeCharge(source.getPrice());
target.setProductName(source.getProduct().getDescription().getName());
target.setProductQuantity(source.getOrderedQuantity());
target.setSku(source.getProduct().getSku());
OrderProductPrice orderProductPrice = new OrderProductPrice();
orderProductPrice.setDefaultPrice(true);
orderProductPrice.setProductPrice(source.getPrice());
orderProductPrice.setOrderProduct(target);
Set<OrderProductPrice> prices = new HashSet<OrderProductPrice>();
prices.add(orderProductPrice);
/**
* DO NOT SUPPORT MUTIPLE PRICES *
*/
/* //Other prices
List<FinalPrice> otherPrices = finalPrice.getAdditionalPrices();
if(otherPrices!=null) {
for(FinalPrice otherPrice : otherPrices) {
OrderProductPrice other = orderProductPrice(otherPrice);
other.setOrderProduct(target);
prices.add(other);
}
}*/
target.setPrices(prices);
// OrderProductAttribute
List<ProductAttribute> attributeItems = source.getAttributes();
if (!CollectionUtils.isEmpty(attributeItems)) {
Set<OrderProductAttribute> attributes = new HashSet<OrderProductAttribute>();
for (ProductAttribute attribute : attributeItems) {
OrderProductAttribute orderProductAttribute = new OrderProductAttribute();
orderProductAttribute.setOrderProduct(target);
Long id = attribute.getId();
com.salesmanager.core.model.catalog.product.attribute.ProductAttribute attr = productAttributeService.getById(id);
if (attr == null) {
throw new ConversionException("Attribute id " + id + " does not exists");
}
if (attr.getProduct().getMerchantStore().getId().intValue() != store.getId().intValue()) {
throw new ConversionException("Attribute id " + id + " invalid for this store");
}
orderProductAttribute.setProductAttributeIsFree(attr.getProductAttributeIsFree());
orderProductAttribute.setProductAttributeName(attr.getProductOption().getDescriptionsSettoList().get(0).getName());
orderProductAttribute.setProductAttributeValueName(attr.getProductOptionValue().getDescriptionsSettoList().get(0).getName());
orderProductAttribute.setProductAttributePrice(attr.getProductAttributePrice());
orderProductAttribute.setProductAttributeWeight(attr.getProductAttributeWeight());
orderProductAttribute.setProductOptionId(attr.getProductOption().getId());
orderProductAttribute.setProductOptionValueId(attr.getProductOptionValue().getId());
attributes.add(orderProductAttribute);
}
target.setOrderAttributes(attributes);
}
} catch (Exception e) {
throw new ConversionException(e);
}
return target;
}
Aggregations