Subversion Repositories SmartDukaan

Rev

Rev 7178 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
7082 rajveer 1
package in.shop2020.recharge.controllers;
2
 
3
 
7169 anupam.sin 4
import in.shop2020.model.v1.order.HotspotStore;
7082 rajveer 5
import in.shop2020.model.v1.order.RechargeOrderStatus;
6
import in.shop2020.model.v1.order.RechargeTransaction;
7169 anupam.sin 7
import in.shop2020.thrift.clients.HelperClient;
7082 rajveer 8
import in.shop2020.thrift.clients.TransactionClient;
7169 anupam.sin 9
import in.shop2020.utils.Mail;
7082 rajveer 10
 
7151 amit.gupta 11
import java.io.ByteArrayOutputStream;
12
import java.io.IOException;
7082 rajveer 13
import java.text.DateFormat;
14
import java.text.SimpleDateFormat;
7169 anupam.sin 15
import java.util.ArrayList;
7082 rajveer 16
import java.util.Calendar;
7151 amit.gupta 17
import java.util.Date;
7082 rajveer 18
import java.util.List;
7169 anupam.sin 19
import java.util.Random;
7082 rajveer 20
 
21
import javax.servlet.ServletContext;
7151 amit.gupta 22
import javax.servlet.ServletOutputStream;
7082 rajveer 23
import javax.servlet.http.HttpServletRequest;
7151 amit.gupta 24
import javax.servlet.http.HttpServletResponse;
7082 rajveer 25
import javax.servlet.http.HttpSession;
26
 
7151 amit.gupta 27
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
28
import org.apache.poi.ss.usermodel.Row;
29
import org.apache.poi.ss.usermodel.Sheet;
30
import org.apache.poi.ss.usermodel.Workbook;
7082 rajveer 31
import org.apache.struts2.interceptor.ServletRequestAware;
7151 amit.gupta 32
import org.apache.struts2.interceptor.ServletResponseAware;
7082 rajveer 33
import org.apache.struts2.util.ServletContextAware;
34
import org.slf4j.Logger;
35
import org.slf4j.LoggerFactory;
36
 
37
 
38
 
7207 anupam.sin 39
public class ReportController  extends BaseController {
7151 amit.gupta 40
 
7207 anupam.sin 41
    /**
42
     * 
43
     */
44
    private static final long serialVersionUID = 1L;
45
 
7082 rajveer 46
    private static Logger logger = LoggerFactory.getLogger(ReportController.class);
47
 
7151 amit.gupta 48
    protected HttpServletRequest request;
49
    protected HttpSession session;
50
    protected HttpServletResponse response;
7082 rajveer 51
    private ServletContext context;
7151 amit.gupta 52
    private String startDate;
53
	private String endDate;
54
	private String status;
55
	private String dateselector;
7169 anupam.sin 56
	private String searchError = "";
57
	private String number = "";
58
	private String passwordGeneration = "";
7151 amit.gupta 59
 
7169 anupam.sin 60
	private static final String chars = "0123456789";
61
	private static final int LENGTH = 4;
62
	private static final Random random = new Random();
7082 rajveer 63
	private TransactionClient tsc;
64
    private in.shop2020.model.v1.order.TransactionService.Client tClient;
65
 
66
    private final DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");
7151 amit.gupta 67
    private final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
7178 anupam.sin 68
    private final DateFormat df4Filename = new SimpleDateFormat("EEE_dd_MMM");
7082 rajveer 69
 
70
    private List<RechargeTransaction> txns = null;
7169 anupam.sin 71
    private List<RechargeTransaction> searchResult = null;
72
 
73
    private boolean showReprintColumn = false;
74
 
7082 rajveer 75
    public ReportController(){
76
	    try {
77
            tsc = new TransactionClient();
78
            tClient = tsc.getClient();
79
        } catch (Exception e) {
80
            logger.error("Error connecting to one of the user, order or payment service", e);
81
        }
82
	}
83
 
84
 
7207 anupam.sin 85
	public String index() {
7096 anupam.sin 86
	    String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
87
        if(loginStatus == null || !loginStatus.equals("TRUE")){
88
            return "authfail";
89
        }
7207 anupam.sin 90
 
91
        storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
92
        if(!hotspotStores.containsKey(storeId)){
93
            try{
94
                HotspotStore hotSpotStore = (new TransactionClient()).getClient().getHotspotStore(storeId, "");
95
                hotspotStores.put(storeId, hotSpotStore);
96
            } catch (Exception e) {
97
                logger.error("Unable to get store", e);
98
            }
99
        }
100
 
7174 anupam.sin 101
        long today = -1;
102
        today = new Date().getTime();
7207 anupam.sin 103
        try {
104
            txns = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, null);
105
        } catch (Exception e) {
106
            setSearchError("Error getting all transactions for today. Please try again.");
107
            logger.error("Unable to get all Transactions for today", e);
108
        }
7082 rajveer 109
        return "index";
110
	}
