Subversion Repositories SmartDukaan

Rev

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