Subversion Repositories SmartDukaan

Rev

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