Subversion Repositories SmartDukaan

Rev

Rev 7343 | Rev 7348 | 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;
36
import org.apache.struts2.interceptor.ServletRequestAware;
37
import org.apache.struts2.interceptor.ServletResponseAware;
38
import org.apache.struts2.util.ServletContextAware;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41
 
42
 
43
 
44
public class ReportController  extends BaseController {
45
 
46
    /**
47
     * 
48
     */
49
    private static final long serialVersionUID = 1L;
50
 
51
    private static Logger logger = LoggerFactory.getLogger(ReportController.class);
52
 
53
    protected HttpServletRequest request;
54
    protected HttpSession session;
55
    protected HttpServletResponse response;
56
    private ServletContext context;
57
    private String startDate;
58
    private String endDate;
59
    private String status;
60
    private String dateselector;
61
    private String searchError = "";
62
    private Long number = null;
63
    private String passwordGeneration = "";
64
 
65
    private static final String chars = "0123456789";
66
    private static final int LENGTH = 4;
67
    private static final Random random = new Random();
68
    private TransactionClient tsc;
69
    private in.shop2020.model.v1.order.TransactionService.Client tClient;
70
 
71
    private final DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
72
    private final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
73
    private final DateFormat df4Filename = new SimpleDateFormat("EEE_dd_MMM");
74
 
75
    private List<Order> orders = null;
76
    private List<Order> searchResult = null;
77
 
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
 
119
    public String search() throws Exception {
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);
148
        orders = tClient.getOrdersForStore(0, 1, today, today, statuses);
7343 anupam.sin 149
        List<RechargeTransaction> successfulRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_SUCCESSFUL);
150
        List<RechargeTransaction> refundedRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED);
151
        ByteArrayOutputStream baos = generateCollectionReport(successfulRecharges, refundedRecharges);
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
 
170
    private ByteArrayOutputStream generateCollectionReport(List<RechargeTransaction> successfulRecharges,
171
                                                            List<RechargeTransaction> refundedRecharges) {
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");
178
        reportSheetHeader.createCell(2).setCellValue("Operator");
179
        reportSheetHeader.createCell(3).setCellValue("Device Number");
180
        reportSheetHeader.createCell(4).setCellValue("Status");
181
        reportSheetHeader.createCell(5).setCellValue("Pay Method");
182
        reportSheetHeader.createCell(6).setCellValue("Refund Date");
183
        reportSheetHeader.createCell(7).setCellValue("Type");
184
        reportSheetHeader.createCell(8).setCellValue("Total Amount");
185
        reportSheetHeader.createCell(9).setCellValue("Discount");
186
        reportSheetHeader.createCell(10).setCellValue("Net Amount");
187
 
188
        int serialNo = 0;
189
 
190
        for(RechargeTransaction transaction : successfulRecharges) {
191
            serialNo++;
192
            Row contentRow = reportSheet.createRow((short)serialNo);
193
            contentRow.createCell(0).setCellValue(transaction.getId());
194
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
195
//            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
196
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
197
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
198
            contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());
199
            contentRow.createCell(6).setCellValue("N/A");
200
            contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
201
            contentRow.createCell(8).setCellValue(transaction.getAmount());
202
            contentRow.createCell(9).setCellValue(transaction.getDiscount());
203
            contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());
204
        }
205
 
206
        for(RechargeTransaction transaction : refundedRecharges) {
207
            serialNo++;
208
            Row contentRow = reportSheet.createRow((short)serialNo);
209
            contentRow.createCell(0).setCellValue(transaction.getId());
210
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
211
//            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
212
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
213
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
214
            contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());
215
            contentRow.createCell(6).setCellValue(formatter.format(new Date(transaction.getResponseTime())));
216
            contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
217
            contentRow.createCell(8).setCellValue(transaction.getAmount());
218
            contentRow.createCell(9).setCellValue(transaction.getDiscount());
219
            contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());
220
        }
221
 
222
        try {
223
            wb.write(baosXLS);
224
        } catch (IOException e) {
225
            // TODO Auto-generated catch block
226
            e.printStackTrace();
227
        }
228
        return baosXLS;
229
    }
230
 
231
 
232
    public String create() throws Exception{
233
        long sDate = -1;
234
        long eDate = -1;
235
        RechargeOrderStatus st = null;
236
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
237
        if(loginStatus == null || !loginStatus.equals("TRUE")){
238
            return "authfail";
239
        }
240
        if(dateselector.equals("1")) {
241
            sDate = new Date().getTime();
242
            eDate = sDate;
243
        }else if (dateselector.equals("2")) {
244
            sDate = new Date().getTime() - 86400*1000;
245
            eDate = sDate;
246
        }else {
247
            if(!(startDate.equals(""))) {
248
                sDate = dateFormatter.parse(startDate).getTime();
249
                startDate = dateFormatter.format(sDate);
250
            }
251
            if(!endDate.equals("")) {
252
                eDate = dateFormatter.parse(endDate).getTime();
253
                endDate = dateFormatter.format(sDate);
254
            }
255
        }
256
        if(!status.equals("-1")){
257
            st = RechargeOrderStatus.findByValue(Integer.parseInt(status));
258
        }
259
 
260
        ByteArrayOutputStream baos = generateReport(tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate, st));
