Subversion Repositories SmartDukaan

Rev

Rev 4452 | 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.OrderStatus;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.Constants;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentGateway;
import in.shop2020.payments.PaymentStatus;
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.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.HashMap;
import java.util.List;
import java.util.Map;

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

public class PaymentDetailsGenerator {
    
    private static Logger logger = LoggerFactory.getLogger(PaymentDetailsGenerator.class);
    
    private static final int S_NO = 0, PAYMENT_ID = 1, GATEWAY = 2, PAYMENT_METHOD = 3, TXN_ID = 4, AMOUNT = 5, PAY_STATUS = 6, 
    PAY_STATUS_DESC = 7, TXN_STATUS = 8, REF_CODE = 9, TXN_TIME = 10, CUST_ID = 11, NAME = 12, 
    MOB_NO = 13, ADDR = 14, PINCODE = 15, CITY = 16, STATE = 17, EMAIL = 18, ORDER_ID = 19, ORDER_STATUS = 20, 
    ORDER_STATUS_DESC = 21, ITEM_ID = 22, PROD_GRP = 23, BRAND = 24, MOD_NAME = 25, MOD_NUM = 26, QTY = 27;
    
    TransactionClient tsc;
    in.shop2020.model.v1.order.TransactionService.Client tClient;

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

    UserClient usc;
    in.shop2020.model.v1.user.UserContextService.Client uClient;

    Map<Long, PaymentGateway> gateWays = new HashMap<Long, PaymentGateway>(4);

    public PaymentDetailsGenerator() {
        try {
            tsc = new TransactionClient();
            tClient = tsc.getClient();

            psc = new PaymentClient();
            pClient = psc.getClient();

            usc = new UserClient();
            uClient = usc.getClient();
        } catch (Exception e) {
            logger.error("Error establishing connection to one of txn, payment or user service", e);
        }
    }

