Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
4801 anupam.sin 1
package in.shop2020.support.controllers;
2
 
3
import java.io.ByteArrayOutputStream;
4
import java.io.IOException;
5
import java.text.DateFormat;
6
import java.text.ParseException;
7
import java.text.SimpleDateFormat;
8
import java.util.ArrayList;
9
import java.util.Calendar;
10
import java.util.Date;
11
import java.util.HashMap;
12
import java.util.List;
13
import java.util.Map;
14
import java.util.SortedSet;
15
import java.util.TimeZone;
16
 
17
import javax.servlet.ServletOutputStream;
18
import javax.servlet.http.HttpServletRequest;
19
import javax.servlet.http.HttpServletResponse;
20
import javax.servlet.http.HttpSession;
21
 
22
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
23
import org.apache.poi.ss.usermodel.Cell;
24
import org.apache.poi.ss.usermodel.CellStyle;
25
import org.apache.poi.ss.usermodel.CreationHelper;
26
import org.apache.poi.ss.usermodel.Font;
27
import org.apache.poi.ss.usermodel.Row;
28
import org.apache.poi.ss.usermodel.Sheet;
29
import org.apache.poi.ss.usermodel.Workbook;
30
import org.apache.poi.ss.util.CellRangeAddress;
31
import org.apache.struts2.interceptor.ServletRequestAware;
32
import org.apache.struts2.interceptor.ServletResponseAware;
33
import org.apache.thrift.TException;
34
import org.apache.thrift.transport.TTransportException;
35
import org.slf4j.Logger;
36
import org.slf4j.LoggerFactory;
37
 
38
import in.shop2020.logistics.LogisticsServiceException;
39
import in.shop2020.logistics.Provider;
5354 anupam.sin 40
import in.shop2020.model.v1.order.LineItem;
4801 anupam.sin 41
import in.shop2020.model.v1.order.Order;
42
import in.shop2020.model.v1.order.OrderStatus;
43
import in.shop2020.model.v1.order.TransactionServiceException;
44
import in.shop2020.support.utils.ReportsUtils;
45
import in.shop2020.thrift.clients.LogisticsClient;
46
import in.shop2020.thrift.clients.TransactionClient;
47
 
48
public class CourierPerformanceController implements ServletRequestAware, ServletResponseAware {
49
 
50
    private List<OrderStatus> rtoStatuses;
51
    private List<Order> orders;
52
 
53
    private static Logger log = LoggerFactory.getLogger(CourierPerformanceController.class);
54
 
55
    private HttpServletResponse response;
56
    private HttpServletRequest request;
57
    private HttpSession session;
58
    private String errorMsg;
59
    private Date startDate;
60
    private Date endDate;
61
    private Map<Long, String> logisticProviderMap;
62
 
63
    public CourierPerformanceController() {
64
        rtoStatuses = new ArrayList<OrderStatus>();
65
        rtoStatuses.add(OrderStatus.RTO_IN_TRANSIT);
66
        rtoStatuses.add(OrderStatus.RTO_RECEIVED_PRESTINE);
67
        rtoStatuses.add(OrderStatus.RTO_RESHIPPED);
68
        rtoStatuses.add(OrderStatus.RTO_REFUNDED);
69
        rtoStatuses.add(OrderStatus.RTO_RECEIVED_DAMAGED);
70
        rtoStatuses.add(OrderStatus.RTO_LOST_IN_TRANSIT);
71
        rtoStatuses.add(OrderStatus.RTO_DAMAGED_RESHIPPED);
72
        rtoStatuses.add(OrderStatus.RTO_DAMAGED_REFUNDED);
73
        rtoStatuses.add(OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED);
74
        rtoStatuses.add(OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED);
75
        rtoStatuses.add(OrderStatus.RTO_INVENTORY_REVERSED);
76
    }
77
 
78
    public String index() {
79
        log.info(request.getServletPath());
80
        if (!ReportsUtils.canAccessReport(
81
                (Long) session.getAttribute(ReportsUtils.ROLE),
82
                request.getServletPath())) 
83
        {
84
            return "authfail";
85
        }
86
        return "index";
87
    }
88
 
89
    public String create() {
90
        try {
91
            logisticProviderMap = new HashMap<Long, String>();
92
            LogisticsClient lc = new LogisticsClient();
93
            List<Provider> providers = lc.getClient().getAllProviders();    
94
            for (Provider provider : providers) {
95
                logisticProviderMap.put(provider.getId(), provider.getName());
96
            }
97
 
98
            String startDateStr = request.getParameter("startDate");
99
            String endDateStr = request.getParameter("endDate");
100
 
101
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
102
            df.setTimeZone(TimeZone.getTimeZone("IST"));
103
            try {
104
                startDate = df.parse(startDateStr);
105
                endDate = df.parse(endDateStr);
106
                //Calendar cal = Calendar.getInstance();
107
                //cal.setTime(endDate);
108
                //endDate.setTime(cal.getTimeInMillis());
109
            } catch (ParseException pe) {
110
                errorMsg = "Please enter start and end dates in format MM/dd/yyyy";
111
                return "index";
112
            }
113
 
114
            response.setContentType("application/vnd.ms-excel");
115
 
116
            response.setHeader("Content-disposition", "inline; filename=" + "courier-performance-report" + ".xls");
117
 
118
            ServletOutputStream sos;
119
            try {
120
                ByteArrayOutputStream baos = getSpreadSheetData();
121
                sos = response.getOutputStream();
122
                baos.writeTo(sos);
123
                sos.flush();
124
            } catch (IOException e) {
125
                log.error("Unable to stream the courier performance report", e);
126
                errorMsg = "Failed to write to response.";
127
            }
128
        } catch (TTransportException e) {
129
            // TODO Auto-generated catch block
130
            e.printStackTrace();
131
        } catch (TException e) {
132
            // TODO Auto-generated catch block
133
            e.printStackTrace();
134
        } catch (LogisticsServiceException e) {
135
            // TODO Auto-generated catch block
136
            e.printStackTrace();
137
        }
138
        return "index";
139
    }
140
 
141
    private ByteArrayOutputStream getSpreadSheetData() {
142
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
143
 
144
        Workbook wb = new HSSFWorkbook();
145
 
146
        Font font = wb.createFont();
147
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
148
        CellStyle style = wb.createCellStyle();
149
        style.setFont(font);
150
 
151
        CreationHelper createHelper = wb.getCreationHelper();
152
        CellStyle dateCellStyle = wb.createCellStyle();
153
        dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("DD/MM/YYYY"));
154
 
155
        createRtoSheet(wb, style, dateCellStyle);
156
        createDeliveredSheet(wb, style, dateCellStyle);
157
 
158
        // Write the workbook to the output stream
159
        try {
160
            wb.write(baosXLS);
161
            baosXLS.close();
162
        } catch (IOException e) {
163
            log.error("Unable to get the byte array for the affiliate report", e);
164
        }       
165
        return baosXLS;
166
    }
