Subversion Repositories SmartDukaan

Rev

Rev 5326 | 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.ShoppingCartException;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserContextService.Client;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;

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;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 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 static Logger logger = LoggerFactory.getLogger(CartReportController.class);
    
        private HttpServletResponse response;
        
        private String errorMsg = "";
        
        @Override
        public void setServletResponse(HttpServletResponse res) {
                this.response = res;
        }
        
        public void index(){
                try     {
                        TransactionClient transactionServiceClient = new TransactionClient();
                        in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
                        
                        UserClient userContextServiceClient = new UserClient();
                        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 checkout
                                        if (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 output
                        response.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.";
                                logger.error("Unable to stream the cart report", e);
                        }

                } catch (ParseException e)      {
                    logger.error("Unable to parse the start or end date", e);
                    errorMsg = e.getMessage();
                } catch (TransactionServiceException e) {
                    logger.error("Error while getting transaction info", e);
                        errorMsg = e.getMessage();
                } catch (ShoppingCartException e) {
                    logger.error("Error while getting cart date", e);
            errorMsg = e.getMessage();
        } catch (TException e) {
            logger.error("Unable to get order or cart data", e);
            errorMsg = e.getMessage();
        } catch (Exception e)   {
            logger.error("Unexpected exception", e);
            errorMsg = e.getMessage();
        }
        }
        
        // Prepares the XLS worksheet object and fills in the data with proper formatting
    private 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 stream
                try {
                        wb.write(baosXLS);
                        baosXLS.close();
                } catch (IOException e) {
                        logger.error("Unable to convert the cart report to byte array", e);
                }               
                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);
            CatalogClient catalogServiceClient = new CatalogClient();
        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
        
                // CART SHEET
            Sheet 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 characters
            for(Cart cart : orderedCarts)       {
                cartSerialNo ++;
                Row contentRow = cartSheet.createRow(cartSerialNo);
                Transaction transaction = cartToTransactionMap.get(cart.getId());
                User user = userClient.getUserByCartId(cart.getId());
                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 Height

            contentRow.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;
        }
}