Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
7343 anupam.sin 1
package in.shop2020.serving.controllers;
2
 
3
 
4
import in.shop2020.model.v1.order.HotspotStore;
5
import in.shop2020.model.v1.order.LineItem;
6
import in.shop2020.model.v1.order.Order;
7
import in.shop2020.model.v1.order.OrderStatus;
8
import in.shop2020.model.v1.order.RechargeOrderStatus;
9
import in.shop2020.model.v1.order.RechargeTransaction;
10
import in.shop2020.model.v1.order.TransactionService;
11
import in.shop2020.thrift.clients.HelperClient;
12
import in.shop2020.thrift.clients.TransactionClient;
13
import in.shop2020.utils.Mail;
14
 
15
import java.io.ByteArrayOutputStream;
16
import java.io.IOException;
17
import java.nio.ByteBuffer;
18
import java.text.DateFormat;
19
import java.text.SimpleDateFormat;
20
import java.util.ArrayList;
21
import java.util.Calendar;
22
import java.util.Date;
23
import java.util.List;
24
import java.util.Random;
25
 
26
import javax.servlet.ServletContext;
27
import javax.servlet.ServletOutputStream;
28
import javax.servlet.http.HttpServletRequest;
29
import javax.servlet.http.HttpServletResponse;
30
import javax.servlet.http.HttpSession;
31
 
32
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
33
import org.apache.poi.ss.usermodel.Row;
34
import org.apache.poi.ss.usermodel.Sheet;
35
import org.apache.poi.ss.usermodel.Workbook;
7348 anupam.sin 36
import org.apache.thrift.meta_data.SetMetaData;
7343 anupam.sin 37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39
 