167
 
168
    private void createRtoSheet(Workbook wb, 
169
                                       CellStyle style,
170
                                       CellStyle dateCellStyle) {
171
        // Summary SHEET
172
        Sheet sheet1 = wb.createSheet("RTO");
173
        short affSerialNo = 0;
174
 
175
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
176
 
177
        Row affTitleRow = sheet1.createRow(affSerialNo ++);
178
        Cell affTitleCell = affTitleRow.createCell(0);
179
        affTitleCell.setCellValue("Courier Performance Report : RTO Orders");
180
        affTitleCell.setCellStyle(style);
181
        sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
182
 
183
        sheet1.createRow(affSerialNo ++);
184
 
185
        Row affDateRangeRow = sheet1.createRow(affSerialNo ++);
186
        Cell affDateRangeCell = affDateRangeRow.createCell(0);
187
        affDateRangeCell.setCellValue("Date Range : " + df.format(startDate) + " - " + df.format(endDate));
188
        affDateRangeCell.setCellStyle(style);
189
        sheet1.addMergedRegion(new CellRangeAddress(3, 3, 0, 6));
190
 
191
        sheet1.createRow(affSerialNo ++);sheet1.createRow(affSerialNo ++);
192
 
193
        Row affHeaderRow = sheet1.createRow(affSerialNo++);
194
        affHeaderRow.createCell(0).setCellValue("Order Id");
195
        affHeaderRow.createCell(1).setCellValue("Payment Type");
196
        affHeaderRow.createCell(2).setCellValue("Pincode");
197
        affHeaderRow.createCell(3).setCellValue("City");
198
        affHeaderRow.createCell(4).setCellValue("Logistics Provider");
199
        affHeaderRow.createCell(5).setCellValue("Shipping Date");
200
        affHeaderRow.createCell(6).setCellValue("Delivery Date");
201
        affHeaderRow.createCell(7).setCellValue("Expected Delivery Date");
202
        affHeaderRow.createCell(8).setCellValue("Delay");
203
 
5354 anupam.sin 204
        affHeaderRow.createCell(9).setCellValue("First Delivery Attempt");
205
        affHeaderRow.createCell(10).setCellValue("First Attempt Delay");
206
 
207
        affHeaderRow.createCell(11).setCellValue("Promised Delivery Date");
208
        affHeaderRow.createCell(12).setCellValue("Order Created Date");
209
        affHeaderRow.createCell(13).setCellValue("Promised Shipping Date");
210
        affHeaderRow.createCell(14).setCellValue("Return Receive Date");
211
        affHeaderRow.createCell(15).setCellValue("Product Name");
212
        affHeaderRow.createCell(16).setCellValue("AWB");
213
 
214
        for (int i=0; i<17 ;i++) {
4801 anupam.sin 215
            affHeaderRow.getCell(i).setCellStyle(style);
216
        }
217
 
218
        try {
219
            TransactionClient tc = new TransactionClient();
220
            orders = tc.getClient().getAllOrders(rtoStatuses, startDate.getTime(), endDate.getTime(), 0);
221
        } catch (TransactionServiceException e) {
222
            // TODO Auto-generated catch block
223
            e.printStackTrace();
224
        } catch (TException e) {
225
            // TODO Auto-generated catch block
226
            e.printStackTrace();
227
        }
228
 
229
        for(Order order : orders) {
230
            boolean deliveryTimestampSet = false;
231
            long diffDays = -99;
232
 
233
            if (order.getDelivery_timestamp() != 0) {
234
                deliveryTimestampSet = true;
5354 anupam.sin 235
                diffDays = GetDelayinDays(order.getDelivery_timestamp(), order.getExpected_delivery_time());
4801 anupam.sin 236
            }
5354 anupam.sin 237
 
4801 anupam.sin 238
            affSerialNo++;
239
            Row commContentRow = sheet1.createRow(affSerialNo);
240
            commContentRow.createCell(0).setCellValue(order.getId());
241
            commContentRow.createCell(1).setCellValue(order.isCod() ? "COD" : "PREPAID");
242
            commContentRow.createCell(2).setCellValue(order.getCustomer_pincode());
243
            commContentRow.createCell(3).setCellValue(order.getCustomer_city());
244
            commContentRow.createCell(4).setCellValue(logisticProviderMap.get(order.getLogistics_provider_id()));
245
            commContentRow.createCell(5).setCellValue(new Date(order.getShipping_timestamp()));
246
            commContentRow.getCell(5).setCellStyle(dateCellStyle);
247
            if (deliveryTimestampSet) {
248
                commContentRow.createCell(6).setCellValue(new Date(order.getDelivery_timestamp()));
249
                commContentRow.getCell(6).setCellStyle(dateCellStyle);
250
            } else {
251
                commContentRow.createCell(6).setCellValue("N/A");
252
            }
253
            commContentRow.createCell(7).setCellValue(new Date(order.getExpected_delivery_time()));
254
            commContentRow.getCell(7).setCellStyle(dateCellStyle);
255
            if (diffDays == -99) {
256
                commContentRow.createCell(8).setCellValue("N/A");
257
            } else {
258
                commContentRow.createCell(8).setCellValue(diffDays);
259
            }
5354 anupam.sin 260
 
261
            commContentRow.createCell(9).setCellValue(new Date(order.getFirst_attempt_timestamp()));
4801 anupam.sin 262
            commContentRow.getCell(9).setCellStyle(dateCellStyle);
5354 anupam.sin 263
 
264
            if (order.getFirst_attempt_timestamp() != 0) {
265
                commContentRow.createCell(9).setCellValue(new Date(order.getFirst_attempt_timestamp()));
266
                commContentRow.getCell(9).setCellStyle(dateCellStyle);
267
 
268
                diffDays = GetDelayinDays(order.getFirst_attempt_timestamp(), order.getExpected_delivery_time());
269
                commContentRow.createCell(10).setCellValue(diffDays);
270
            } else {
271
                commContentRow.createCell(9).setCellValue("N/A");
272
                commContentRow.createCell(10).setCellValue("N/A");
273
            }
274
 
275
            commContentRow.createCell(11).setCellValue(new Date(order.getPromised_delivery_time()));
4801 anupam.sin 276
            commContentRow.getCell(11).setCellStyle(dateCellStyle);
5354 anupam.sin 277
            commContentRow.createCell(12).setCellValue(new Date(order.getCreated_timestamp()));
278
            commContentRow.getCell(12).setCellStyle(dateCellStyle);
279
            commContentRow.createCell(13).setCellValue(new Date(order.getPromised_shipping_time()));
280
            commContentRow.getCell(13).setCellStyle(dateCellStyle);
281
            commContentRow.createCell(14).setCellValue(new Date(order.getReceived_return_timestamp()));
282
            commContentRow.getCell(14).setCellStyle(dateCellStyle);
283
 
284
            List<LineItem> items = order.getLineitems();
285
            String product = items.get(0).getBrand() + " " + ((items.get(0).getModel_name() == null)? "" : items.get(0).getModel_name()) + " " + items.get(0).getModel_number();
286
            commContentRow.createCell(15).setCellValue(product);
287
            commContentRow.createCell(16).setCellValue(order.getAirwaybill_no());
4801 anupam.sin 288
        }
5354 anupam.sin 289
        for (int i = 0; i<17; i++) {
4801 anupam.sin 290
            sheet1.autoSizeColumn(i);
291
        }
292
    }