261
 
262
        response.setContentType("application/vnd.ms-excel");
263
        String st1 = "ALL";
264
        if(st!=null){
265
            st1 = st.name();
266
        }
267
        String fileName = st1 + "-recharge-report";
268
        if (!startDate.equals("")) {
269
            fileName = fileName + "-" + startDate.replaceAll("\\\\", "_") ;
270
        }
271
        if (!endDate.equals("")) {
272
            fileName = fileName + "-" + endDate.replaceAll("\\\\", "_") ;
273
        }
274
        fileName = fileName + ".xls";
275
        response.setHeader("Content-disposition", "inline; filename=" + fileName);
276
        ServletOutputStream sos;
277
        try {
278
            sos = response.getOutputStream();
279
            baos.writeTo(sos);
280
            sos.flush();
281
        } catch (IOException e) {
282
            e.printStackTrace();
283
        }
284
        return "index";
285
    }
286
 
287
 
288
    private ByteArrayOutputStream generateReport(
289
            List<RechargeTransaction> rechargeTrans) {
290
ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
291
 
292
        Workbook wb = new HSSFWorkbook();
293
 
294
        Sheet reportSheet = wb.createSheet("Recharge Report");
295
 
296
        Row reportSheetHeader = reportSheet.createRow((short)0);
297
        reportSheetHeader.createCell(0).setCellValue("Order ID");
298
        reportSheetHeader.createCell(1).setCellValue("Order Date");
299
        reportSheetHeader.createCell(2).setCellValue("Operator");
300
        reportSheetHeader.createCell(3).setCellValue("Device");
301
        reportSheetHeader.createCell(4).setCellValue("Status");
302
        reportSheetHeader.createCell(5).setCellValue("Recharge Amount");
303
        reportSheetHeader.createCell(6).setCellValue("Discount");
304
        reportSheetHeader.createCell(7).setCellValue("Net Amount");
305
        reportSheetHeader.createCell(8).setCellValue("Type");
306
        reportSheetHeader.createCell(9).setCellValue("Pay Method");
307
        reportSheetHeader.createCell(10).setCellValue("Refund Date");
308
 
309
        int serialNo = 0;
310
 
311
        for(RechargeTransaction transaction : rechargeTrans) {
312
            serialNo++;
313
            Row contentRow = reportSheet.createRow((short)serialNo);
314
            contentRow.createCell(0).setCellValue(transaction.getId());
315
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
316
//            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
317
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
318
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
319
            contentRow.createCell(5).setCellValue(transaction.getAmount());
320
            contentRow.createCell(6).setCellValue(transaction.getDiscount());
321
            contentRow.createCell(7).setCellValue(transaction.getPaymentAmount());
322
            contentRow.createCell(8).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
323
            contentRow.createCell(9).setCellValue(transaction.getPayMethod().name());
324
            if(transaction.getStatus() == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED) {
325
                contentRow.createCell(10).setCellValue(transaction.getResponseTime());
326
            } else {
327
                contentRow.createCell(10).setCellValue("N/A");
328
            }
329
        }
330
        try {
331
            wb.write(baosXLS);
332
        } catch (IOException e) {
333
            // TODO Auto-generated catch block
334
            e.printStackTrace();
335
        }
336
        return baosXLS;
337
    }
338
 
339
    public String downloadInvoice() {
340
        ByteBuffer buffer = null;
341
        try {
342
            if (number == null || number == 0) {
343
                log.error("rechargeId is 0");
344
                return "index";
345
            }
346
            TransactionClient transactionServiceClient = new TransactionClient();
347
            TransactionService.Client orderClient = transactionServiceClient.getClient();
348
            buffer = orderClient.getStoreOrderAdvanceInvoice(number);
349
            if(!buffer.hasArray()) {
350
                log.error("The invoice was not found for orderId : " + 1);
351
            }
352
        } catch (Exception e) {
353
            System.out.println(e.getMessage());
354
        }
355
        response.setContentType("application/pdf");
7346 anupam.sin 356
        response.setHeader("Content-disposition", "attachment; filename=advance-invoice-" + number.toString() + ".pdf");
7343 anupam.sin 357
 
358
        ServletOutputStream sos;
359
        try {
360
            sos = response.getOutputStream();
361
            sos.write(buffer.array());
362
            sos.flush();
363
        } catch (Exception e) {
364
            System.out.println("Unable to stream the invoice file");
365
        }
366
        return "index";
367
    }