40
public class ReportController  extends BaseController {
41
 
42
    /**
43
     * 
44
     */
45
    private static final long serialVersionUID = 1L;
46
 
47
    private static Logger logger = LoggerFactory.getLogger(ReportController.class);
48
 
49
    protected HttpServletRequest request;
50
    protected HttpSession session;
51
    protected HttpServletResponse response;
52
    private ServletContext context;
53
    private String startDate;
54
    private String endDate;
55
    private String status;
56
    private String dateselector;
57
    private String searchError = "";
58
    private Long number = null;
59
    private String passwordGeneration = "";
60
 
61
    private static final String chars = "0123456789";
62
    private static final int LENGTH = 4;
63
    private static final Random random = new Random();
64
    private TransactionClient tsc;
65
    private in.shop2020.model.v1.order.TransactionService.Client tClient;
66
 
67
    private final DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
68
    private final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
69
    private final DateFormat df4Filename = new SimpleDateFormat("EEE_dd_MMM");
70
 
7348 anupam.sin 71
    private String returnType;
7343 anupam.sin 72
    private List<Order> orders = null;
73
    private List<Order> searchResult = null;
7348 anupam.sin 74
    private Long orderId;
7343 anupam.sin 75
 
76
    private boolean showReprintColumn = false;
77
 
78
    public ReportController(){
79
        try {
80
            tsc = new TransactionClient();
81
            tClient = tsc.getClient();
82
        } catch (Exception e) {
83
            logger.error("Error connecting to one of the user, order or payment service", e);
84
        }
85
    }
86
 
87
 
88
    public String index() {
89
//      String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
90
//        if(loginStatus == null || !loginStatus.equals("TRUE")){
91
//            return "authfail";
92
//        }
93
//        
94
//        storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
95
        storeId = 1L;
96
        if(!hotspotStores.containsKey(storeId)){
97
            try{
98
                HotspotStore hotSpotStore = (new TransactionClient()).getClient().getHotspotStore(storeId, "");
99
                hotspotStores.put(storeId, hotSpotStore);
100
            } catch (Exception e) {
101
                logger.error("Unable to get store", e);
102
            }
103
        }
104
 
105
        long today = -1;
106
        today = new Date().getTime();
107
        try {
108
            List<OrderStatus> statuses = new ArrayList<OrderStatus>();
109
            orders = tClient.getOrdersForStore(0, storeId, today, today, statuses);
110
        } catch (Exception e) {
111
            setSearchError("Error getting all transactions for today. Please try again.");
112
            logger.error("Unable to get all Transactions for today", e);
113
        }
114
        return "index";
115
    }
116
 
7348 anupam.sin 117
    public String search() {
7343 anupam.sin 118
//        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
119
//        if(loginStatus == null || !loginStatus.equals("TRUE")){
120
//            return "authfail";
121
//        }
122
        if(number != null) {
123
            try {
124
                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
125
                setSearchResult(tClient.getOrdersForStore(number, 1, -1, -1, statuses));
126
                if(searchResult.size() == 0) {
127
                    setSearchError("Could not find any recharges with this number. Please try again.");
128
                }
129
            } catch(Exception e) {
130
                setSearchError("Some error occured. Please try again.");
131
                logger.error("Error during search", e);
132
            }
133
        }
134
        return index();
135
    }
136
 
137
    public String getCollection() throws Exception{
7346 anupam.sin 138
//        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
139
//        if(loginStatus == null || !loginStatus.equals("TRUE")){
140
//            return "authfail";
141
//        }
7343 anupam.sin 142
        long today = -1;
143
        today = new Date().getTime();
7346 anupam.sin 144
        List<OrderStatus> statuses = new ArrayList<OrderStatus>();
145
        statuses.add(OrderStatus.DELIVERY_SUCCESS);
7348 anupam.sin 146
        List<Order> successfulOrders = tClient.getOrdersForStore(0, 1, today, today, statuses);
147
        statuses.clear();
148
        statuses.add(OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST);
149
        statuses.add(OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);
150
        List<Order> refundedOrders = tClient.getOrdersForStore(0, 1, today, today, statuses);
151
        ByteArrayOutputStream baos = generateCollectionReport(successfulOrders, refundedOrders);
7343 anupam.sin 152
        response.setContentType("application/vnd.ms-excel");
153
        String fileName = "collection-report";
154
        String todayDate = df4Filename.format(new Date(today));
155
        fileName = fileName + "-" + todayDate;
156
        fileName = fileName + ".xls";
157
        response.setHeader("Content-disposition", "inline; filename=" + fileName);
158
        ServletOutputStream sos;
159
        try {
160
            sos = response.getOutputStream();
161
            baos.writeTo(sos);
162
            sos.flush();
163
        } catch (IOException e) {
164
            e.printStackTrace();
165
        }
166
        return null;
167
 
168
    }
169
 
7348 anupam.sin 170
    private ByteArrayOutputStream generateCollectionReport(List<Order> successfulOrders,
171
                                                            List<Order> refundedOrders) {
7343 anupam.sin 172
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
173
        Workbook wb = new HSSFWorkbook();
174
        Sheet reportSheet = wb.createSheet("Recharge Report");
175
        Row reportSheetHeader = reportSheet.createRow((short)0);
176
        reportSheetHeader.createCell(0).setCellValue("Order ID");
177
        reportSheetHeader.createCell(1).setCellValue("Order Date");
7348 anupam.sin 178
        reportSheetHeader.createCell(2).setCellValue("Product");
179
        reportSheetHeader.createCell(3).setCellValue("Status");
180
        reportSheetHeader.createCell(4).setCellValue("Refund Date");
181
        reportSheetHeader.createCell(5).setCellValue("Total Amount");
7343 anupam.sin 182
 
183
        int serialNo = 0;
184
 
7348 anupam.sin 185
        for(Order order : successfulOrders) {
7343 anupam.sin 186
            serialNo++;
187
            Row contentRow = reportSheet.createRow((short)serialNo);
7348 anupam.sin 188
            contentRow.createCell(0).setCellValue(order.getId());
189
            contentRow.createCell(1).setCellValue(formatter.format(new Date(order.getCreated_timestamp())));
190
            contentRow.createCell(2).setCellValue(getProductName(order.getLineitems().get(0)));
191
            contentRow.createCell(3).setCellValue(order.getStatusDescription());
192
            contentRow.createCell(4).setCellValue("N/A");
193
            contentRow.createCell(5).setCellValue(order.getTotal_amount());
7343 anupam.sin 194
        }
195
 
7348 anupam.sin 196
        for(Order order : refundedOrders) {
7343 anupam.sin 197
            serialNo++;
198
            Row contentRow = reportSheet.createRow((short)serialNo);
7348 anupam.sin 199
            contentRow.createCell(0).setCellValue(order.getId());
200
            contentRow.createCell(1).setCellValue(formatter.format(new Date(order.getCreated_timestamp())));
201
            contentRow.createCell(2).setCellValue(getProductName(order.getLineitems().get(0)));
202
            contentRow.createCell(3).setCellValue(order.getStatusDescription());
203
            contentRow.createCell(4).setCellValue(formatter.format(new Date(order.getRefund_timestamp())));
204
            contentRow.createCell(5).setCellValue(order.getTotal_amount());
7343 anupam.sin 205
        }
206
 
207
        try {
208
            wb.write(baosXLS);
209
        } catch (IOException e) {
210
            // TODO Auto-generated catch block
211
            e.printStackTrace();
212
        }
213
        return baosXLS;
214
    }
215
 
216
 
217
    public String create() throws Exception{
218
        long sDate = -1;
219
        long eDate = -1;
220
        RechargeOrderStatus st = null;
221
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
222
        if(loginStatus == null || !loginStatus.equals("TRUE")){
223
            return "authfail";
224
        }
225
        if(dateselector.equals("1")) {
226
            sDate = new Date().getTime();
227
            eDate = sDate;
228
        }else if (dateselector.equals("2")) {
229
            sDate = new Date().getTime() - 86400*1000;
230
            eDate = sDate;
231
        }else {
232
            if(!(startDate.equals(""))) {
233
                sDate = dateFormatter.parse(startDate).getTime();
234
                startDate = dateFormatter.format(sDate);
235
            }
236
            if(!endDate.equals("")) {
237
                eDate = dateFormatter.parse(endDate).getTime();
238
                endDate = dateFormatter.format(sDate);
239
            }
240
        }
241
        if(!status.equals("-1")){
242
            st = RechargeOrderStatus.findByValue(Integer.parseInt(status));
243
        }
244
 
245
        ByteArrayOutputStream baos = generateReport(tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate, st));
246
 
247
        response.setContentType("application/vnd.ms-excel");
248
        String st1 = "ALL";
249
        if(st!=null){
250
            st1 = st.name();
251
        }
252
        String fileName = st1 + "-recharge-report";
253
        if (!startDate.equals("")) {
254
            fileName = fileName + "-" + startDate.replaceAll("\\\\", "_") ;
255
        }
256
        if (!endDate.equals("")) {
257
            fileName = fileName + "-" + endDate.replaceAll("\\\\", "_") ;
258
        }
259
        fileName = fileName + ".xls";
260
        response.setHeader("Content-disposition", "inline; filename=" + fileName);
261
        ServletOutputStream sos;
262
        try {
263
            sos = response.getOutputStream();
264
            baos.writeTo(sos);
265
            sos.flush();
266
        } catch (IOException e) {
267
            e.printStackTrace();
268
        }
269
        return "index";
270
    }
