Subversion Repositories SmartDukaan

Rev

Rev 7349 | Rev 7393 | 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
 
7386 anupam.sin 40
public class ReportController extends BaseController {
7343 anupam.sin 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(){
7386 anupam.sin 81
        super();
7343 anupam.sin 82
        try {
83
            tsc = new TransactionClient();
84
            tClient = tsc.getClient();
85
        } catch (Exception e) {
86
            logger.error("Error connecting to one of the user, order or payment service", e);
87
        }
88
    }
89
 
90
 
91
    public String index() {
7386 anupam.sin 92
      String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
93
        if(loginStatus == null || !loginStatus.equals("TRUE")){
94
            return "authfail";
95
        }
96
 
97
        storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
7343 anupam.sin 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() {
7386 anupam.sin 120
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
121
        if(loginStatus == null || !loginStatus.equals("TRUE")){
122
            return "authfail";
123
        }
7343 anupam.sin 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{
7386 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();
7386 anupam.sin 337
            //TODO : dynamically get StoreId
338
            buffer = orderClient.getStoreOrderAdvanceInvoice(number, 1);
7343 anupam.sin 339
            if(!buffer.hasArray()) {
340
                log.error("The invoice was not found for orderId : " + 1);
341
            }
342
        } catch (Exception e) {
343
            System.out.println(e.getMessage());
344
        }
345
        response.setContentType("application/pdf");
7346 anupam.sin 346
        response.setHeader("Content-disposition", "attachment; filename=advance-invoice-" + number.toString() + ".pdf");
7343 anupam.sin 347
 
348
        ServletOutputStream sos;
349
        try {
350
            sos = response.getOutputStream();
351
            sos.write(buffer.array());
352
            sos.flush();
353
        } catch (Exception e) {
354
            System.out.println("Unable to stream the invoice file");
355
        }
356
        return "index";
357
    }
358
 
359
    public String sendPassword() throws Exception {
360
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
361
        if(loginStatus == null || !loginStatus.equals("TRUE")){
362
            return "authfail";
363
        }
364
        Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
365
 
366
        char[] buf = new char[LENGTH];
367
        for (int i = 0; i < buf.length; i++) {
368
            buf[i] = chars.charAt(random.nextInt(chars.length()));
369
        }
370
        String password = new String(buf);
371
 
372
        try {
373
            TransactionClient tcl = new TransactionClient(); 
374
            HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");
375
            boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);
376
            if(!wasPasswordSet) {
377
                passwordGeneration = "FAIL";
378
                return index();
379
            }
380
            List<String> toList = new ArrayList<String>();
381
            toList.add(hotSpotStore.getEmail());
382
            HelperClient helperServiceClient = null;
383
            helperServiceClient = new HelperClient();
384
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
385
 
386
 
387
            Mail mail = new Mail();
388
            mail.setSubject("New Password for Saholic Recharge");
389
            mail.setTo(toList);
390
            mail.setData("Your new password is : " + password);
391
            client.sendMail(mail);
392
        } catch(Exception e) {
393
            passwordGeneration = "FAIL";
394
            logger.error("Password generation/sending failed for storeId : " + storeId, e);
395
        }
396
        passwordGeneration = "SUCCESS";
397
        return index();
398
    }
399
 
400
    public String getDateTime(long milliseconds) {
401
        Calendar cal = Calendar.getInstance();
402
        cal.setTimeInMillis(milliseconds);
403
        return formatter.format(cal.getTime());
404
    }
7348 anupam.sin 405
 
406
    public String cancelRequest() {
407
        try{
408
        TransactionClient tcl = new TransactionClient();
7386 anupam.sin 409
 
410
        tcl.getClient().refundOrder(orderId, "Store", "User requested for cancellation");
7348 anupam.sin 411
        } catch (Exception e) {
412
            logger.error("Could not mark order as cancellation requested for id : " + orderId.toString(), e);
413
            setSearchError("Request failed. Try again or call customer care.");
414
        }
415
        number = orderId;
416
        return search();
417
    }
418
 
419
    public String requestReturn() {
420
        try{
421
            TransactionClient tcl = new TransactionClient();
422
            if(returnType.equals("doa")) {
423
                tcl.getClient().markOrderDoaRequestReceived(orderId);
424
            } else if(returnType.equals("return")) {
425
                tcl.getClient().markOrderReturnRequestReceived(orderId);
426
            } else {
427
                setSearchError("Error in requesting return. Try Again.");
428
            }
429
        } catch (Exception e) {
430
            logger.error("Could not mark order as return requested for id : " + orderId.toString(), e);
431
            setSearchError("Request failed. Try again or call customer care.");
432
        }
433
        number = orderId;
434
        return search();
435
    }
7349 anupam.sin 436
 
437
    public String refundOrder() {
438
        number = orderId;
439
        try{
440
            TransactionClient tcl = new TransactionClient();
441
            Order order = tcl.getClient().getOrder(number);
442
            if(order.getTotal_amount() < refundAmount) {
443
                setSearchError("You cannot refund more than Rs. " + refundAmount.toString());
444
                return search();
445
            }
446
            tcl.getClient().refundOrder(orderId, "ANU", "Cancelled");
447
            setSearchError("SUCCESSFUL. Please refund Rs. " + refundAmount.toString() + " to the customer.");
448
        } catch (Exception e) {
449
            logger.error("Could not mark order as return requested for id : " + orderId.toString(), e);
450
            setSearchError("Could not refund. Try again or call customer care.");
451
        }
452
        return search();
453
    }
7343 anupam.sin 454
 
455
    public List<Order> getOrders(){
456
        return orders;
457
    }
458
 
459
    public void setServletRequest(HttpServletRequest req) {
460
        this.request = req;
461
        this.session = req.getSession();        
462
    }
463
 
464
    public void setServletContext(ServletContext context) {
465
        this.context = context;
466
    }
467
 
468
    public void setServletResponse(HttpServletResponse response) {
469
        this.response = response;
470
    }
471
 
472
    public String getServletContextPath() {
473
        return context.getContextPath();
474
    }
475
 
476
    public String getProductName(LineItem item) {
477
        return item.getBrand() 
478
                + (item.getModel_name() == null ? "" : " " + item.getModel_name())
479
                + (item.getModel_number() == null ? "" : " " + item.getModel_number())
480
                + (item.getColor() == null || item.getColor() == "" ? "" : " (" + item.getColor() + ")");
481
    }
482
 
483
    public String getStartDate() {
484
        return startDate;
485
    }
486
 
487
 
488
    public void setStartDate(String startDate) {
489
        this.startDate = startDate;
490
    }
491
 
492
    public String getEndDate() {
493
        return endDate;
494
    }
495
 
496
 
497
    public void setEndDate(String endDate) {
498
        this.endDate = endDate;
499
    }
500
 
501
    public String getStatus() {
502
        return status;
503
    }
504
 
505
 
506
    public void setStatus(String status) {
507
        this.status = status;
508
    }
509
 
510
 
511
    public String getDateselector() {
512
        return dateselector;
513
    }
514
 
515
 
516
    public void setDateselector(String dateselector) {
517
        this.dateselector = dateselector;
518
    }
519
 
520
 
521
    public void setSearchError(String searchError) {
522
        this.searchError = searchError;
523
    }
524
 
525
 
526
    public String getSearchError() {
527
        return searchError;
528
    }
529
 
530
 
531
    public void setNumber(Long number) {
532
        this.number = number;
533
    }
534
 
535
 
536
    public Long getNumber() {
537
        return number;
538
    }
539
 
540
 
541
    public void setSearchResult(List<Order> searchResult) {
542
        this.searchResult = searchResult;
543
    }
544
 
545
 
546
    public List<Order> getSearchResult() {
547
        if(searchResult == null)
548
            searchResult = new ArrayList<Order>();
549
        return searchResult;
550
    }
551
 
552
 
553
    public void setShowReprintColumn(boolean showReprintColumn) {
554
        this.showReprintColumn = showReprintColumn;
555
    }
556
 
557
 
558
    public boolean shouldShowReprintColumn() {
559
        return showReprintColumn;
560
    }
561
 
562
 
563
    public void setPasswordGeneration(String passwordGeneration) {
564
        this.passwordGeneration = passwordGeneration;
565
    }
566
 
567
 
568
    public String getPasswordGeneration() {
569
        return passwordGeneration;
570
    }
7348 anupam.sin 571
 
572
 
573
    public void setOrderId(Long orderId) {
574
        this.orderId = orderId;
575
    }
576
 
577
 
578
    public Long getOrderId() {
579
        return orderId;
580
    }
581
 
582
 
583
    public void setReturnType(String returnType) {
584
        this.returnType = returnType;
585
    }
586
 
587
 
588
    public String getReturnType() {
589
        return returnType;
590
    }
7349 anupam.sin 591
 
592
 
593
    public void setRefundAmount(Long refundAmount) {
594
        this.refundAmount = refundAmount;
595
    }
596
 
597
 
598
    public Long getRefundAmount() {
599
        return refundAmount;
600
    }
7343 anupam.sin 601
 
7386 anupam.sin 602
    public boolean isOrderPlacedOnSameDay(long orderTime) {
603
        Calendar calOrderDate = Calendar.getInstance();
604
        calOrderDate.setTimeInMillis(orderTime);
605
 
606
        Calendar cal = Calendar.getInstance();
607
        if(cal.get(Calendar.DATE) == calOrderDate.get(Calendar.DATE) 
608
                && cal.get(Calendar.MONTH) == calOrderDate.get(Calendar.MONTH)
609
                && cal.get(Calendar.YEAR) == calOrderDate.get(Calendar.YEAR)) {
610
            return true;
611
        }
612
        return false;
613
    }
7343 anupam.sin 614
 
615
}