Subversion Repositories SmartDukaan

Rev

Rev 3125 | Rev 4817 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1676 ankur.sing 1
package in.shop2020.support.services;
2
 
1879 ankur.sing 3
import in.shop2020.model.v1.order.Order;
4
import in.shop2020.model.v1.order.TransactionServiceException;
1676 ankur.sing 5
import in.shop2020.model.v1.user.Address;
1879 ankur.sing 6
import in.shop2020.model.v1.user.Cart;
7
import in.shop2020.model.v1.user.Line;
8
import in.shop2020.model.v1.user.ShoppingCartException;
1676 ankur.sing 9
import in.shop2020.model.v1.user.User;
1684 ankur.sing 10
import in.shop2020.model.v1.user.UserContextException;
11
import in.shop2020.model.v1.user.UserState;
1676 ankur.sing 12
import in.shop2020.model.v1.user.UserType;
3125 rajveer 13
import in.shop2020.thrift.clients.TransactionClient;
14
import in.shop2020.thrift.clients.UserClient;
1676 ankur.sing 15
 
16
import java.io.ByteArrayOutputStream;
17
import java.io.FileNotFoundException;
18
import java.io.FileOutputStream;
19
import java.io.IOException;
1684 ankur.sing 20
import java.text.DateFormat;
21
import java.text.SimpleDateFormat;
1676 ankur.sing 22
import java.util.Calendar;
1879 ankur.sing 23
import java.util.Date;
1676 ankur.sing 24
import java.util.List;
25
 
26
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
27
import org.apache.poi.ss.usermodel.Cell;
28
import org.apache.poi.ss.usermodel.CellStyle;
29
import org.apache.poi.ss.usermodel.Font;
30
import org.apache.poi.ss.usermodel.Row;
31
import org.apache.poi.ss.usermodel.Sheet;
32
import org.apache.poi.ss.usermodel.Workbook;
33
import org.apache.poi.ss.util.CellRangeAddress;
34
import org.apache.thrift.TException;
3213 chandransh 35
import org.slf4j.Logger;
36
import org.slf4j.LoggerFactory;
1676 ankur.sing 37
 