293
 
294
    private void createDeliveredSheet(Workbook wb, 
295
            CellStyle style,
296
            CellStyle dateCellStyle) {
297
        // Summary SHEET
298
        Sheet sheet2 = wb.createSheet("Delivered");
299
        short affSerialNo = 0;
300
 
301
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
302
 
303
        Row affTitleRow = sheet2.createRow(affSerialNo ++);
304
        Cell affTitleCell = affTitleRow.createCell(0);
305
        affTitleCell.setCellValue("Courier Performance Report : Delivered Orders");
306
        affTitleCell.setCellStyle(style);
307
        sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
308
 
309
        sheet2.createRow(affSerialNo ++);
310
 
311
        Row affDateRangeRow = sheet2.createRow(affSerialNo ++);
312
        Cell affDateRangeCell = affDateRangeRow.createCell(0);
313
        affDateRangeCell.setCellValue("Date Range : " + df.format(startDate) + " - " + df.format(endDate));
314
        affDateRangeCell.setCellStyle(style);
315
        sheet2.addMergedRegion(new CellRangeAddress(3, 3, 0, 6));
316
 
317
        sheet2.createRow(affSerialNo ++);sheet2.createRow(affSerialNo ++);
318
 
319
        Row affHeaderRow = sheet2.createRow(affSerialNo++);
320
        affHeaderRow.createCell(0).setCellValue("Order Id");
321
        affHeaderRow.createCell(1).setCellValue("Payment Type");
322
        affHeaderRow.createCell(2).setCellValue("Pincode");
323
        affHeaderRow.createCell(3).setCellValue("City");
324
        affHeaderRow.createCell(4).setCellValue("Logistics Provider");
325
        affHeaderRow.createCell(5).setCellValue("Shipping Date");
326
        affHeaderRow.createCell(6).setCellValue("Delivery Date");
327
        affHeaderRow.createCell(7).setCellValue("Expected Delivery Date");
328
        affHeaderRow.createCell(8).setCellValue("Delay");
5354 anupam.sin 329
 
330
        affHeaderRow.createCell(9).setCellValue("First Delivery Attempt");
331
        affHeaderRow.createCell(10).setCellValue("First Attempt Delay");
4801 anupam.sin 332
 
5354 anupam.sin 333
 
334
        affHeaderRow.createCell(11).setCellValue("Promised Delivery Date");
335
        affHeaderRow.createCell(12).setCellValue("Order Created Date");
336
        affHeaderRow.createCell(13).setCellValue("Promised Shipping Date");
337
        affHeaderRow.createCell(14).setCellValue("Product Name");
338
        affHeaderRow.createCell(15).setCellValue("AWB");
339
 
340
        for (int i=0; i<16 ;i++) {
4801 anupam.sin 341
            affHeaderRow.getCell(i).setCellStyle(style);
342
        }
343
 
344
        try {
345
            TransactionClient tc = new TransactionClient();
346
            List<OrderStatus> deliveredStatuses = new ArrayList<OrderStatus>();
347
            deliveredStatuses.add(OrderStatus.DELIVERY_SUCCESS);
348
            orders = tc.getClient().getAllOrders(deliveredStatuses, startDate.getTime(), endDate.getTime(), 0);
349
        } catch (TransactionServiceException e) {
350
            // TODO Auto-generated catch block
351
            e.printStackTrace();
352
        } catch (TException e) {
353
            // TODO Auto-generated catch block
354
            e.printStackTrace();
355
        }
356
 
357
        for(Order order : orders) {
5354 anupam.sin 358
            long diffDays = GetDelayinDays(order.getDelivery_timestamp(), order.getExpected_delivery_time());
4801 anupam.sin 359
            affSerialNo++;
360
            Row commContentRow = sheet2.createRow(affSerialNo);
361
            commContentRow.createCell(0).setCellValue(order.getId());
362
            commContentRow.createCell(1).setCellValue(order.isCod() ? "COD" : "PREPAID");
363
            commContentRow.createCell(2).setCellValue(order.getCustomer_pincode());
364
            commContentRow.createCell(3).setCellValue(order.getCustomer_city());
365
            commContentRow.createCell(4).setCellValue(logisticProviderMap.get(order.getLogistics_provider_id()));
366
            commContentRow.createCell(5).setCellValue(new Date(order.getShipping_timestamp()));
367
            commContentRow.getCell(5).setCellStyle(dateCellStyle);
368
            commContentRow.createCell(6).setCellValue(new Date(order.getDelivery_timestamp()));
369
            commContentRow.getCell(6).setCellStyle(dateCellStyle);
370
            commContentRow.createCell(7).setCellValue(new Date(order.getExpected_delivery_time()));
371
            commContentRow.getCell(7).setCellStyle(dateCellStyle);
372
            commContentRow.createCell(8).setCellValue(diffDays);
5354 anupam.sin 373
 
374
            commContentRow.createCell(9).setCellValue(new Date(order.getFirst_attempt_timestamp()));
4801 anupam.sin 375
            commContentRow.getCell(9).setCellStyle(dateCellStyle);
5354 anupam.sin 376
 
377
            diffDays = GetDelayinDays(order.getFirst_attempt_timestamp(), order.getExpected_delivery_time());
378
            commContentRow.createCell(10).setCellValue(diffDays);
379
 
380
 
381
            commContentRow.createCell(11).setCellValue(new Date(order.getPromised_delivery_time()));
4801 anupam.sin 382
            commContentRow.getCell(11).setCellStyle(dateCellStyle);
5354 anupam.sin 383
            commContentRow.createCell(12).setCellValue(new Date(order.getCreated_timestamp()));
384
            commContentRow.getCell(12).setCellStyle(dateCellStyle);
385
            commContentRow.createCell(13).setCellValue(new Date(order.getPromised_shipping_time()));
386
            commContentRow.getCell(13).setCellStyle(dateCellStyle);
387
 
388
            List<LineItem> items = order.getLineitems();
389
            String product = items.get(0).getBrand() + " " + items.get(0).getModel_name() + " " + items.get(0).getModel_number();
390
 
391
            commContentRow.createCell(14).setCellValue(product);
392
            commContentRow.createCell(15).setCellValue(order.getAirwaybill_no());
4801 anupam.sin 393
        }
5354 anupam.sin 394
        for (int i = 0; i<16; i++) {
4801 anupam.sin 395
            sheet2.autoSizeColumn(i);
396
        }
397
    }
