Subversion Repositories SmartDukaan

Rev

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