38
public class RegisteredUsersGenerator {
3213 chandransh 39
 
40
    private static Logger logger = LoggerFactory.getLogger(RegisteredUsersGenerator.class);
41
 
3125 rajveer 42
	UserClient usc;
1676 ankur.sing 43
    in.shop2020.model.v1.user.UserContextService.Client uClient;
1879 ankur.sing 44
 
3125 rajveer 45
    TransactionClient tsc;
1879 ankur.sing 46
    in.shop2020.model.v1.order.TransactionService.Client tClient;
47
 
1676 ankur.sing 48
    public RegisteredUsersGenerator() {
49
        try {
3125 rajveer 50
            usc = new UserClient();
1676 ankur.sing 51
            uClient = usc.getClient();
1879 ankur.sing 52
 
3125 rajveer 53
            tsc = new TransactionClient();
1879 ankur.sing 54
            tClient = tsc.getClient();
1676 ankur.sing 55
        } catch (Exception e) {
3213 chandransh 56
            logger.error("Error initializing connection to user or order service", e);
1676 ankur.sing 57
        }
58
    }
59
 
60
    /**
61
     * This method is used in RegisteredUsersController. 
62
     * If any registered user(s) exist(s), then returns ByteArrayOutputStream containing user(s) data,
63
     * otherwise returns null
64
     * @param startDate -- inclusive
65
     * @param endDate -- inclusive
66
     * @return
67
     */
68
    public ByteArrayOutputStream generateRegisteredUsersReport() {
69
        List<User> users = null;
70
        try {
1891 ankur.sing 71
            users = uClient.getAllUsers(UserType.USER, -1, -1);
1676 ankur.sing 72
        } catch (TException e) {
3213 chandransh 73
            logger.error("Unable to get all users", e);
1676 ankur.sing 74
        }
75
        if(users == null || users.isEmpty()) {
76
            return null;
77
        }
78
        // Preparing XLS file for output
79
        return getSpreadSheetData(users);
80
 
81
    }
82
 
83
    // Prepares the XLS worksheet object and fills in the data with proper
84
    // formatting
85
    private ByteArrayOutputStream getSpreadSheetData(List<User> users) {
86
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
87
 
88
        Workbook wb = new HSSFWorkbook();
89
 
90
        Font font = wb.createFont();
91
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
92
        CellStyle style = wb.createCellStyle();
93
        style.setFont(font);
94
 
95
        CellStyle styleWT = wb.createCellStyle();
96
        styleWT.setWrapText(true);
97
 
98
        Sheet userSheet = wb.createSheet("User");
99
        short userSerialNo = 0;
100
 
101
        Row titleRow = userSheet.createRow(userSerialNo++);
102
        Cell titleCell = titleRow.createCell(0);
103
        titleCell.setCellValue("Registered Users");
104
        titleCell.setCellStyle(style);
105
 
106
        userSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
107
 
108
        Row headerRow = userSheet.createRow(userSerialNo++);
109
        headerRow.createCell(0).setCellValue("User Id");
110
        headerRow.createCell(1).setCellValue("Email");
111
        headerRow.createCell(2).setCellValue("Name");
112
        headerRow.createCell(3).setCellValue("Communication Email");
113
        headerRow.createCell(4).setCellValue("Date of Birth");
114
        headerRow.createCell(5).setCellValue("Sex");
115
        headerRow.createCell(6).setCellValue("Mobile");
1684 ankur.sing 116
        headerRow.createCell(7).setCellValue("Registered On");
117
        headerRow.createCell(8).setCellValue("Last Login");
1879 ankur.sing 118
        headerRow.createCell(9).setCellValue("Successful Orders");
119
        headerRow.createCell(10).setCellValue("Pending/Failed Orders");
120
        headerRow.createCell(11).setCellValue("Items in Cart");
121
        userSheet.setColumnWidth(11, 20 * 256); // set width of items in cart column to 20 chars
1676 ankur.sing 122
 
123
        Calendar calendar = Calendar.getInstance();
124
        Row contentRow;
125
        float defaultRowHeight = userSheet.getDefaultRowHeightInPoints();
1684 ankur.sing 126
        UserState uState;
127
        DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
1879 ankur.sing 128
        Date currentDate = new Date();
1676 ankur.sing 129
        for (User u : users) {
130
            userSerialNo++;
131
            contentRow = userSheet.createRow(userSerialNo);
132
            contentRow.createCell(0).setCellValue(u.getUserId());
133
            contentRow.createCell(1).setCellValue(u.getEmail());
134
            contentRow.createCell(2).setCellValue(u.getName());
135
            contentRow.createCell(3).setCellValue(u.getCommunicationEmail());
136
            contentRow.createCell(4).setCellValue(u.getDateOfBirth());
137
            // calendar.setTimeInMillis
138
            contentRow.createCell(5).setCellValue(u.getSex().name());
139
            contentRow.createCell(6).setCellValue(u.getMobileNumber());
140
 
1879 ankur.sing 141
 
142
 
1684 ankur.sing 143
            try {
144
                uState = uClient.getUserState(u.getUserId());
145
                calendar.setTimeInMillis(uState.getActiveSince());
146
                contentRow.createCell(7).setCellValue(formatter.format(calendar.getTime()));
147
                calendar.setTimeInMillis(uState.getLastLogin());
148
                contentRow.createCell(8).setCellValue(formatter.format(calendar.getTime()));
149
            } catch (UserContextException e) {
3213 chandransh 150
                logger.error("Error while getting user state", e);
1684 ankur.sing 151
            } catch (TException e) {
3213 chandransh 152
                logger.error("Unable to get user state", e);
1684 ankur.sing 153
            }
1879 ankur.sing 154
 
155
            try {
156
                List<Order> orders = tClient.getOrdersForCustomer(u.getUserId(), 0, currentDate.getTime(), null);
157
                int noOfFailedOrders = 0, noOfValidOrders = 0;
158
                for(Order order : orders) {
159
                    if(order.getStatus().getValue() < 3) {
160
                        noOfFailedOrders++;
161
                    } else {
162
                        noOfValidOrders++;
163
                    }
164
                }
165
                contentRow.createCell(9).setCellValue(noOfValidOrders);
166
                contentRow.createCell(10).setCellValue(noOfFailedOrders);
167
            } catch (TransactionServiceException e) {
3213 chandransh 168
                logger.error("Error while getting orders for the customer", e);
1879 ankur.sing 169
            } catch (TException e) {
3213 chandransh 170
                logger.error("Unable to get orders for the customer", e);
1879 ankur.sing 171
            }
172
 
173
            String itemList = getCartItems(u.getUserId());
174
            contentRow.createCell(11).setCellValue(itemList);
175
            contentRow.getCell(11).setCellStyle(styleWT);
1684 ankur.sing 176
 
1676 ankur.sing 177
            List<Address> addresses = u.getAddresses();
178
            if(addresses == null || addresses.isEmpty()) {
179
                continue;
180
            }
1879 ankur.sing 181
            int i = 0, col, defaultAddrCol = 12, maxAddrLength = 0, len, addrColWidth = 40;
1676 ankur.sing 182
            String addressString;
183
            for(Address a : addresses) {
184
                if(a.getId() == u.getDefaultAddressId()) {
185
                    col = defaultAddrCol;
1684 ankur.sing 186
                    headerRow.createCell(col).setCellValue("Default Address");
1676 ankur.sing 187
                } else {
188
                    i++;
189
                    col = defaultAddrCol + i;
190
                    headerRow.createCell(col).setCellValue("Address " + i);
191
                }
1684 ankur.sing 192
                userSheet.setColumnWidth(col, addrColWidth * 256);  // set width of address column to 40 characters
1676 ankur.sing 193
                addressString = generateAddressString(a);
194
                contentRow.createCell(col).setCellValue(addressString);
195
                contentRow.getCell(col).setCellStyle(styleWT);
196
                len = addressString.length();
197
                if(len > maxAddrLength)
198
                    maxAddrLength = len;
199
            }
1879 ankur.sing 200
            if((len = itemList.length()) > maxAddrLength) {
201
                maxAddrLength = len;
202
            }
1676 ankur.sing 203
            contentRow.setHeightInPoints((maxAddrLength / addrColWidth + 1) * defaultRowHeight); // Setting Row Height
204
        }
1879 ankur.sing 205
        for (int i = 0; i <= 10; i++) {
1676 ankur.sing 206
            userSheet.autoSizeColumn(i);
207
        }
208
 
209
        // Write the workbook to the output stream
210
        try {
211
            wb.write(baosXLS);
212
            baosXLS.close();
213
        } catch (IOException e) {
3213 chandransh 214
            logger.error("Unable to write the registered orders report to the byte array", e);
1676 ankur.sing 215
        }
216
        return baosXLS;
217
    }
218
 
1879 ankur.sing 219
    private String getCartItems(long userId) {
220
        String itemList = "";
221
        try {
222
            Cart cart = uClient.getCurrentCart(userId);
223
            if(cart == null) {
224
                return "";
225
            }
226
            List<Line> lines = cart.getLines();
227
            if(lines == null || lines.isEmpty()) {
228
                return "";
229
            }
230
            boolean firstItem = true;
231
            for(Line line : lines) {
232
                if(firstItem) {
233
                    firstItem = false;
234
                    itemList += line.getItemId();
235
                    continue;
236
                }
237
                itemList += ", " + line.getItemId();;
238
            }
239
        } catch (ShoppingCartException e) {
3213 chandransh 240
            logger.error("Error while getting the cart of the user", e);
1879 ankur.sing 241
        } catch (TException e) {
3213 chandransh 242
            logger.error("Unable to get the cart of the user", e);
1879 ankur.sing 243
        }
244
        return itemList;
245
    }
246
 
1676 ankur.sing 247
    private String generateAddressString(Address a) {
248
        String addrStr = "";
249
        addrStr += "Name: " + getStringValue(a.getName());
250
        addrStr += "; Address: " + getStringValue(a.getLine1());
251
        addrStr += ", " + getStringValue(a.getLine2());
252
        addrStr += "; City: " + getStringValue(a.getCity());
253
        addrStr += "; State: " + getStringValue(a.getState());
254
        addrStr += "; Pin: " + getStringValue(a.getPin());
255
        addrStr += "; Phone: " + getStringValue(a.getPhone());
256
        return addrStr;
257
    }
258
 
259
    private String getStringValue(String str) {
260
        return str == null ? "" : str.trim();
261
    }
262
 
263
    public static void main(String[] args) {
264
        RegisteredUsersGenerator rug = new RegisteredUsersGenerator();
265
        try {
266
            String userHome = System.getProperty("user.home");
267
            FileOutputStream f = new FileOutputStream(userHome + "/registered-users.xls");
268
            ByteArrayOutputStream baosXLS = rug.generateRegisteredUsersReport();
269
            if(baosXLS == null) {
270
                System.out.println("No data");
271
                return;
272
            }
273
            baosXLS.writeTo(f);
274
            f.close();
275
        } catch (FileNotFoundException e) {
3213 chandransh 276
            logger.error("Unable to create the registered users report", e);
1676 ankur.sing 277
        } catch (IOException e) {
3213 chandransh 278
            logger.error("IO Error while creating the registered users report", e);
1676 ankur.sing 279
        }
280
        System.out.println("Successfully generated the registered users report");
281
    }
282
}