111
 
7169 anupam.sin 112
	public String search() throws Exception {
113
	    String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
114
        if(loginStatus == null || !loginStatus.equals("TRUE")){
115
            return "authfail";
116
        }
117
	    if(number != null && !number.equals("")) {
118
	        try {
7172 anupam.sin 119
	            setSearchResult(tClient.getRechargeTransactionsByNumber(number.trim(), Long.parseLong((String) request.getSession().getAttribute("STORE_ID"))));
7169 anupam.sin 120
	            if(searchResult.size() == 0) {
121
	                setSearchError("Could not find any recharges with this number. Please try again.");
122
	            }
123
	            for(RechargeTransaction txn : getSearchResult()) {
124
	                if(txn.getStatus().equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)) {
125
	                    setShowReprintColumn(true);
126
	                    break;
127
	                }
128
	            }
129
	        } catch(Exception e) {
130
	            setSearchError("Some error occured. Please try again.");
131
	            logger.error("Error during search", e);
132
	        }
133
	    }
134
        return index();
135
	}
136
 
137
	public String getCollection() throws Exception{
138
	    String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
139
        if(loginStatus == null || !loginStatus.equals("TRUE")){
140
            return "authfail";
141
        }
142
	    long today = -1;
143
	    today = new Date().getTime();
144
	    List<RechargeTransaction> successfulRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_SUCCESSFUL);
145
	    List<RechargeTransaction> refundedRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED);
146
	    ByteArrayOutputStream baos = generateCollectionReport(successfulRecharges, refundedRecharges);
147
	    response.setContentType("application/vnd.ms-excel");
148
        String fileName = "collection-report";
7178 anupam.sin 149
        String todayDate = df4Filename.format(new Date(today));
150
        fileName = fileName + "-" + todayDate;
7169 anupam.sin 151
        fileName = fileName + ".xls";
152
        response.setHeader("Content-disposition", "inline; filename=" + fileName);
153
        ServletOutputStream sos;
154
        try {
155
            sos = response.getOutputStream();
156
            baos.writeTo(sos);
157
            sos.flush();
158
        } catch (IOException e) {
159
            e.printStackTrace();
160
        }
161
        return null;
162
 
163
	}
164
 
165
	private ByteArrayOutputStream generateCollectionReport(List<RechargeTransaction> successfulRecharges,
166
                                                            List<RechargeTransaction> refundedRecharges) {
167
	    ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
168
        Workbook wb = new HSSFWorkbook();
169
        Sheet reportSheet = wb.createSheet("Recharge Report");
170
        Row reportSheetHeader = reportSheet.createRow((short)0);
171
        reportSheetHeader.createCell(0).setCellValue("Order ID");
172
        reportSheetHeader.createCell(1).setCellValue("Order Date");
173
        reportSheetHeader.createCell(2).setCellValue("Operator");
174
        reportSheetHeader.createCell(3).setCellValue("Device Number");
175
        reportSheetHeader.createCell(4).setCellValue("Status");
176
        reportSheetHeader.createCell(5).setCellValue("Pay Method");
177
        reportSheetHeader.createCell(6).setCellValue("Refund Date");
178
        reportSheetHeader.createCell(7).setCellValue("Type");
179
        reportSheetHeader.createCell(8).setCellValue("Total Amount");
180
        reportSheetHeader.createCell(9).setCellValue("Discount");
181
        reportSheetHeader.createCell(10).setCellValue("Net Amount");
182
 
183
        int serialNo = 0;
184
 
185
        for(RechargeTransaction transaction : successfulRecharges) {
186
            serialNo++;
187
            Row contentRow = reportSheet.createRow((short)serialNo);
188
            contentRow.createCell(0).setCellValue(transaction.getId());
189
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
190
            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
191
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
192
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
193
            contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());
194
            contentRow.createCell(6).setCellValue("N/A");
195
            contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
196
            contentRow.createCell(8).setCellValue(transaction.getAmount());
197
            contentRow.createCell(9).setCellValue(transaction.getDiscount());
198
            contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());
199
        }
200
 
201
        for(RechargeTransaction transaction : refundedRecharges) {
202
            serialNo++;
203
            Row contentRow = reportSheet.createRow((short)serialNo);
204
            contentRow.createCell(0).setCellValue(transaction.getId());
205
            contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
206
            contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
207
            contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
208
            contentRow.createCell(4).setCellValue(transaction.getStatus().name());
209
            contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());
210
            contentRow.createCell(6).setCellValue(formatter.format(new Date(transaction.getResponseTime())));
211
            contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
212
            contentRow.createCell(8).setCellValue(transaction.getAmount());