271
 
272
 
273
    private ByteArrayOutputStream generateReport(
274
            List<RechargeTransaction> rechargeTrans) {
275
ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
276
 
277
        Workbook wb = new HSSFWorkbook();
278
 
279
        Sheet reportSheet = wb.createSheet("Recharge Report");
280
 
281
        Row reportSheetHeader = reportSheet.createRow((short)0);
282
        reportSheetHeader.createCell(0).setCellValue("Order ID");
283
        reportSheetHeader.createCell(1).setCellValue("Order Date");
284
        reportSheetHeader.createCell(2).setCellValue("Operator");
285
        reportSheetHeader.createCell(3).setCellValue("Device");
286
        reportSheetHeader.createCell(4).setCellValue("Status");
287
        reportSheetHeader.createCell(5).setCellValue("Recharge Amount");
288
        reportSheetHeader.createCell(6).setCellValue("Discount");
289
        reportSheetHeader.createCell(7).setCellValue("Net Amount");
290
        reportSheetHeader.createCell(8).setCellValue("Type");
291
        reportSheetHeader.createCell(9).setCellValue("Pay Method");
292
        reportSheetHeader.createCell(10).setCellValue("Refund Date");
293
 
294
        int serialNo = 0;
295
 
296
        for(RechargeTransaction transaction : rechargeTrans) {
297
            serialNo++;
298
            Row contentRow = reportSheet.createRow((short)serialNo);
299
            contentRow.createCell(0).setCellValue(transaction.getId());
300
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
301
//            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
302
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
303
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
304
            contentRow.createCell(5).setCellValue(transaction.getAmount());
305
            contentRow.createCell(6).setCellValue(transaction.getDiscount());
306
            contentRow.createCell(7).setCellValue(transaction.getPaymentAmount());
307
            contentRow.createCell(8).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
308
            contentRow.createCell(9).setCellValue(transaction.getPayMethod().name());
309
            if(transaction.getStatus() == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED) {
310
                contentRow.createCell(10).setCellValue(transaction.getResponseTime());
311
            } else {
312
                contentRow.createCell(10).setCellValue("N/A");
313
            }
314
        }
315
        try {
316
            wb.write(baosXLS);
317
        } catch (IOException e) {
318
            // TODO Auto-generated catch block
319
            e.printStackTrace();
320
        }
321
        return baosXLS;
322
    }
