Subversion Repositories SmartDukaan

Rev

Rev 1631 | 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.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.PaymentServiceClient;
import in.shop2020.thrift.clients.TransactionServiceClient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
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.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.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.thrift.TException;

public class PaymentDetailsController implements ServletResponseAware, ServletRequestAware{

        private HttpServletRequest request;
        private HttpServletResponse response;
        
        private String errorMsg = "";
        
        public PaymentDetailsController(){
                
        }
        
        @Override
        public void setServletRequest(HttpServletRequest req) {
                this.request = req;
        }

        @Override
        public void setServletResponse(HttpServletResponse res) {
                this.response = res;
        }
        
        public String index()   {
                return "report";
        }
        
        public String show(){
                return "report";
        }
        
        // Handles the POST request (Form Submission)
        public String create(){
                try     {
                        //Formatting Form input parameters
                        String startDateStr = request.getParameter("startDate");
                        String endDateStr = request.getParameter("endDate");
                        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
                        Date startDate = null, endDate = null;
                        TransactionServiceClient tsc = new TransactionServiceClient();
                        in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                        
                        PaymentServiceClient psc = new PaymentServiceClient();
                        in.shop2020.payments.PaymentService.Client pClient = psc.getClient();
                        
                        try {
                                startDate = df.parse(startDateStr);
                                endDate = df.parse(endDateStr);
                                Calendar cal = Calendar.getInstance();
                                cal.setTime(endDate);
                                cal.add(Calendar.DATE, 1);
                                endDate.setTime(cal.getTimeInMillis());
                                errorMsg = "Date Range: " + startDate + " to " + endDate;
                        } catch(ParseException pe) {
                                errorMsg = "Please enter start and end dates in format MM/dd/yyyy";
                                return "report";
                        }
                        
                        // Retrieving all the payments between start and end dates with status as failed and for gateway Id = 1 (HDFC)
                        List<Payment> payments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.FAILED, 1);
                        if(payments == null || payments.isEmpty()) {
                                errorMsg = "There is no FAILED payment within given date range";
                                return "report";
                        }

                        // Preparing XLS file for output
                        response.setContentType("application/vnd.ms-excel");
                        response.setHeader("Content-disposition", "inline; filename=payments-report" + ".xls");
                        ServletOutputStream sos;
                        try {
                                ByteArrayOutputStream baos = getSpreadSheetData(payments, tclient);
                                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();
                }
                return "report";
        }
        