5354 anupam.sin 398
 
399
    long GetDelayinDays(long actualDate, long expectedDate) {
400
 
401
        Calendar actualTime = Calendar.getInstance();
402
        Calendar expectedTime = Calendar.getInstance();
403
        long millisInDays = 24 * 60 * 60 * 1000;
404
 
405
        actualTime.setTimeInMillis(actualDate);
406
        expectedTime.setTimeInMillis(expectedDate);
407
 
408
        long actualTimeInMillis = actualTime.getTimeInMillis();
409
        long expectedTimeInMillis = expectedTime.getTimeInMillis();
410
        long diff = actualTimeInMillis - expectedTimeInMillis;
411
        long diffDays = diff / millisInDays;
412
 
413
        return diffDays;
414
    }
4801 anupam.sin 415
 
416
    public List<OrderStatus> getRtoStatuses() {
417
        return rtoStatuses;
418
    }
419
 
420
    public void setRtoStatuses(List<OrderStatus> rtoStatuses) {
421
        this.rtoStatuses = rtoStatuses;
422
    }
423
 
424
    public void setOrders(List<Order> orders) {
425
        this.orders = orders;
426
    }
427
 
428
    public List<Order> getOrders() {
429
        return orders;
430
    }
431
 
432
    @Override
433
    public void setServletResponse(HttpServletResponse res) {
434
        this.response = res;
435
    }
436
 
437
    @Override
438
    public void setServletRequest(HttpServletRequest req) {
439
        this.request = req;
440
        this.session = req.getSession();
441
    }
442
 
443
    public String getErrorMsg() {
444
        return errorMsg;
445
    }
446
 
447
    public void setErrorMsg(String errorMsg) {
448
        this.errorMsg = errorMsg;
449
    }
450
 
451
    public Date getStartDate() {
452
        return startDate;
453
    }
454
 
455
    public void setStartDate(Date startDate) {
456
        this.startDate = startDate;
457
    }
458
 
459
    public Date getEndDate() {
460
        return endDate;
461
    }
462
 
463
    public void setEndDate(Date endDate) {
464
        this.endDate = endDate;
465
    }
466
}