Subversion Repositories SmartDukaan

Rev

Rev 7207 | 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");
7282 anupam.sin 302
	    reportSheetHeader.createCell(10).setCellValue("Refund Date");
7151 amit.gupta 303
 
304
	    int serialNo = 0;
305
 
306
	    for(RechargeTransaction transaction : rechargeTrans) {
307
	    	serialNo++;
308
	    	Row contentRow = reportSheet.createRow((short)serialNo);
309
	    	contentRow.createCell(0).setCellValue(transaction.getId());
310
	    	contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));
311
	    	contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));
312
	    	contentRow.createCell(3).setCellValue(transaction.getDeviceNum());
313
	    	contentRow.createCell(4).setCellValue(transaction.getStatus().name());
314
	    	contentRow.createCell(5).setCellValue(transaction.getAmount());
315
	    	contentRow.createCell(6).setCellValue(transaction.getDiscount());
7169 anupam.sin 316
	    	contentRow.createCell(7).setCellValue(transaction.getPaymentAmount());
317
	    	contentRow.createCell(8).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");
318
	    	contentRow.createCell(9).setCellValue(transaction.getPayMethod().name());
7282 anupam.sin 319
	    	if(transaction.getStatus() == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED) {
320
	    	    contentRow.createCell(10).setCellValue(transaction.getResponseTime());
321
	    	} else {
322
	    	    contentRow.createCell(10).setCellValue("N/A");
323
	    	}
7151 amit.gupta 324
	    }
325
	    try {
326
			wb.write(baosXLS);
327
		} catch (IOException e) {
328
			// TODO Auto-generated catch block
329
			e.printStackTrace();
330
		}
331
	    return baosXLS;
332
	}
333
 
7169 anupam.sin 334
 
335
    public String sendPassword() throws Exception {
336
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
337
        if(loginStatus == null || !loginStatus.equals("TRUE")){
338
            return "authfail";
339
        }
340
        Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
341
 
342
        char[] buf = new char[LENGTH];
343
        for (int i = 0; i < buf.length; i++) {
344
            buf[i] = chars.charAt(random.nextInt(chars.length()));
345
        }
346
        String password = new String(buf);
347
 
348
        try {
349
            TransactionClient tcl = new TransactionClient(); 
350
            HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");
351
            boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);
352
            if(!wasPasswordSet) {
353
                passwordGeneration = "FAIL";
354
                return index();
355
            }
356
            List<String> toList = new ArrayList<String>();
357
            toList.add(hotSpotStore.getEmail());
358
            HelperClient helperServiceClient = null;
359
            helperServiceClient = new HelperClient();
360
            in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
361
 
362
 
363
            Mail mail = new Mail();
364
            mail.setSubject("New Password for Saholic Recharge");
365
            mail.setTo(toList);
366
            mail.setData("Your new password is : " + password);
367
            client.sendMail(mail);
368
        } catch(Exception e) {
369
            passwordGeneration = "FAIL";
370
            logger.error("Password generation/sending failed for storeId : " + storeId, e);
371
        }
372
        passwordGeneration = "SUCCESS";
373
        return index();
374
    }
7151 amit.gupta 375
 
376
	public String getDateTime(long milliseconds) {
7082 rajveer 377
        Calendar cal = Calendar.getInstance();
378
        cal.setTimeInMillis(milliseconds);
379
        return formatter.format(cal.getTime());
380
    }
381
 
382
    public List<RechargeTransaction> getTxns(){
383
    	return txns;
384
    }
385
 
386
    public void setServletRequest(HttpServletRequest req) {
387
        this.request = req;
388
        this.session = req.getSession();        
389
    }
390
 
391
    public void setServletContext(ServletContext context) {
392
        this.context = context;
393
    }
7151 amit.gupta 394
 
395
    public void setServletResponse(HttpServletResponse response) {
396
        this.response = response;
397
    }
7082 rajveer 398
 
399
    public String getServletContextPath() {
400
        return context.getContextPath();
401
    }
7096 anupam.sin 402
 
403
    public String getOperatorName(long operatorId) {
404
        String operatorName = "";
405
        if (HomeController.getMobileProvidersMap().containsKey(operatorId)) {
406
            operatorName = HomeController.getMobileProvidersMap().get(operatorId);
407
        } else if(HomeController.getDthProvidersMap().containsKey(operatorId)) {
408
            operatorName = HomeController.getDthProvidersMap().get(operatorId);
409
        } else {
410
            operatorName = "N/A";
411
        }
412
        return operatorName;
413
    }
7151 amit.gupta 414
 
415
	public String getStartDate() {
416
		return startDate;
417
	}
418
 
419
 
420
	public void setStartDate(String startDate) {
421
		this.startDate = startDate;
422
	}
7082 rajveer 423
 
7151 amit.gupta 424
	public String getEndDate() {
425
		return endDate;
426
	}
427
 
428
 
429
	public void setEndDate(String endDate) {
430
		this.endDate = endDate;
431
	}
432
 
433
	public String getStatus() {
434
		return status;
435
	}
436
 
437
 
438
	public void setStatus(String status) {
439
		this.status = status;
440
	}
441
 
442
 
443
	public String getDateselector() {
444
		return dateselector;
445
	}
446
 
447
 
448
	public void setDateselector(String dateselector) {
449
		this.dateselector = dateselector;
450
	}
7169 anupam.sin 451
 
452
 
453
    public void setSearchError(String searchError) {
454
        this.searchError = searchError;
455
    }
456
 
457
 
458
    public String getSearchError() {
459
        return searchError;
460
    }
461
 
462
 
463
    public void setNumber(String number) {
464
        this.number = number;
465
    }
466
 
467
 
468
    public String getNumber() {
469
        return number;
470
    }
471
 
472
 
473
    public void setSearchResult(List<RechargeTransaction> searchResult) {
474
        this.searchResult = searchResult;
475
    }
476
 
477
 
478
    public List<RechargeTransaction> getSearchResult() {
479
        if(searchResult == null)
480
            searchResult = new ArrayList<RechargeTransaction>();
481
        return searchResult;
482
    }
483
 
484
 
485
    public void setShowReprintColumn(boolean showReprintColumn) {
486
        this.showReprintColumn = showReprintColumn;
487
    }
488
 
489
 
490
    public boolean shouldShowReprintColumn() {
491
        return showReprintColumn;
492
    }
493
 
494
 
495
    public void setPasswordGeneration(String passwordGeneration) {
496
        this.passwordGeneration = passwordGeneration;
497
    }
498
 
499
 
500
    public String getPasswordGeneration() {
501
        return passwordGeneration;
502
    }
7151 amit.gupta 503
 
504
 
505
 
506
}