        // Prepares the XLS worksheet object and fills in the data with proper formatting
        private ByteArrayOutputStream getSpreadSheetData(List<Payment> payments, in.shop2020.model.v1.order.TransactionService.Client tsc)      {
                ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();

            Workbook wb = new HSSFWorkbook();
            
            Font font = wb.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            CellStyle style = wb.createCellStyle();
            style.setFont(font);
            
            Sheet paymentSheet = wb.createSheet("Payment");
            short paymentSerialNo = 0;

            Row titleRow = paymentSheet.createRow(paymentSerialNo ++);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue("Payment Details");
            titleCell.setCellStyle(style);
            
            paymentSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
            
            paymentSheet.createRow(paymentSerialNo ++);
            
            Row headerRow = paymentSheet.createRow(paymentSerialNo ++);
            headerRow.createCell(0).setCellValue("Payment Id");
            headerRow.createCell(1).setCellValue("Txn Id");
            headerRow.createCell(2).setCellValue("Amount");
            headerRow.createCell(3).setCellValue("Payment Status");
            headerRow.createCell(4).setCellValue("Payment Status Description");
            headerRow.createCell(5).setCellValue("Reference Code");
            headerRow.createCell(6).setCellValue("Transaction Time");
            
            headerRow.createCell(7).setCellValue("Customer Id");
            headerRow.createCell(8).setCellValue("Name");
            headerRow.createCell(9).setCellValue("MobileNo");
            headerRow.createCell(10).setCellValue("Pincode");
            headerRow.createCell(11).setCellValue("City");
            headerRow.createCell(12).setCellValue("State");
            headerRow.createCell(13).setCellValue("Email");
            headerRow.createCell(14).setCellValue("Order Id");
            headerRow.createCell(15).setCellValue("Order Status");
            headerRow.createCell(16).setCellValue("Order Status Description");
            
            headerRow.createCell(17).setCellValue("Item Id");
            headerRow.createCell(18).setCellValue("Product Group");
            headerRow.createCell(19).setCellValue("Brand");
            headerRow.createCell(20).setCellValue("Model Name");
            headerRow.createCell(21).setCellValue("Model Number");
            headerRow.createCell(22).setCellValue("Quantity");
            
            List<Order> orders;
                long txnId;
                Row contentRow;
                Calendar calendar = Calendar.getInstance();
                DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
                for(Payment payment : payments) {
                        try {
                                paymentSerialNo++;
                                contentRow = paymentSheet.createRow(paymentSerialNo);
                                contentRow.createCell(0).setCellValue(payment.getPaymentId());
                                contentRow.createCell(1).setCellValue(payment.getMerchantTxnId());
                                contentRow.createCell(2).setCellValue(payment.getAmount());
                                contentRow.createCell(3).setCellValue(payment.getStatus().name());
                                contentRow.createCell(4).setCellValue(payment.getDescription());
                                contentRow.createCell(5).setCellValue(payment.getReferenceCode());
                                calendar.setTimeInMillis(payment.getInitTimestamp());
                                contentRow.createCell(6).setCellValue(formatter.format(calendar.getTime()));

                                txnId = tsc.getTransaction(payment.getMerchantTxnId()).getId();
                                orders = tsc.getOrdersForTransaction(txnId, payment.getUserId());
                                List<LineItem> lineItems;
                                
                                if(orders != null && !orders.isEmpty()) {
                                        contentRow.createCell(7).setCellValue(orders.get(0).getCustomer_id());
                                        contentRow.createCell(8).setCellValue(orders.get(0).getCustomer_name());
                                        contentRow.createCell(9).setCellValue(orders.get(0).getCustomer_mobilenumber());
                                        contentRow.createCell(10).setCellValue(orders.get(0).getCustomer_pincode());
                                        contentRow.createCell(11).setCellValue(orders.get(0).getCustomer_city());
                                        contentRow.createCell(12).setCellValue(orders.get(0).getCustomer_state());
                                        contentRow.createCell(13).setCellValue(orders.get(0).getCustomer_email());              
                                
                                        for(Order o : orders) {
                                                paymentSerialNo++;
                                                contentRow = paymentSheet.createRow(paymentSerialNo);

                                                contentRow.createCell(14).setCellValue(o.getId());
                                                contentRow.createCell(15).setCellValue(o.getStatus().name());
                                                contentRow.createCell(16).setCellValue(o.getStatusDescription());

                                                lineItems = tsc.getLineItemsForOrder(o.getId());
                                                for(LineItem i : lineItems) {
                                                        /*Right now there can be only one line item in an order.
                                                  So putting line item details in the same row as order details. Commenting below 2 lines for this.*/
                                                        //paymentSerialNo++;
                                                        //contentRow = paymentSheet.createRow(paymentSerialNo);

                                                        contentRow.createCell(17).setCellValue(i.getId());
                                                        contentRow.createCell(18).setCellValue(i.getProductGroup());
                                                        contentRow.createCell(19).setCellValue(i.getBrand());
                                                        contentRow.createCell(20).setCellValue(i.getModel_name());
                                                        contentRow.createCell(21).setCellValue(i.getModel_number());
                                                        contentRow.createCell(22).setCellValue(i.getQuantity());
                                                }
                                        }
                                }
                        } catch (TransactionServiceException e) {
                                e.printStackTrace();
                        } catch (TException e) {
                                e.printStackTrace();
                        }
                }
            
                paymentSheet.autoSizeColumn(0);
                paymentSheet.autoSizeColumn(1);
                paymentSheet.autoSizeColumn(2);
                paymentSheet.autoSizeColumn(3);
                paymentSheet.autoSizeColumn(4);
                paymentSheet.autoSizeColumn(5);
                paymentSheet.autoSizeColumn(6);
                paymentSheet.autoSizeColumn(7);
                paymentSheet.autoSizeColumn(8);
                paymentSheet.autoSizeColumn(9);
                paymentSheet.autoSizeColumn(10);
                paymentSheet.autoSizeColumn(11);
                paymentSheet.autoSizeColumn(12);
                paymentSheet.autoSizeColumn(13);
                paymentSheet.autoSizeColumn(14);
                paymentSheet.autoSizeColumn(15);
                paymentSheet.autoSizeColumn(16);
                paymentSheet.autoSizeColumn(17);
                paymentSheet.autoSizeColumn(18);
                paymentSheet.autoSizeColumn(19);
                paymentSheet.autoSizeColumn(20);
                paymentSheet.autoSizeColumn(21);
                paymentSheet.autoSizeColumn(22);
                
                // Write the workbook to the output stream
                try {
                        wb.write(baosXLS);
                        baosXLS.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }               
                return baosXLS;
        }
        
        public String getErrorMsg() {
                return errorMsg;
        }
}