Subversion Repositories SmartDukaan

Rev

Rev 3125 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.support.controllers;

import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserCommunication;
import in.shop2020.model.v1.user.UserCommunicationException;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.model.v1.user.UserContextService.Client;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.support.utils.ReportsUtils;
import in.shop2020.thrift.clients.PaymentClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@InterceptorRefs({
    @InterceptorRef("defaultStack"),
    @InterceptorRef("login")
})
@Results({
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
})
public class UserOrdersController implements ServletRequestAware, ServletResponseAware, ServletContextAware {

    private static Logger logger = LoggerFactory.getLogger(UserOrdersController.class);
    
    private HttpServletRequest request;
    private HttpSession session;
    private HttpServletResponse response;
    private ServletContext context;

        //private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                
        private String errorMsg = "";
        
        public String index()   {
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath())) {
            return "authfail";
        }
                return "report";
        }
        
        // Handles the POST request (Form Submission)
        public String create(){
                try     {
                        //Formatting Form input parameters
                        String email = request.getParameter("email");
                        String orderid = request.getParameter("orderid");

                        TransactionClient transactionServiceClient = new TransactionClient();
                        in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
                        
                        UserClient userContextServiceClient = new UserClient();
                        Client userClient = userContextServiceClient.getClient();
                        
                        PaymentClient paymentServiceClient = new PaymentClient();
                        in.shop2020.payments.PaymentService.Client paymentClient = paymentServiceClient.getClient();

                        User user = null;
                        if (email != null && !email.isEmpty()) {
                                user = userClient.getUserByEmail(email);
                                if(user.getUserId() == -1){
                                    errorMsg = "No user for this id.";
                                        return "report";
                                }
                        } else {
                                try {
                                    user = userClient.getUserById(transactionClient.getOrder(Long.parseLong(orderid)).getCustomer_id());
                                } catch (NumberFormatException e)       {
                                    logger.error("Error parsing order id", e);
                                        errorMsg = "Order Id should be a number.";
                                        return "report";
                                }
                        }
                        
                        if (user == null) {
                                errorMsg = "Could not find user.";
                                return "report";
                        }

                        //Retrieving all user communications
                        List<UserCommunication> userCommunications = userClient.getUserCommunicationByUser(user.getUserId());
                        
                        //Retrieving all the transactions
                        List <Transaction> transactions = transactionClient.getTransactionsForCustomer(user.getUserId(), 0, (new Date()).getTime(), null);
                        Collections.reverse(transactions);

                        //Retrieving all the payments 
                        List <Payment> payments = paymentClient.getPaymentsForUser(user.getUserId(), 0,
                                        (new Date()).getTime(), null, 0);
                        
                        Map<Long, Payment> txnIdToPaymentMap = new HashMap<Long, Payment>();
                        for(Payment payment : payments) {
                                txnIdToPaymentMap.put(payment.getMerchantTxnId(), payment);
                        }
                        
                        // Preparing XLS file for output
                        response.setContentType("application/vnd.ms-excel");
                        
                        response.setHeader("Content-disposition", "inline; filename=user-orders" + ".xls");
                        
                        ServletOutputStream sos;
                        try {
                                ByteArrayOutputStream baos = getSpreadSheetData(user,
                                                transactions, txnIdToPaymentMap, userCommunications, userClient);
                                sos = response.getOutputStream();
                                baos.writeTo(sos);
                                sos.flush();
                        } catch (IOException e) {
                                errorMsg = "Failed to write to response.";
                                logger.error("Error streaming the user orders report", e);
                        }

                }  catch (TransactionServiceException e)        {
                        errorMsg = e.getMessage();
                        logger.error("Error retrieving info from transaction service", e);
                } catch (UserContextException e) {
                    errorMsg = e.getMessage();
                    logger.error("Error retrieving info from user service", e);
        } catch (PaymentException e) {
            errorMsg = e.getMessage();
            logger.error("Error retrieving info from payment service", e);
        } catch (UserCommunicationException e) {
            errorMsg = e.getMessage();
            logger.error("Error retrieving user communication from user service", e);
        } catch (TException e) {
            errorMsg = e.getMessage();
            logger.error("Error retrieving info from user, payment or transaction service", e);
        } catch (Exception e) {
            errorMsg = "Error establishing connection to one of the services";
            logger.error("Error establishing connection from user, payment or transaction service", e);
        }
                return "report";
        }
        
        // Prepares the XLS worksheet object and fills in the data with proper formatting
        private ByteArrayOutputStream getSpreadSheetData(User user,
                        List<Transaction> transactions,
                        Map<Long, Payment> txnIdToPaymentMap,
                        List<UserCommunication> userCommunications,
                        Client userClient) 
        {
            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"));
            
            createUserSheet(user, userCommunications, wb, style, dateCellStyle);
            createTransactionSheet(transactions, txnIdToPaymentMap, wb, style, dateCellStyle);
                        
                // Write the workbook to the output stream
                try {
                        wb.write(baosXLS);
                        baosXLS.close();
                } catch (IOException e) {
                        logger.error("Error streaming user order report", e);
                }               
                return baosXLS;
        }

        private void createTransactionSheet(List<Transaction> transactions, Map<Long, Payment> txnIdToPaymentMap, Workbook wb, CellStyle style, CellStyle dateCellStyle) {
                // TRANSACTION SHEET
            Sheet transactionSheet = wb.createSheet("Transactions and Payments");
            short transactionSerialNo = 0;

            Row orderTitleRow = transactionSheet.createRow(transactionSerialNo ++);
            Cell orderTitleCell = orderTitleRow.createCell(0);
            orderTitleCell.setCellValue("User Transactions and Payments");
            orderTitleCell.setCellStyle(style);
            
            transactionSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
            
            transactionSheet.createRow(transactionSerialNo ++);
            
            Row orderHeaderRow = transactionSheet.createRow(transactionSerialNo ++);
            orderHeaderRow.createCell(0).setCellValue("Transaction Id");
            orderHeaderRow.createCell(1).setCellValue("Transaction Date");
            orderHeaderRow.createCell(2).setCellValue("Transaction Status");
            orderHeaderRow.createCell(3).setCellValue("Order Id");
            orderHeaderRow.createCell(4).setCellValue("Billing Number");
            orderHeaderRow.createCell(5).setCellValue("Billing Date");
            orderHeaderRow.createCell(6).setCellValue("Order Status");
            
            orderHeaderRow.createCell(7).setCellValue("Brand");
            orderHeaderRow.createCell(8).setCellValue("Model Name");
            orderHeaderRow.createCell(9).setCellValue("Model Number");
            orderHeaderRow.createCell(10).setCellValue("Color");
            orderHeaderRow.createCell(11).setCellValue("Quantity");
            orderHeaderRow.createCell(12).setCellValue("Unit Price");
            orderHeaderRow.createCell(13).setCellValue("Total Price");
            
            orderHeaderRow.createCell(14).setCellValue("User Id");
            orderHeaderRow.createCell(15).setCellValue("Name");
            orderHeaderRow.createCell(16).setCellValue("Address1");
            orderHeaderRow.createCell(17).setCellValue("Address2");
            orderHeaderRow.createCell(18).setCellValue("City");
            orderHeaderRow.createCell(19).setCellValue("State");
            orderHeaderRow.createCell(20).setCellValue("Pin Code");
            orderHeaderRow.createCell(21).setCellValue("Mobile Number");
            orderHeaderRow.createCell(22).setCellValue("email");
            
            orderHeaderRow.createCell(23).setCellValue("Airway Bill No.");
            orderHeaderRow.createCell(24).setCellValue("Billed By");
            orderHeaderRow.createCell(25).setCellValue("Receiver");
            orderHeaderRow.createCell(26).setCellValue("Tracking Id");
            orderHeaderRow.createCell(27).setCellValue("Accepted Timestamp");
            orderHeaderRow.createCell(28).setCellValue("Delivery Timestamp");
            orderHeaderRow.createCell(29).setCellValue("Expected Delivery Time");
            
            orderHeaderRow.createCell(30).setCellValue("Payment Id");
            orderHeaderRow.createCell(31).setCellValue("Payment Status");
            orderHeaderRow.createCell(32).setCellValue("Gateway Payment Id");
            orderHeaderRow.createCell(33).setCellValue("Gateway Transaction Date");
            orderHeaderRow.createCell(34).setCellValue("Gateway Txn Id");
            orderHeaderRow.createCell(35).setCellValue("Gateway Txn Status");
            orderHeaderRow.createCell(36).setCellValue("Reference Code");
            orderHeaderRow.createCell(37).setCellValue("Gateway Id");
            orderHeaderRow.createCell(38).setCellValue("Amount");
            orderHeaderRow.createCell(39).setCellValue("Description");
            orderHeaderRow.createCell(40).setCellValue("Auth Code");
            orderHeaderRow.createCell(41).setCellValue("Error Code");

            for (int i=0; i<42 ;i++) {
            orderHeaderRow.getCell(i).setCellStyle(style);
        }
            
            for(Transaction transaction : transactions) {
                List<Order> orders = transaction.getOrders();
                Date transactionDate = new Date(transaction.getCreatedOn());
                long transactionId = transaction.getId();
                String transactionStatus = transaction.getStatusDescription();
                for(Order order : orders)       {
                        transactionSerialNo ++;
                        Row contentRow = transactionSheet.createRow(transactionSerialNo);
                            LineItem lineItem = order.getLineitems().get(0);
                            Payment payment = txnIdToPaymentMap.get(transactionId);
                            
                            contentRow.createCell(0).setCellValue(transactionId);
                            contentRow.createCell(1).setCellValue(transactionDate);
                            contentRow.getCell(1).setCellStyle(dateCellStyle);
                            contentRow.createCell(2).setCellValue(transactionStatus);
                            contentRow.createCell(3).setCellValue(order.getId());
                            contentRow.createCell(4).setCellValue(order.getInvoice_number());
                            contentRow.createCell(5).setCellValue(new Date(order.getBilling_timestamp()));
                            contentRow.getCell(5).setCellStyle(dateCellStyle);
                            contentRow.createCell(6).setCellValue(order.getStatusDescription());
                            
                            contentRow.createCell(7).setCellValue(getValueForEmptyString(lineItem.getBrand()));
                            contentRow.createCell(8).setCellValue(getValueForEmptyString(lineItem.getModel_name()));
                            contentRow.createCell(9).setCellValue(getValueForEmptyString(lineItem.getModel_number()));
                            contentRow.createCell(10).setCellValue(getValueForEmptyString(lineItem.getColor()));
                            contentRow.createCell(11).setCellValue(lineItem.getQuantity());
                            contentRow.createCell(12).setCellValue(lineItem.getUnit_price());
                            contentRow.createCell(13).setCellValue(lineItem.getTotal_price());
                            
                            contentRow.createCell(14).setCellValue(order.getCustomer_id());
                            contentRow.createCell(15).setCellValue(order.getCustomer_name());
                            contentRow.createCell(16).setCellValue(order.getCustomer_address1());
                            contentRow.createCell(17).setCellValue(order.getCustomer_address2());
                            contentRow.createCell(18).setCellValue(order.getCustomer_city());
                            contentRow.createCell(19).setCellValue(order.getCustomer_state());
                            contentRow.createCell(20).setCellValue(order.getCustomer_pincode());
                            contentRow.createCell(21).setCellValue(order.getCustomer_mobilenumber());
                            contentRow.createCell(22).setCellValue(order.getCustomer_email());
                            
                            contentRow.createCell(23).setCellValue(order.getAirwaybill_no());
                            contentRow.createCell(24).setCellValue(order.getBilled_by());
                            contentRow.createCell(25).setCellValue(order.getReceiver());
                            contentRow.createCell(26).setCellValue(order.getTracking_id());
                            contentRow.createCell(27).setCellValue(new Date(order.getAccepted_timestamp()));
                            contentRow.getCell(27).setCellStyle(dateCellStyle);
                            contentRow.createCell(28).setCellValue(new Date(order.getDelivery_timestamp()));
                            contentRow.getCell(28).setCellStyle(dateCellStyle);
                            contentRow.createCell(29).setCellValue(new Date(order.getExpected_delivery_time()));
                            contentRow.getCell(29).setCellStyle(dateCellStyle);
                            
                                if (payment != null) {
                                        contentRow.createCell(30).setCellValue(payment.getPaymentId());
                                        contentRow.createCell(31).setCellValue(payment.getStatus().name());
                                        contentRow.createCell(32).setCellValue(payment.getGatewayPaymentId());
                                        contentRow.createCell(33).setCellValue(payment.getGatewayTxnDate());
                                        contentRow.createCell(34).setCellValue(payment.getGatewayTxnId());
                                        contentRow.createCell(35).setCellValue(payment.getGatewayTxnStatus());
                                        contentRow.createCell(36).setCellValue(payment.getReferenceCode());
                                        contentRow.createCell(37).setCellValue(payment.getGatewayId());
                                        contentRow.createCell(38).setCellValue(payment.getAmount());
                                        contentRow.createCell(39).setCellValue(payment.getDescription());
                                        contentRow.createCell(40).setCellValue(payment.getAuthCode());
                                        contentRow.createCell(41).setCellValue(payment.getErrorCode());
                                }
                    }
            }
        }

        private String getValueForEmptyString(String s){
                if(s==null || s.equals(""))
                        return "-";
                else
                        return s; 
        }
        
        private void createUserSheet(User user, List<UserCommunication> userCommunications, Workbook wb, CellStyle style, CellStyle dateCellStyle) {
            Sheet userSheet = wb.createSheet("User");
            short userSerialNo = 0;
        // Create the header row and put all the titles in it. Rows are 0 based.
            
            Row titleRow = userSheet.createRow(userSerialNo++);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue("User Details");
            titleCell.setCellStyle(style);
            
            userSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
            
            Row userHeaderRow = userSheet.createRow(userSerialNo++);
            userHeaderRow.createCell(0).setCellValue("Name");
            userHeaderRow.createCell(1).setCellValue("Email");
            userHeaderRow.createCell(2).setCellValue("Communication Email");
            userHeaderRow.createCell(3).setCellValue("Date Of Birth");
            userHeaderRow.createCell(4).setCellValue("Mobile Number");
            userHeaderRow.createCell(5).setCellValue("Sex");
            userHeaderRow.createCell(6).setCellValue("User Id");
            for (int i=0; i<7 ;i++) {
            userHeaderRow.getCell(i).setCellStyle(style);
        }

            Row userContentRow = userSheet.createRow(userSerialNo++);
            
        userContentRow.createCell(0).setCellValue(user.getName());
        userContentRow.createCell(1).setCellValue(user.getEmail());
        userContentRow.createCell(2).setCellValue(user.getCommunicationEmail());
        userContentRow.createCell(3).setCellValue(user.getDateOfBirth());
        userContentRow.createCell(4).setCellValue(user.getMobileNumber());
        userContentRow.createCell(5).setCellValue(user.getSex().name());
        userContentRow.createCell(6).setCellValue(user.getUserId());
        
        userSerialNo+=2;
                Row addressHeaderRow = userSheet.createRow(userSerialNo++);
            addressHeaderRow.createCell(0).setCellValue("Name");
            addressHeaderRow.createCell(1).setCellValue("Line1");
            addressHeaderRow.createCell(2).setCellValue("Line2");
            addressHeaderRow.createCell(3).setCellValue("City");
            addressHeaderRow.createCell(4).setCellValue("State");
            addressHeaderRow.createCell(5).setCellValue("Pincode");
            addressHeaderRow.createCell(6).setCellValue("Phone");
            for (int i=0; i<7 ;i++) {
            addressHeaderRow.getCell(i).setCellStyle(style);
        }

                List<Address> user_addresses = user.getAddresses();
                if (user_addresses != null && !user_addresses.isEmpty()) {
                        for (Address address : user.getAddresses()) {
                                if (user.getDefaultAddressId() == address.getId()) {
                                        userContentRow = userSheet.createRow(userSerialNo);
                                        userSheet.addMergedRegion(new CellRangeAddress(
                                                        userSerialNo, userSerialNo, 0, 6));
                                        userContentRow.createCell(0)
                                                        .setCellValue("Primary Address");
                                        userContentRow.getCell(0).setCellStyle(style);

                                        userSerialNo++;
                                        userContentRow = userSheet.createRow(userSerialNo);
                                        userContentRow.createCell(0)
                                                        .setCellValue(address.getName());
                                        userContentRow.createCell(1).setCellValue(
                                                        address.getLine1());
                                        userContentRow.createCell(2).setCellValue(
                                                        address.getLine2());
                                        userContentRow.createCell(3)
                                                        .setCellValue(address.getCity());
                                        userContentRow.createCell(4).setCellValue(
                                                        address.getState());
                                        userContentRow.createCell(5).setCellValue(address.getPin());
                                        userContentRow.createCell(6).setCellValue(
                                                        address.getPhone());
                                        userSerialNo += 3;
                                }
                        }

                        userContentRow = userSheet.createRow(userSerialNo);
                        userSheet.addMergedRegion(new CellRangeAddress(userSerialNo,
                                        userSerialNo, 0, 6));
                        userContentRow.createCell(0).setCellValue("Other Addresses");
                        userContentRow.getCell(0).setCellStyle(style);

                        for (Address address : user.getAddresses()) {
                                if (user.getDefaultAddressId() != address.getId()) {
                                        userSerialNo++;
                                        userContentRow = userSheet.createRow(userSerialNo);
                                        userContentRow.createCell(0)
                                                        .setCellValue(address.getName());
                                        userContentRow.createCell(1).setCellValue(
                                                        address.getLine1());
                                        userContentRow.createCell(2).setCellValue(
                                                        address.getLine2());
                                        userContentRow.createCell(3)
                                                        .setCellValue(address.getCity());
                                        userContentRow.createCell(4).setCellValue(
                                                        address.getState());
                                        userContentRow.createCell(5).setCellValue(address.getPin());
                                        userContentRow.createCell(6).setCellValue(
                                                        address.getPhone());
                                }
                        }
                        
                        
                        userSerialNo+=2;
                        userContentRow = userSheet.createRow(userSerialNo);
                        userSheet.addMergedRegion(new CellRangeAddress(userSerialNo,
                                        userSerialNo, 0, 6));
                        userContentRow.createCell(0).setCellValue("User Communication");
                        userContentRow.getCell(0).setCellStyle(style);
                        userSerialNo++;
                        Row commHeaderRow = userSheet.createRow(userSerialNo);
                    commHeaderRow.createCell(0).setCellValue("Order Id");
                    commHeaderRow.createCell(1).setCellValue("Communication Type");
                    commHeaderRow.createCell(2).setCellValue("AirwayBill No");
                    commHeaderRow.createCell(3).setCellValue("TimeStamp");
                    commHeaderRow.createCell(4).setCellValue("Product Name");
                    commHeaderRow.createCell(5).setCellValue("Reply To");
                    commHeaderRow.createCell(6).setCellValue("Subject");
                    commHeaderRow.createCell(7).setCellValue("Message");
                    for (int i=0; i<8 ;i++) {
                    commHeaderRow.getCell(i).setCellStyle(style);
                }
                    
                        for( UserCommunication userComm : userCommunications) {
                                userSerialNo++;
                                userContentRow = userSheet.createRow(userSerialNo);
                                userContentRow.createCell(0).setCellValue(userComm.getOrderId());
                                if (userComm.getCommunicationType() != null) {
                                        userContentRow.createCell(1).setCellValue(userComm.getCommunicationType().name());
                                }
                                userContentRow.createCell(2).setCellValue(userComm.getAirwaybillNo());
                                userContentRow.createCell(3).setCellValue(new Date(userComm.getCommunication_timestamp()));
                                userContentRow.getCell(3).setCellStyle(dateCellStyle);
                                userContentRow.createCell(4).setCellValue(userComm.getProductName());
                                userContentRow.createCell(5).setCellValue(userComm.getReplyTo());
                                userContentRow.createCell(6).setCellValue(userComm.getSubject());
                                userContentRow.createCell(7).setCellValue(userComm.getMessage());
                        }
                }
        }
        
        public String getErrorMsg() {
                return errorMsg;
        }
        
    @Override
    public void setServletRequest(HttpServletRequest req) {
        this.request = req;
        this.session = req.getSession();        
    }

    @Override
    public void setServletResponse(HttpServletResponse res) {
        this.response = res;
    }
    
    @Override
    public void setServletContext(ServletContext context) {
        this.context = context;
    }

    public String getServletContextPath() {
        return context.getContextPath();
    }
}