323
 
324
    public String downloadInvoice() {
325
        ByteBuffer buffer = null;
326
        try {
327
            if (number == null || number == 0) {
328
                log.error("rechargeId is 0");
329
                return "index";
330
            }
331
            TransactionClient transactionServiceClient = new TransactionClient();
332
            TransactionService.Client orderClient = transactionServiceClient.getClient();
333
            buffer = orderClient.getStoreOrderAdvanceInvoice(number);
334
            if(!buffer.hasArray()) {
335
                log.error("The invoice was not found for orderId : " + 1);
336
            }
337
        } catch (Exception e) {
338
            System.out.println(e.getMessage());
339
        }
340
        response.setContentType("application/pdf");
7346 anupam.sin 341
        response.setHeader("Content-disposition", "attachment; filename=advance-invoice-" + number.toString() + ".pdf");
7343 anupam.sin 342
 
343
        ServletOutputStream sos;
344
        try {
345
            sos = response.getOutputStream();
346
            sos.write(buffer.array());
347
            sos.flush();
348
        } catch (Exception e) {
349
            System.out.println("Unable to stream the invoice file");
350
        }
351
        return "index";
352
    }
353
 
354
    public String sendPassword() throws Exception {
355
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
356
        if(loginStatus == null || !loginStatus.equals("TRUE")){
357
            return "authfail";
358
        }
359
        Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
360
 
361
        char[] buf = new char[LENGTH];
362
        for (int i = 0; i < buf.length; i++) {
363
            buf[i] = chars.charAt(random.nextInt(chars.length()));
364
        }
365
        String password = new String(buf);
366
 
367
        try {
368
            TransactionClient tcl = new TransactionClient(); 
369
            HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");
370
            boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);
371
            if(!wasPasswordSet) {
372
                passwordGeneration = "FAIL";
373
                return index();
374
            }
375
            List<String> toList = new ArrayList<String>();
376
            toList.add(hotSpotStore.getEmail());
377
            HelperClient helperServiceClient = null;
378
            helperServiceClient = new HelperClient();
379
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
380
 
381
 
382
            Mail mail = new Mail();
383
            mail.setSubject("New Password for Saholic Recharge");
384
            mail.setTo(toList);
385
            mail.setData("Your new password is : " + password);
386
            client.sendMail(mail);
387
        } catch(Exception e) {
388
            passwordGeneration = "FAIL";
389
            logger.error("Password generation/sending failed for storeId : " + storeId, e);
390
        }
391
        passwordGeneration = "SUCCESS";
392
        return index();
393
    }
394
 
395
    public String getDateTime(long milliseconds) {
396
        Calendar cal = Calendar.getInstance();
397
        cal.setTimeInMillis(milliseconds);
398
        return formatter.format(cal.getTime());
399
    }
7348 anupam.sin 400
 
401
    public String cancelRequest() {
402
        try{
403
        TransactionClient tcl = new TransactionClient();
404
        tcl.getClient().markOrderCancellationRequestReceived(orderId);
405
        } catch (Exception e) {
406
            logger.error("Could not mark order as cancellation requested for id : " + orderId.toString(), e);
407
            setSearchError("Request failed. Try again or call customer care.");
408
        }
409
        number = orderId;
410
        return search();
411
    }
