Rev 2042 | Rev 3213 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.support.controllers;import in.shop2020.model.v1.catalog.Item;import in.shop2020.model.v1.order.Transaction;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.order.TransactionStatus;import in.shop2020.model.v1.user.Address;import in.shop2020.model.v1.user.Cart;import in.shop2020.model.v1.user.Line;import in.shop2020.model.v1.user.User;import in.shop2020.model.v1.user.UserContextService.Client;import in.shop2020.thrift.clients.CatalogServiceClient;import in.shop2020.thrift.clients.TransactionServiceClient;import in.shop2020.thrift.clients.UserContextServiceClient;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.text.ParseException;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.struts2.interceptor.ServletResponseAware;/*** Provides reports about carts created in last 15 days. Also provides data* about transactions created for a cart.** @author Ankur Singhal**/public class CartReportController implements ServletResponseAware{private HttpServletResponse response;private String errorMsg = "";@Overridepublic void setServletResponse(HttpServletResponse res) {this.response = res;}public void index(){try {TransactionServiceClient transactionServiceClient = new TransactionServiceClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();UserContextServiceClient userContextServiceClient = new UserContextServiceClient();Client userClient = userContextServiceClient.getClient();// get carts created in last 15 days.Date now = new Date();Date from = new Date();Calendar c = Calendar.getInstance();c.setTime(from);c.add(Calendar.DATE, -15);from.setTime(c.getTime().getTime());List<Cart> carts = userClient.getCartsByTime(from.getTime(), now.getTime(), null);System.out.println("Total carts : " + carts.size());Map<Long, Transaction> cartToTransactionMap = new HashMap<Long, Transaction>();for (Iterator<Cart> itr = carts.iterator(); itr.hasNext();) {Cart cart = itr.next();if (cart.getCheckedOutOn() == 0) {itr.remove();}else {List<Transaction> cartTransactions = transactionClient.getTransactionsForShoppingCartId(cart.getId());long cartTime = cart.getCheckedOutOn();for (Transaction t : cartTransactions) {long tTime = t.getCreatedOn();if (tTime > cartTime && ((tTime - cartTime)/(60 * 1000) < 30)) { // transaction with in 30 min of checkoutif (t.getTransactionStatus() == TransactionStatus.IN_PROCESS || t.getTransactionStatus() == TransactionStatus.FAILED) {itr.remove();}else {if (cartToTransactionMap.containsKey(cart.getId())) {if (cartToTransactionMap.get(cart.getId()).getCreatedOn() > t.getCreatedOn()){cartToTransactionMap.put(cart.getId(),t);}}else {cartToTransactionMap.put(cart.getId(),t);}}}}}}System.out.println("Checked out carts with unsuccessful payment : " + carts.size());// Preparing XLS file for outputresponse.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "inline; filename=cart-report" + ".xls");ServletOutputStream sos;try {ByteArrayOutputStream baos = getSpreadSheetData(carts, cartToTransactionMap, userClient);sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {errorMsg = "Failed to write to response.";e.printStackTrace();}} catch (ParseException e) {errorMsg = e.getMessage();e.printStackTrace();} catch (TransactionServiceException e) {errorMsg = e.getMessage();e.printStackTrace();} catch (Exception e) {errorMsg = e.getMessage();e.printStackTrace();}}// Prepares the XLS worksheet object and fills in the data with proper formattingprivate ByteArrayOutputStream getSpreadSheetData(List<Cart> carts,Map<Long, Transaction> cartToTransactionMap, Client userClient)throws Exception{ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();Workbook wb = new HSSFWorkbook();Font font = wb.createFont();font.setBoldweight(Font.BOLDWEIGHT_BOLD);CellStyle style = wb.createCellStyle();style.setFont(font);CreationHelper createHelper = wb.getCreationHelper();CellStyle dateCellStyle = wb.createCellStyle();dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("DD/MM/YYYY HH:MM"));createCartSheet(carts, cartToTransactionMap, userClient, wb, style, dateCellStyle);// Write the workbook to the output streamtry {wb.write(baosXLS);baosXLS.close();} catch (IOException e) {e.printStackTrace();}return baosXLS;}private void createCartSheet(List<Cart> carts,Map<Long, Transaction> cartToTransactionMap, Client userClient,Workbook wb, CellStyle style, CellStyle dateCellStyle)throws Exception{CellStyle styleWT = wb.createCellStyle();styleWT.setWrapText(true);CatalogServiceClient catalogServiceClient = new CatalogServiceClient();in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = catalogServiceClient.getClient();// CART SHEETSheet cartSheet = wb.createSheet("Cart");short cartSerialNo = 0;List<Cart> noAddressCarts = new LinkedList<Cart>();List<Cart> noPaymentCarts = new LinkedList<Cart>();List<Cart> otherCarts = new LinkedList<Cart>();for (Cart cart : carts) {if (cart.getAddressId() == 0) {noAddressCarts.add(cart);}else if (!cartToTransactionMap.containsKey(cart.getId())) {noPaymentCarts.add(cart);}else {otherCarts.add(cart);}}List<Cart> orderedCarts = new LinkedList<Cart>();orderedCarts.addAll(noAddressCarts);orderedCarts.addAll(noPaymentCarts);orderedCarts.addAll(otherCarts);Row cartTitleRow = cartSheet.createRow(cartSerialNo ++);Cell cartTitleCell = cartTitleRow.createCell(0);cartTitleCell.setCellValue("User Cart Conversions");cartTitleCell.setCellStyle(style);cartSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));cartSheet.createRow(cartSerialNo ++);Row cartHeaderRow = cartSheet.createRow(cartSerialNo ++);cartHeaderRow.createCell(0).setCellValue("Cart Id");cartHeaderRow.createCell(1).setCellValue("Cart Address");cartHeaderRow.getCell(1).setCellStyle(styleWT);cartHeaderRow.createCell(2).setCellValue("Checked out date");cartHeaderRow.createCell(3).setCellValue("Transaction Date");cartHeaderRow.createCell(4).setCellValue("Transaction Status");cartHeaderRow.createCell(5).setCellValue("Created On");cartHeaderRow.createCell(6).setCellValue("Item size");cartHeaderRow.createCell(7).setCellValue("Updated On");cartHeaderRow.createCell(8).setCellValue("Cart Status");cartHeaderRow.createCell(9).setCellValue("Cart Items");cartHeaderRow.createCell(10).setCellValue("User Id");cartHeaderRow.createCell(11).setCellValue("Comm Email");cartHeaderRow.createCell(12).setCellValue("Date Of Birth");cartHeaderRow.createCell(13).setCellValue("Mobile");cartHeaderRow.createCell(14).setCellValue("Name");for (int i=0; i<15 ;i++) {cartHeaderRow.getCell(i).setCellStyle(style);}int addrColWidth = 35;cartSheet.setColumnWidth(1, 256 * addrColWidth); // set width of address column to 35 charactersfor(Cart cart : orderedCarts) {cartSerialNo ++;Row contentRow = cartSheet.createRow(cartSerialNo);Transaction transaction = cartToTransactionMap.get(cart.getId());User user = userClient.getUserById(cart.getUserId());List<Line> cartLines = cart.getLines();String cartItems = "";for (Line line : cartLines) {Item item = catalogClient.getItem(line.getItemId());if (!cartItems.isEmpty()) {cartItems += ", ";}cartItems += item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + "(" + line.getQuantity()+ ")";}String cartAddress = "-";if (cart.getAddressId() != 0) {Address address = userClient.getAddressById(cart.getAddressId());cartAddress = address.getName() + ", " + address.getLine1() + ", " + address.getLine2() + ", " + address.getCity()+ ", " + address.getState() + "-" + address.getPin() + ", " + address.getPhone();}contentRow.createCell(0).setCellValue(cart.getId());contentRow.createCell(1).setCellValue(cartAddress);contentRow.getCell(1).setCellStyle(styleWT);float rowHeight = cartSheet.getDefaultRowHeightInPoints();int maxLength = Math.max(cartAddress.length(), cartSheet.getDefaultColumnWidth());contentRow.setHeightInPoints((maxLength / addrColWidth + 1) * rowHeight); // Setting Row HeightcontentRow.createCell(2).setCellValue(new Date(cart.getCheckedOutOn()));contentRow.getCell(2).setCellStyle(dateCellStyle);if (transaction != null) {contentRow.createCell(3).setCellValue(new Date(transaction.getCreatedOn()));contentRow.getCell(3).setCellStyle(dateCellStyle);contentRow.createCell(4).setCellValue(transaction.getStatusDescription());}contentRow.createCell(5).setCellValue(new Date(cart.getCreatedOn()));contentRow.getCell(5).setCellStyle(dateCellStyle);contentRow.createCell(6).setCellValue(cart.getLinesSize());contentRow.createCell(7).setCellValue(new Date(cart.getUpdatedOn()));contentRow.getCell(7).setCellStyle(dateCellStyle);contentRow.createCell(8).setCellValue(cart.getStatus().name());contentRow.createCell(9).setCellValue(cartItems);contentRow.createCell(10).setCellValue(user.getEmail());contentRow.createCell(11).setCellValue(user.getCommunicationEmail());contentRow.createCell(12).setCellValue(user.getDateOfBirth());contentRow.createCell(13).setCellValue(user.getMobileNumber());contentRow.createCell(14).setCellValue(user.getName());}for (int i = 0; i <= 14; i++) {if (i != 1) {cartSheet.autoSizeColumn(i);}}}public String getErrorMsg() {return errorMsg;}}