Subversion Repositories SmartDukaan

Rev

Rev 3125 | Rev 5326 | 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.Order;
import in.shop2020.model.v1.order.TransactionServiceException;
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.UserContextException;
import in.shop2020.model.v1.user.UserState;
import in.shop2020.model.v1.user.UserType;
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.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.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 RegisteredUsersGenerator {
    
    private static Logger logger = LoggerFactory.getLogger(RegisteredUsersGenerator.class);
    
        UserClient usc;
    in.shop2020.model.v1.user.UserContextService.Client uClient;
    
    TransactionClient tsc;
    in.shop2020.model.v1.order.TransactionService.Client tClient;
    
    public RegisteredUsersGenerator() {
        try {
            usc = new UserClient();
            uClient = usc.getClient();
            
            tsc = new TransactionClient();
            tClient = tsc.getClient();
        } catch (Exception e) {
            logger.error("Error initializing connection to user or order service", e);
        }
    }

    /**
     * This method is used in RegisteredUsersController. 
     * If any registered user(s) exist(s), then returns ByteArrayOutputStream containing user(s) data,
     * otherwise returns null
     * @param startDate -- inclusive
     * @param endDate -- inclusive
     * @return
     */
    public ByteArrayOutputStream generateRegisteredUsersReport() {
        List<User> users = null;
        try {
            users = uClient.getAllUsers(UserType.USER, -1, -1);
        } catch (TException e) {
            logger.error("Unable to get all users", e);
        }
        if(users == null || users.isEmpty()) {
            return null;
        }
        // Preparing XLS file for output
        return getSpreadSheetData(users);

    }

    // Prepares the XLS worksheet object and fills in the data with proper
    // formatting
    private ByteArrayOutputStream getSpreadSheetData(List<User> users) {
        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);

        Sheet userSheet = wb.createSheet("User");
        short userSerialNo = 0;

        Row titleRow = userSheet.createRow(userSerialNo++);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("Registered Users");
        titleCell.setCellStyle(style);

        userSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

        Row headerRow = userSheet.createRow(userSerialNo++);
        headerRow.createCell(0).setCellValue("User Id");
        headerRow.createCell(1).setCellValue("Email");
        headerRow.createCell(2).setCellValue("Name");
        headerRow.createCell(3).setCellValue("Communication Email");
        headerRow.createCell(4).setCellValue("Date of Birth");
        headerRow.createCell(5).setCellValue("Sex");
        headerRow.createCell(6).setCellValue("Mobile");
        headerRow.createCell(7).setCellValue("Registered On");
        headerRow.createCell(8).setCellValue("Last Login");
        headerRow.createCell(9).setCellValue("Successful Orders");
        headerRow.createCell(10).setCellValue("Pending/Failed Orders");
        headerRow.createCell(11).setCellValue("Items in Cart");
        userSheet.setColumnWidth(11, 20 * 256); // set width of items in cart column to 20 chars
        
        Calendar calendar = Calendar.getInstance();
        Row contentRow;
        float defaultRowHeight = userSheet.getDefaultRowHeightInPoints();
        UserState uState;
        DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
        Date currentDate = new Date();
        for (User u : users) {
            userSerialNo++;
            contentRow = userSheet.createRow(userSerialNo);
            contentRow.createCell(0).setCellValue(u.getUserId());
            contentRow.createCell(1).setCellValue(u.getEmail());
            contentRow.createCell(2).setCellValue(u.getName());
            contentRow.createCell(3).setCellValue(u.getCommunicationEmail());
            contentRow.createCell(4).setCellValue(u.getDateOfBirth());
            // calendar.setTimeInMillis
            contentRow.createCell(5).setCellValue(u.getSex().name());
            contentRow.createCell(6).setCellValue(u.getMobileNumber());
            
            
            
            try {
                uState = uClient.getUserState(u.getUserId());
                calendar.setTimeInMillis(uState.getActiveSince());
                contentRow.createCell(7).setCellValue(formatter.format(calendar.getTime()));
                calendar.setTimeInMillis(uState.getLastLogin());
                contentRow.createCell(8).setCellValue(formatter.format(calendar.getTime()));
            } catch (UserContextException e) {
                logger.error("Error while getting user state", e);
            } catch (TException e) {
                logger.error("Unable to get user state", e);
            }
            
            try {
                List<Order> orders = tClient.getOrdersForCustomer(u.getUserId(), 0, currentDate.getTime(), null);
                int noOfFailedOrders = 0, noOfValidOrders = 0;
                for(Order order : orders) {
                    if(order.getStatus().getValue() < 3) {
                        noOfFailedOrders++;
                    } else {
                        noOfValidOrders++;
                    }
                }
                contentRow.createCell(9).setCellValue(noOfValidOrders);
                contentRow.createCell(10).setCellValue(noOfFailedOrders);
            } catch (TransactionServiceException e) {
                logger.error("Error while getting orders for the customer", e);
            } catch (TException e) {
                logger.error("Unable to get orders for the customer", e);
            }
            
            String itemList = getCartItems(u.getUserId());
            contentRow.createCell(11).setCellValue(itemList);
            contentRow.getCell(11).setCellStyle(styleWT);

            List<Address> addresses = u.getAddresses();
            if(addresses == null || addresses.isEmpty()) {
                continue;
            }
            int i = 0, col, defaultAddrCol = 12, maxAddrLength = 0, len, addrColWidth = 40;
            String addressString;
            for(Address a : addresses) {
                if(a.getId() == u.getDefaultAddressId()) {
                    col = defaultAddrCol;
                    headerRow.createCell(col).setCellValue("Default Address");
                } else {
                    i++;
                    col = defaultAddrCol + i;
                    headerRow.createCell(col).setCellValue("Address " + i);
                }
                userSheet.setColumnWidth(col, addrColWidth * 256);  // set width of address column to 40 characters
                addressString = generateAddressString(a);
                contentRow.createCell(col).setCellValue(addressString);
                contentRow.getCell(col).setCellStyle(styleWT);
                len = addressString.length();
                if(len > maxAddrLength)
                    maxAddrLength = len;
            }
            if((len = itemList.length()) > maxAddrLength) {
                maxAddrLength = len;
            }
            contentRow.setHeightInPoints((maxAddrLength / addrColWidth + 1) * defaultRowHeight); // Setting Row Height
        }
        for (int i = 0; i <= 10; i++) {
            userSheet.autoSizeColumn(i);
        }
        
        // Write the workbook to the output stream
        try {
            wb.write(baosXLS);
            baosXLS.close();
        } catch (IOException e) {
            logger.error("Unable to write the registered orders report to the byte array", e);
        }
        return baosXLS;
    }
    
    private String getCartItems(long userId) {
        String itemList = "";
        try {
            Cart cart = uClient.getCurrentCart(userId);
            if(cart == null) {
                return "";
            }
            List<Line> lines = cart.getLines();
            if(lines == null || lines.isEmpty()) {
                return "";
            }
            boolean firstItem = true;
            for(Line line : lines) {
                if(firstItem) {
                    firstItem = false;
                    itemList += line.getItemId();
                    continue;
                }
                itemList += ", " + line.getItemId();;
            }
        } catch (ShoppingCartException e) {
            logger.error("Error while getting the cart of the user", e);
        } catch (TException e) {
            logger.error("Unable to get the cart of the user", e);
        }
        return itemList;
    }
    
    private String generateAddressString(Address a) {
        String addrStr = "";
        addrStr += "Name: " + getStringValue(a.getName());
        addrStr += "; Address: " + getStringValue(a.getLine1());
        addrStr += ", " + getStringValue(a.getLine2());
        addrStr += "; City: " + getStringValue(a.getCity());
        addrStr += "; State: " + getStringValue(a.getState());
        addrStr += "; Pin: " + getStringValue(a.getPin());
        addrStr += "; Phone: " + getStringValue(a.getPhone());
        return addrStr;
    }
    
    private String getStringValue(String str) {
        return str == null ? "" : str.trim();
    }

    public static void main(String[] args) {
        RegisteredUsersGenerator rug = new RegisteredUsersGenerator();
        try {
            String userHome = System.getProperty("user.home");
            FileOutputStream f = new FileOutputStream(userHome + "/registered-users.xls");
            ByteArrayOutputStream baosXLS = rug.generateRegisteredUsersReport();
            if(baosXLS == null) {
                System.out.println("No data");
                return;
            }
            baosXLS.writeTo(f);
            f.close();
        } catch (FileNotFoundException e) {
            logger.error("Unable to create the registered users report", e);
        } catch (IOException e) {
            logger.error("IO Error while creating the registered users report", e);
        }
        System.out.println("Successfully generated the registered users report");
    }
}