412
 
413
    public String requestReturn() {
414
        try{
415
            TransactionClient tcl = new TransactionClient();
416
            if(returnType.equals("doa")) {
417
                tcl.getClient().markOrderDoaRequestReceived(orderId);
418
            } else if(returnType.equals("return")) {
419
                tcl.getClient().markOrderReturnRequestReceived(orderId);
420
            } else {
421
                setSearchError("Error in requesting return. Try Again.");
422
            }
423
        } catch (Exception e) {
424
            logger.error("Could not mark order as return requested for id : " + orderId.toString(), e);
425
            setSearchError("Request failed. Try again or call customer care.");
426
        }
427
        number = orderId;
428
        return search();
429
    }
7343 anupam.sin 430
 
431
    public List<Order> getOrders(){
432
        return orders;
433
    }
434
 
435
    public void setServletRequest(HttpServletRequest req) {
436
        this.request = req;
437
        this.session = req.getSession();        
438
    }
439
 
440
    public void setServletContext(ServletContext context) {
441
        this.context = context;
442
    }
443
 
444
    public void setServletResponse(HttpServletResponse response) {
445
        this.response = response;
446
    }
447
 
448
    public String getServletContextPath() {
449
        return context.getContextPath();
450
    }
451
 
452
    public String getProductName(LineItem item) {
453
        return item.getBrand() 
454
                + (item.getModel_name() == null ? "" : " " + item.getModel_name())
455
                + (item.getModel_number() == null ? "" : " " + item.getModel_number())
456
                + (item.getColor() == null || item.getColor() == "" ? "" : " (" + item.getColor() + ")");
457
    }
458
 
459
    public String getStartDate() {
460
        return startDate;
461
    }
462
 
463
 
464
    public void setStartDate(String startDate) {
465
        this.startDate = startDate;
466
    }
467
 
468
    public String getEndDate() {
469
        return endDate;
470
    }
471
 
472
 
473
    public void setEndDate(String endDate) {
474
        this.endDate = endDate;
475
    }
476
 
477
    public String getStatus() {
478
        return status;
479
    }
480
 
481
 
482
    public void setStatus(String status) {
483
        this.status = status;
484
    }
485
 
486
 
487
    public String getDateselector() {
488
        return dateselector;
489
    }
490
 
491
 
492
    public void setDateselector(String dateselector) {
493
        this.dateselector = dateselector;
494
    }
495
 
496
 
497
    public void setSearchError(String searchError) {
498
        this.searchError = searchError;
499
    }
500
 
501
 
502
    public String getSearchError() {
503
        return searchError;
504
    }
505
 
506
 
507
    public void setNumber(Long number) {
508
        this.number = number;
509
    }
510
 
511
 
512
    public Long getNumber() {
513
        return number;
514
    }
515
 
516
 
517
    public void setSearchResult(List<Order> searchResult) {
518
        this.searchResult = searchResult;
519
    }
520
 
521
 
522
    public List<Order> getSearchResult() {
523
        if(searchResult == null)
524
            searchResult = new ArrayList<Order>();
525
        return searchResult;
526
    }
527
 
528
 
529
    public void setShowReprintColumn(boolean showReprintColumn) {
530
        this.showReprintColumn = showReprintColumn;
531
    }
532
 
533
 
534
    public boolean shouldShowReprintColumn() {
535
        return showReprintColumn;
536
    }
537
 
538
 
539
    public void setPasswordGeneration(String passwordGeneration) {
540
        this.passwordGeneration = passwordGeneration;
541
    }
542
 
543
 
544
    public String getPasswordGeneration() {
545
        return passwordGeneration;
546
    }
7348 anupam.sin 547
 
548
 
549
    public void setOrderId(Long orderId) {
550
        this.orderId = orderId;
551
    }
552
 
553
 
554
    public Long getOrderId() {
555
        return orderId;
556
    }
557
 
558
 
559
    public void setReturnType(String returnType) {
560
        this.returnType = returnType;
561
    }
562
 
563
 
564
    public String getReturnType() {
565
        return returnType;
566
    }
7343 anupam.sin 567
 
568
 
569
 
570
}