368
 
369
    public String sendPassword() throws Exception {
370
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
371
        if(loginStatus == null || !loginStatus.equals("TRUE")){
372
            return "authfail";
373
        }
374
        Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
375
 
376
        char[] buf = new char[LENGTH];
377
        for (int i = 0; i < buf.length; i++) {
378
            buf[i] = chars.charAt(random.nextInt(chars.length()));
379
        }
380
        String password = new String(buf);
381
 
382
        try {
383
            TransactionClient tcl = new TransactionClient(); 
384
            HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");
385
            boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);
386
            if(!wasPasswordSet) {
387
                passwordGeneration = "FAIL";
388
                return index();
389
            }
390
            List<String> toList = new ArrayList<String>();
391
            toList.add(hotSpotStore.getEmail());
392
            HelperClient helperServiceClient = null;
393
            helperServiceClient = new HelperClient();
394
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
395
 
396
 
397
            Mail mail = new Mail();
398
            mail.setSubject("New Password for Saholic Recharge");
399
            mail.setTo(toList);
400
            mail.setData("Your new password is : " + password);
401
            client.sendMail(mail);
402
        } catch(Exception e) {
403
            passwordGeneration = "FAIL";
404
            logger.error("Password generation/sending failed for storeId : " + storeId, e);
405
        }
406
        passwordGeneration = "SUCCESS";
407
        return index();
408
    }
409
 
410
    public String getDateTime(long milliseconds) {
411
        Calendar cal = Calendar.getInstance();
412
        cal.setTimeInMillis(milliseconds);
413
        return formatter.format(cal.getTime());
414
    }
415
 
416
    public List<Order> getOrders(){
417
        return orders;
418
    }
419
 
420
    public void setServletRequest(HttpServletRequest req) {
421
        this.request = req;
422
        this.session = req.getSession();        
423
    }
424
 
425
    public void setServletContext(ServletContext context) {
426
        this.context = context;
427
    }
428
 
429
    public void setServletResponse(HttpServletResponse response) {
430
        this.response = response;
431
    }
432
 
433
    public String getServletContextPath() {
434
        return context.getContextPath();
435
    }
436
 
437
    public String getProductName(LineItem item) {
438
        return item.getBrand() 
439
                + (item.getModel_name() == null ? "" : " " + item.getModel_name())
440
                + (item.getModel_number() == null ? "" : " " + item.getModel_number())
441
                + (item.getColor() == null || item.getColor() == "" ? "" : " (" + item.getColor() + ")");
442
    }
443
 
444
    public String getStartDate() {
445
        return startDate;
446
    }
447
 
448
 
449
    public void setStartDate(String startDate) {
450
        this.startDate = startDate;
451
    }
452
 
453
    public String getEndDate() {
454
        return endDate;
455
    }
456
 
457
 
458
    public void setEndDate(String endDate) {
459
        this.endDate = endDate;
460
    }
461
 
462
    public String getStatus() {
463
        return status;
464
    }
465
 
466
 
467
    public void setStatus(String status) {
468
        this.status = status;
469
    }
470
 
471
 
472
    public String getDateselector() {
473
        return dateselector;
474
    }
475
 
476
 
477
    public void setDateselector(String dateselector) {
478
        this.dateselector = dateselector;
479
    }
480
 
481
 
482
    public void setSearchError(String searchError) {
483
        this.searchError = searchError;
484
    }
485
 
486
 
487
    public String getSearchError() {
488
        return searchError;
489
    }
490
 
491
 
492
    public void setNumber(Long number) {
493
        this.number = number;
494
    }
495
 
496
 
497
    public Long getNumber() {
498
        return number;
499
    }
500
 
501
 
502
    public void setSearchResult(List<Order> searchResult) {
503
        this.searchResult = searchResult;
504
    }
505
 
506
 
507
    public List<Order> getSearchResult() {
508
        if(searchResult == null)
509
            searchResult = new ArrayList<Order>();
510
        return searchResult;
511
    }
512
 
513
 
514
    public void setShowReprintColumn(boolean showReprintColumn) {
515
        this.showReprintColumn = showReprintColumn;
516
    }
517
 
518
 
519
    public boolean shouldShowReprintColumn() {
520
        return showReprintColumn;
521
    }
522
 
523
 
524
    public void setPasswordGeneration(String passwordGeneration) {
525
        this.passwordGeneration = passwordGeneration;
526
    }
527
 
528
 
529
    public String getPasswordGeneration() {
530
        return passwordGeneration;
531
    }
532
 
533
 
534
 
535
}