Subversion Repositories SmartDukaan

Rev

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