213
            contentRow.createCell(9).setCellValue(transaction.getDiscount());
214
            contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());
215
        }
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
 
7151 amit.gupta 227
	public String create() throws Exception{
228
		long sDate = -1;
229
		long eDate = -1;
230
		RechargeOrderStatus st = null;
231
		String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
232
		if(loginStatus == null || !loginStatus.equals("TRUE")){
233
			return "authfail";
234
		}
235
		if(dateselector.equals("1")) {
236
			sDate = new Date().getTime();
237
			eDate = sDate;
238
		}else if (dateselector.equals("2")) {
239
			sDate = new Date().getTime() - 86400*1000;
240
			eDate = sDate;
241
		}else {
242
			if(!(startDate.equals(""))) {
243
				sDate = dateFormatter.parse(startDate).getTime();
244
				startDate = dateFormatter.format(sDate);
245
			}
246
			if(!endDate.equals("")) {
247
				eDate = dateFormatter.parse(endDate).getTime();
248
				endDate = dateFormatter.format(sDate);
249
			}
250
		}
251
		if(!status.equals("-1")){
7174 anupam.sin 252
			st = RechargeOrderStatus.findByValue(Integer.parseInt(status));
7151 amit.gupta 253
		}
254
 
255
		ByteArrayOutputStream baos = generateReport(tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate, st));
256
 
257
		response.setContentType("application/vnd.ms-excel");
258
		String st1 = "ALL";
259
		if(st!=null){
260
			st1 = st.name();
261
		}
262
		String fileName = st1 + "-recharge-report";
263
		if (!startDate.equals("")) {
7178 anupam.sin 264
			fileName = fileName + "-" + startDate.replaceAll("\\\\", "_") ;
7151 amit.gupta 265
		}
266
		if (!endDate.equals("")) {
7178 anupam.sin 267
			fileName = fileName + "-" + endDate.replaceAll("\\\\", "_") ;
7151 amit.gupta 268
		}
269
		fileName = fileName + ".xls";
270
		response.setHeader("Content-disposition", "inline; filename=" + fileName);
271
        ServletOutputStream sos;
272
        try {
273
            sos = response.getOutputStream();
274
            baos.writeTo(sos);
275
            sos.flush();
276
        } catch (IOException e) {
277
            e.printStackTrace();
278
        }
279
		return "index";
280
	}
281
 
7082 rajveer 282
 
