Subversion Repositories SmartDukaan

Rev

Rev 1660 | Rev 2090 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.support.services;

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.PaymentException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.PaymentServiceClient;
import in.shop2020.thrift.clients.TransactionServiceClient;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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 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.DataFormat;
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.thrift.TException;

public class PaymentDetailsGenerator {
    TransactionServiceClient tsc;
    in.shop2020.model.v1.order.TransactionService.Client tClient;

    PaymentServiceClient psc;
    in.shop2020.payments.PaymentService.Client pClient;

    public PaymentDetailsGenerator() {
        try {
            tsc = new TransactionServiceClient();
            tClient = tsc.getClient();
            psc = new PaymentServiceClient();
            pClient = psc.getClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is used in PaymentDetailsController.
     * If any pending or failed payment exists between given date range, it returns ByteArrayOutputStream,
     * otherwise it returns null.
     * @param startDate
     * @param endDate
     * @param status 0 --> user input: Successful  1: Failed & pending
     * @return
     */
    public ByteArrayOutputStream generatePaymentDetailsReport(Date startDate, Date endDate, int status) {

        // Retrieving all the payments between start and end dates with status
        // as FAILED or INIT and for gateway Id = 1 (HDFC)
        List<Payment> payments = null;
        List<Payment> pendingPayments = null;
        try {
            if(status == 0) {
                payments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.SUCCESS, 1);
            } else {
                payments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.FAILED, 1);
                pendingPayments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.INIT, 1);
                if (payments != null && pendingPayments != null) {
                    payments.addAll(pendingPayments);
                } else if (pendingPayments != null){
                    payments = pendingPayments;
                }
            }
        } catch (PaymentException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        }
        if (payments == null || payments.isEmpty()) {
            return null;
        }

        // Preparing XLS file for output
        return getSpreadSheetData(payments);

    }

    // Prepares the XLS worksheet object and fills in the data with proper
    // formatting
    private ByteArrayOutputStream getSpreadSheetData(List<Payment> payments) {
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();

        Workbook wb = new HSSFWorkbook();

        Font font = wb.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);

        CellStyle styleWT = wb.createCellStyle();
        styleWT.setWrapText(true);

        DataFormat format = wb.createDataFormat();
        CellStyle styleAmount = wb.createCellStyle();
        styleAmount.setDataFormat(format.getFormat("#,##0.00"));

        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("Address");
        headerRow.getCell(10).setCellStyle(styleWT);
        headerRow.createCell(11).setCellValue("Pincode");
        headerRow.createCell(12).setCellValue("City");
        headerRow.createCell(13).setCellValue("State");
        headerRow.createCell(14).setCellValue("Email");

        headerRow.createCell(15).setCellValue("Order Id");
        headerRow.createCell(16).setCellValue("Order Status");
        headerRow.createCell(17).setCellValue("Order Status Description");

        headerRow.createCell(18).setCellValue("Item Id");
        headerRow.createCell(19).setCellValue("Product Group");
        headerRow.createCell(20).setCellValue("Brand");
        headerRow.createCell(21).setCellValue("Model Name");
        headerRow.createCell(22).setCellValue("Model Number");
        headerRow.createCell(23).setCellValue("Qty");

        int addrColWidth = 35;
        paymentSheet.setColumnWidth(10, 256 * addrColWidth); // set width of address column to 35 characters
        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.getCell(2).setCellStyle(styleAmount);
                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 = tClient.getTransaction(payment.getMerchantTxnId()).getId();
                orders = tClient.getOrdersForTransaction(txnId, payment.getUserId());
                List<LineItem> lineItems;

                String address = "";
                float rowHeight = paymentSheet.getDefaultRowHeightInPoints();
                if (orders == null || orders.isEmpty()) {
                    continue;
                }
                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());
                address = orders.get(0).getCustomer_address1() + ", " + orders.get(0).getCustomer_address2();
                contentRow.createCell(10).setCellValue(address);
                contentRow.getCell(10).setCellStyle(styleWT);
                int maxLength = Math.max(address.length(), paymentSheet.getDefaultColumnWidth());
                contentRow.setHeightInPoints((maxLength / addrColWidth + 1) * rowHeight); // Setting Row Height
                contentRow.createCell(11).setCellValue(orders.get(0).getCustomer_pincode());
                contentRow.createCell(12).setCellValue(orders.get(0).getCustomer_city());
                contentRow.createCell(13).setCellValue(orders.get(0).getCustomer_state());
                contentRow.createCell(14).setCellValue(orders.get(0).getCustomer_email());

                for (Order o : orders) {
                    paymentSerialNo++;
                    contentRow = paymentSheet.createRow(paymentSerialNo);

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

                    lineItems = tClient.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(18).setCellValue(i.getId());
                        contentRow.createCell(19).setCellValue(i.getProductGroup());
                        contentRow.createCell(20).setCellValue(i.getBrand());
                        contentRow.createCell(21).setCellValue(i.getModel_name());
                        contentRow.createCell(22).setCellValue(i.getModel_number());
                        contentRow.createCell(23).setCellValue(i.getQuantity());
                    }
                }
            } catch (TransactionServiceException e) {
                e.printStackTrace();
            } catch (TException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i <= 23; i++) {
            if (i == 10) // Address Column is of fixed size with wrap text style
                continue;
            paymentSheet.autoSizeColumn(i);
        }

        // Write the workbook to the output stream
        try {
            wb.write(baosXLS);
            baosXLS.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baosXLS;
    }

    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        Date startDate = null, endDate = null;
        try {
            startDate = df.parse("01/01/2011");
            endDate = df.parse("04/30/2011");
            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            cal.add(Calendar.DATE, 1);
            endDate.setTime(cal.getTimeInMillis());
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
        PaymentDetailsGenerator pdg = new PaymentDetailsGenerator();
        try {
            String userHome = System.getProperty("user.home");
            FileOutputStream f = new FileOutputStream(userHome + "/payment-details-report.xls");
            ByteArrayOutputStream baosXLS = pdg.generatePaymentDetailsReport(startDate, endDate, 1);
            baosXLS.writeTo(f);
            f.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Successfully generated the payment details report");
    }
}