    /**
     * 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> authorizedPayments = null;
        List<Payment> pendingPayments = null;
        try {
            if(status == 0) {
                payments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.SUCCESS, 0);
                authorizedPayments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.AUTHORIZED, 0);
                if(payments != null && authorizedPayments != null) {
                    payments.addAll(authorizedPayments);
                } else if(authorizedPayments != null){
                    payments = authorizedPayments;
                }
            } else {
                payments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.FAILED, 0);
                pendingPayments = pClient.getPayments(startDate.getTime(), endDate.getTime(), PaymentStatus.INIT, 0);
                if(payments != null && pendingPayments != null) {
                    payments.addAll(pendingPayments);
                } else if(pendingPayments != null){
                    payments = pendingPayments;
                }
            }
        } catch (PaymentException e) {
            logger.error("Error in payment service while getting payments", e);
        } catch (TException e) {
            logger.error("Error getting info from payment service", e);
        }
        if (payments == null || payments.isEmpty()) {
            return null;
        }

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

        /**
         * Generates the payment reconciliation report for the payments captured
         * between the given dates.
         * 
         * @param startDate
         * @param endDate
         * @return
         */
    public ByteArrayOutputStream generatePaymentReconciliationReport(Date startDate, Date endDate) {
                // Retrieving all the payments between start and end dates with status
                // as CAPTURED
        List<Payment> payments = null;
        try {
            payments = pClient.getPaymentsByCapturedDate(startDate.getTime(), endDate.getTime(), 0);
        } catch (PaymentException e) {
            logger.error("Error in payment service while getting payments", e);
        } catch (TException e) {
            logger.error("Error getting info from payment service", e);
        }
        if (payments == null || payments.isEmpty())
            return null;

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

    
    // Prepares the XLS worksheet object and fills in the data with proper
    // formatting
    private ByteArrayOutputStream getSpreadSheetData(List<Payment> payments, boolean useCaptureTimeAsTxnTime) {
        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(S_NO).setCellValue("S.No");
        headerRow.createCell(PAYMENT_ID).setCellValue("Payment Id");
        headerRow.createCell(GATEWAY).setCellValue("Gateway");
        headerRow.createCell(PAYMENT_METHOD).setCellValue("Payment Method");
        headerRow.getCell(PAYMENT_METHOD).setCellStyle(styleWT);
        
        headerRow.createCell(TXN_ID).setCellValue("Txn Id");
        headerRow.createCell(AMOUNT).setCellValue("Amount");
        headerRow.createCell(PAY_STATUS).setCellValue("Payment Status");
        headerRow.createCell(PAY_STATUS_DESC).setCellValue("Payment Status Description");
        headerRow.getCell(PAY_STATUS_DESC).setCellStyle(styleWT);
        headerRow.createCell(TXN_STATUS).setCellValue("Gateway Txn Status");
        headerRow.createCell(REF_CODE).setCellValue("Reference Code");
        headerRow.createCell(TXN_TIME).setCellValue("Transaction Time");

        headerRow.createCell(CUST_ID).setCellValue("Customer Id");
        headerRow.createCell(NAME).setCellValue("Name");
        headerRow.createCell(MOB_NO).setCellValue("MobileNo");
        headerRow.createCell(ADDR).setCellValue("Address");
        headerRow.getCell(ADDR).setCellStyle(styleWT);
        headerRow.createCell(PINCODE).setCellValue("Pincode");
        headerRow.createCell(CITY).setCellValue("City");
        headerRow.createCell(STATE).setCellValue("State");
        headerRow.createCell(EMAIL).setCellValue("Login Email");

        headerRow.createCell(ORDER_ID).setCellValue("Order Id");
        headerRow.createCell(ORDER_STATUS).setCellValue("Order Status");
        headerRow.createCell(ORDER_STATUS_DESC).setCellValue("Order Status Description");

        headerRow.createCell(ITEM_ID).setCellValue("Item Id");
        headerRow.createCell(PROD_GRP).setCellValue("Product Group");
        headerRow.createCell(BRAND).setCellValue("Brand");
        headerRow.createCell(MOD_NAME).setCellValue("Model Name");
        headerRow.createCell(MOD_NUM).setCellValue("Model Number");
        headerRow.createCell(QTY).setCellValue("Qty");

        int paymethodColWidth = 25, statusDescWidth = 25, addrColWidth = 35;
        paymentSheet.setColumnWidth(PAYMENT_METHOD, 256 * paymethodColWidth); // set width of payment method column
        paymentSheet.setColumnWidth(PAY_STATUS_DESC, 256 * statusDescWidth); // set width of payment status description column
        paymentSheet.setColumnWidth(ADDR, 256 * addrColWidth); // set width of address column
        List<Order> orders;
        long txnId;
        Row contentRow;
        Calendar calendar = Calendar.getInstance();
        DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
        float rowHeight = paymentSheet.getDefaultRowHeightInPoints();
        int sNo = 0;
        for (Payment payment : payments) {
            float newRowHeight = paymentSheet.getDefaultRowHeightInPoints();;
            try {
                paymentSerialNo++;
                contentRow = paymentSheet.createRow(paymentSerialNo);
                sNo++;
                contentRow.createCell(S_NO).setCellValue(sNo);
                contentRow.createCell(PAYMENT_ID).setCellValue(payment.getPaymentId());

                PaymentGateway gateway = gateWays.get(payment.getGatewayId());
                if(gateway == null) {
                    try {
                        gateway = pClient.getPaymentGateway(payment.getGatewayId());
                        gateWays.put(payment.getGatewayId(), gateway);
                    } catch (Exception e) {
                        logger.error("Error gerring payment gateway info from payment service", e);
                    }
                }
                contentRow.createCell(GATEWAY).setCellValue(gateway != null ? gateway.getName() : payment.getGatewayId()+"");
                //contentRow.createCell(GATEWAY).setCellValue(payment.getGatewayId());
                
                String paymentMethod = getPaymentMethod(payment.getAttributes());
                contentRow.createCell(PAYMENT_METHOD).setCellValue(paymentMethod);
                contentRow.getCell(PAYMENT_METHOD).setCellStyle(styleWT);
                
                if(paymentMethod.length() > paymethodColWidth) {
                    newRowHeight = Math.max(newRowHeight, (paymentMethod.length() / paymethodColWidth + 1) * rowHeight);
                }
                
                contentRow.createCell(TXN_ID).setCellValue(payment.getMerchantTxnId());
                contentRow.createCell(AMOUNT).setCellValue(payment.getAmount());
                contentRow.getCell(AMOUNT).setCellStyle(styleAmount);
                contentRow.createCell(PAY_STATUS).setCellValue(payment.getStatus().name());
                String desc = payment.getDescription();
                contentRow.createCell(PAY_STATUS_DESC).setCellValue(desc);
                contentRow.getCell(PAY_STATUS_DESC).setCellStyle(styleWT);
                if(desc != null && desc.length() > statusDescWidth) {
                    newRowHeight = Math.max(newRowHeight, (desc.length() / statusDescWidth + 1) * rowHeight);
                }
                
                contentRow.createCell(TXN_STATUS).setCellValue(payment.getGatewayTxnStatus());
                contentRow.createCell(REF_CODE).setCellValue(payment.getReferenceCode());
                
                if(useCaptureTimeAsTxnTime)
                        calendar.setTimeInMillis(payment.getSuccessTimestamp());
                else
                        calendar.setTimeInMillis(payment.getInitTimestamp());
                contentRow.createCell(TXN_TIME).setCellValue(formatter.format(calendar.getTime()));

                txnId = payment.getMerchantTxnId();
                orders = tClient.getOrdersForTransaction(txnId, payment.getUserId());
                List<LineItem> lineItems;

                String address = "";
                
                if (orders == null || orders.isEmpty()) {
                    continue;
                }
                contentRow.createCell(CUST_ID).setCellValue(orders.get(0).getCustomer_id());
                contentRow.createCell(NAME).setCellValue(orders.get(0).getCustomer_name());
                contentRow.createCell(MOB_NO).setCellValue(orders.get(0).getCustomer_mobilenumber());
                address = orders.get(0).getCustomer_address1() + ", " + orders.get(0).getCustomer_address2();
                contentRow.createCell(ADDR).setCellValue(address);
                contentRow.getCell(ADDR).setCellStyle(styleWT);
             
                if(address.length() > addrColWidth) {
                    newRowHeight = Math.max(newRowHeight, (address.length() / addrColWidth + 1) * rowHeight);
                }
                contentRow.setHeightInPoints(newRowHeight);
                
                contentRow.createCell(PINCODE).setCellValue(orders.get(0).getCustomer_pincode());
                contentRow.createCell(CITY).setCellValue(orders.get(0).getCustomer_city());
                contentRow.createCell(STATE).setCellValue(orders.get(0).getCustomer_state());
                contentRow.createCell(EMAIL).setCellValue(orders.get(0).getCustomer_email());
                
                boolean firstOrder = true;
                for (Order o : orders) {
                    if(o.getStatus() == OrderStatus.RTO_RESHIPPED || o.getStatus() == OrderStatus.DOA_VALID_RESHIPPED || o.getStatus() == OrderStatus.DOA_INVALID_RESHIPPED)
                        continue;

                    if(firstOrder) {
                        firstOrder = false;
                    } else {
                        paymentSerialNo++;
                        contentRow = paymentSheet.createRow(paymentSerialNo);
                    }

                    contentRow.createCell(ORDER_ID).setCellValue(o.getId());
                    contentRow.createCell(ORDER_STATUS).setCellValue(o.getStatus().name());
                    contentRow.createCell(ORDER_STATUS_DESC).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(ITEM_ID).setCellValue(i.getId());
                        contentRow.createCell(PROD_GRP).setCellValue(i.getProductGroup());
                        contentRow.createCell(BRAND).setCellValue(i.getBrand());
                        contentRow.createCell(MOD_NAME).setCellValue(i.getModel_name());
                        contentRow.createCell(MOD_NUM).setCellValue(i.getModel_number());
                        contentRow.createCell(QTY).setCellValue(i.getQuantity());
                    }
                }
            } catch (TransactionServiceException e) {
                logger.error("Error in transaction service while getting orders", e);
            } catch (TException e) {
                logger.error("Error getting info from transaction service", e);
            }
        }

        for (int i = 0; i <= QTY; i++) {
            if (i == PAYMENT_METHOD || i == PAY_STATUS_DESC || i == ADDR) // 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) {
            logger.error("Error while streaming payment details report", e);
        }
        return baosXLS;
    }
    
    public String getPaymentMethod(List<Attribute> paymentAttributes) {
        String paymentMethod = null;
        if(paymentAttributes == null || paymentAttributes.isEmpty()) {
            return "N/A";
        }
        for(Attribute a : paymentAttributes) {
            if("payMethod".equals(a.getName())) {
                paymentMethod = Constants.PAYMENT_METHOD.get(a.getValue());
                break;
            }
        }
        return paymentMethod != null ? paymentMethod : "N/A";
    }
    
    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("06/30/2011");
            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            cal.add(Calendar.DATE, 1);
            endDate.setTime(cal.getTimeInMillis());
        } catch (ParseException pe) {
            logger.error("Error parsing the supplied date", pe);
        }
        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) {
            logger.error("Error creating payment details report", e);
        } catch (IOException e) {
            logger.error("IO error while creating payment details report", e);
        }
        System.out.println("Successfully generated the payment details report");
    }
}