7151 amit.gupta 283
    private ByteArrayOutputStream generateReport(
284
			List<RechargeTransaction> rechargeTrans) {
285
ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
286
 
287
	    Workbook wb = new HSSFWorkbook();
288
 
289
	    Sheet reportSheet = wb.createSheet("Recharge Report");
290
 
291
	    Row reportSheetHeader = reportSheet.createRow((short)0);
292
	    reportSheetHeader.createCell(0).setCellValue("Order ID");
293
	    reportSheetHeader.createCell(1).setCellValue("Order Date");
294
	    reportSheetHeader.createCell(2).setCellValue("Operator");
295
	    reportSheetHeader.createCell(3).setCellValue("Device");
296
	    reportSheetHeader.createCell(4).setCellValue("Status");
7169 anupam.sin 297
	    reportSheetHeader.createCell(5).setCellValue("Recharge Amount");
7151 amit.gupta 298
	    reportSheetHeader.createCell(6).setCellValue("Discount");
7169 anupam.sin 299
	    reportSheetHeader.createCell(7).setCellValue("Net Amount");
300
	    reportSheetHeader.createCell(8).setCellValue("Type");
301
	    reportSheetHeader.createCell(9).setCellValue("Pay Method");
7151 amit.gupta 302
 
303
	    int serialNo = 0;
304
 
305
	    for(RechargeTransaction transaction : rechargeTrans) {
306
	    	serialNo++;
307
	    	Row contentRow = reportSheet.createRow((short)serialNo);
308
	    	contentRow.createCell(0).setCellValue(transaction.getId());
309
	    	contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
310
	    	contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
311
	    	contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
312
	    	contentRow.createCell(4).setCellValue(transaction.getStatus().name());
313
	    	contentRow.createCell(5).setCellValue(transaction.getAmount());
314
	    	contentRow.createCell(6).setCellValue(transaction.getDiscount());
7169 anupam.sin 315
	    	contentRow.createCell(7).setCellValue(transaction.getPaymentAmount());
316
	    	contentRow.createCell(8).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
317
	    	contentRow.createCell(9).setCellValue(transaction.getPayMethod().name());
7151 amit.gupta 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
 
7169 anupam.sin 328
 
329
    public String sendPassword() throws Exception {
330
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
331
        if(loginStatus == null || !loginStatus.equals("TRUE")){
332
            return "authfail";
333
        }
334
        Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
335
 
336
        char[] buf = new char[LENGTH];
337
        for (int i = 0; i < buf.length; i++) {
338
            buf[i] = chars.charAt(random.nextInt(chars.length()));
339
        }
340
        String password = new String(buf);
341
 
342
        try {
343
            TransactionClient tcl = new TransactionClient(); 
344
            HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");
345
            boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);
346
            if(!wasPasswordSet) {
347
                passwordGeneration = "FAIL";
348
                return index();
349
            }
350
            List<String> toList = new ArrayList<String>();
351
            toList.add(hotSpotStore.getEmail());
352
            HelperClient helperServiceClient = null;
353
            helperServiceClient = new HelperClient();
354
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
355
 
356
 
357
            Mail mail = new Mail();
358
            mail.setSubject("New Password for Saholic Recharge");
359
            mail.setTo(toList);
360
            mail.setData("Your new password is : " + password);
361
            client.sendMail(mail);
362
        } catch(Exception e) {
363
            passwordGeneration = "FAIL";
364
            logger.error("Password generation/sending failed for storeId : " + storeId, e);
365
        }
366
        passwordGeneration = "SUCCESS";
367
        return index();
368
    }
7151 amit.gupta 369
 
370
	public String getDateTime(long milliseconds) {
7082 rajveer 371
        Calendar cal = Calendar.getInstance();
372
        cal.setTimeInMillis(milliseconds);
373
        return formatter.format(cal.getTime());
374
    }
375
 
376
    public List<RechargeTransaction> getTxns(){
377
    	return txns;
378
    }
379
 
380
    public void setServletRequest(HttpServletRequest req) {
381
        this.request = req;
382
        this.session = req.getSession();        
383
    }
384
 
385
    public void setServletContext(ServletContext context) {
386
        this.context = context;
387
    }
7151 amit.gupta 388
 
389
    public void setServletResponse(HttpServletResponse response) {
390
        this.response = response;
391
    }
7082 rajveer 392
 
393
    public String getServletContextPath() {
394
        return context.getContextPath();
395
    }
7096 anupam.sin 396
 
397
    public String getOperatorName(long operatorId) {
398
        String operatorName = "";
399
        if (HomeController.getMobileProvidersMap().containsKey(operatorId)) {
400
            operatorName = HomeController.getMobileProvidersMap().get(operatorId);
401
        } else if(HomeController.getDthProvidersMap().containsKey(operatorId)) {
402
            operatorName = HomeController.getDthProvidersMap().get(operatorId);
403
        } else {
404
            operatorName = "N/A";
405
        }
406
        return operatorName;
407
    }
7151 amit.gupta 408
 
409
	public String getStartDate() {
410
		return startDate;
411
	}
412
 
413
 
414
	public void setStartDate(String startDate) {
415
		this.startDate = startDate;
416
	}
7082 rajveer 417
 
7151 amit.gupta 418
	public String getEndDate() {
419
		return endDate;
420
	}
421
 
422
 
423
	public void setEndDate(String endDate) {
424
		this.endDate = endDate;
425
	}
426
 
427
	public String getStatus() {
428
		return status;
429
	}
430
 
431
 
432
	public void setStatus(String status) {
433
		this.status = status;
434
	}
435
 
436
 
437
	public String getDateselector() {
438
		return dateselector;
439
	}
440
 
441
 
442
	public void setDateselector(String dateselector) {
443
		this.dateselector = dateselector;
444
	}
7169 anupam.sin 445
 
446
 
447
    public void setSearchError(String searchError) {
448
        this.searchError = searchError;
449
    }
450
 
451
 
452
    public String getSearchError() {
453
        return searchError;
454
    }
455
 
456
 
457
    public void setNumber(String number) {
458
        this.number = number;
459
    }
460
 
461
 
462
    public String getNumber() {
463
        return number;
464
    }
465
 
466
 
467
    public void setSearchResult(List<RechargeTransaction> searchResult) {
468
        this.searchResult = searchResult;
469
    }
470
 
471
 
472
    public List<RechargeTransaction> getSearchResult() {
473
        if(searchResult == null)
474
            searchResult = new ArrayList<RechargeTransaction>();
475
        return searchResult;
476
    }
477
 
478
 
479
    public void setShowReprintColumn(boolean showReprintColumn) {
480
        this.showReprintColumn = showReprintColumn;
481
    }
482
 
483
 
484
    public boolean shouldShowReprintColumn() {
485
        return showReprintColumn;
486
    }
487
 
488
 
489
    public void setPasswordGeneration(String passwordGeneration) {
490
        this.passwordGeneration = passwordGeneration;
491
    }
492
 
493
 
494
    public String getPasswordGeneration() {
495
        return passwordGeneration;
496
    }
7151 amit.gupta 497
 
498
 
499
 
500
}