Subversion Repositories SmartDukaan

Rev

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