Rev 7207 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.recharge.controllers;import in.shop2020.model.v1.order.HotspotStore;import in.shop2020.model.v1.order.RechargeOrderStatus;import in.shop2020.model.v1.order.RechargeTransaction;import in.shop2020.thrift.clients.HelperClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.utils.Mail;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.Random;import javax.servlet.ServletContext;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;import org.apache.struts2.util.ServletContextAware;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class ReportController extends BaseController {/****/private static final long serialVersionUID = 1L;private static Logger logger = LoggerFactory.getLogger(ReportController.class);protected HttpServletRequest request;protected HttpSession session;protected HttpServletResponse response;private ServletContext context;private String startDate;private String endDate;private String status;private String dateselector;private String searchError = "";private String number = "";private String passwordGeneration = "";private static final String chars = "0123456789";private static final int LENGTH = 4;private static final Random random = new Random();private TransactionClient tsc;private in.shop2020.model.v1.order.TransactionService.Client tClient;private final DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");private final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");private final DateFormat df4Filename = new SimpleDateFormat("EEE_dd_MMM");private List<RechargeTransaction> txns = null;private List<RechargeTransaction> searchResult = null;private boolean showReprintColumn = false;public ReportController(){try {tsc = new TransactionClient();tClient = tsc.getClient();} catch (Exception e) {logger.error("Error connecting to one of the user, order or payment service", e);}}public String index() {String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");if(loginStatus == null || !loginStatus.equals("TRUE")){return "authfail";}storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));if(!hotspotStores.containsKey(storeId)){try{HotspotStore hotSpotStore = (new TransactionClient()).getClient().getHotspotStore(storeId, "");hotspotStores.put(storeId, hotSpotStore);} catch (Exception e) {logger.error("Unable to get store", e);}}long today = -1;today = new Date().getTime();try {txns = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, null);} catch (Exception e) {setSearchError("Error getting all transactions for today. Please try again.");logger.error("Unable to get all Transactions for today", e);}return "index";}public String search() throws Exception {String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");if(loginStatus == null || !loginStatus.equals("TRUE")){return "authfail";}if(number != null && !number.equals("")) {try {setSearchResult(tClient.getRechargeTransactionsByNumber(number.trim(), Long.parseLong((String) request.getSession().getAttribute("STORE_ID"))));if(searchResult.size() == 0) {setSearchError("Could not find any recharges with this number. Please try again.");}for(RechargeTransaction txn : getSearchResult()) {if(txn.getStatus().equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)) {setShowReprintColumn(true);break;}}} catch(Exception e) {setSearchError("Some error occured. Please try again.");logger.error("Error during search", e);}}return index();}public String getCollection() throws Exception{String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");if(loginStatus == null || !loginStatus.equals("TRUE")){return "authfail";}long today = -1;today = new Date().getTime();List<RechargeTransaction> successfulRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_SUCCESSFUL);List<RechargeTransaction> refundedRecharges = tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), today, today, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED);ByteArrayOutputStream baos = generateCollectionReport(successfulRecharges, refundedRecharges);response.setContentType("application/vnd.ms-excel");String fileName = "collection-report";String todayDate = df4Filename.format(new Date(today));fileName = fileName + "-" + todayDate;fileName = fileName + ".xls";response.setHeader("Content-disposition", "inline; filename=" + fileName);ServletOutputStream sos;try {sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {e.printStackTrace();}return null;}private ByteArrayOutputStream generateCollectionReport(List<RechargeTransaction> successfulRecharges,List<RechargeTransaction> refundedRecharges) {ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();Workbook wb = new HSSFWorkbook();Sheet reportSheet = wb.createSheet("Recharge Report");Row reportSheetHeader = reportSheet.createRow((short)0);reportSheetHeader.createCell(0).setCellValue("Order ID");reportSheetHeader.createCell(1).setCellValue("Order Date");reportSheetHeader.createCell(2).setCellValue("Operator");reportSheetHeader.createCell(3).setCellValue("Device Number");reportSheetHeader.createCell(4).setCellValue("Status");reportSheetHeader.createCell(5).setCellValue("Pay Method");reportSheetHeader.createCell(6).setCellValue("Refund Date");reportSheetHeader.createCell(7).setCellValue("Type");reportSheetHeader.createCell(8).setCellValue("Total Amount");reportSheetHeader.createCell(9).setCellValue("Discount");reportSheetHeader.createCell(10).setCellValue("Net Amount");int serialNo = 0;for(RechargeTransaction transaction : successfulRecharges) {serialNo++;Row contentRow = reportSheet.createRow((short)serialNo);contentRow.createCell(0).setCellValue(transaction.getId());contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));contentRow.createCell(3).setCellValue(transaction.getDeviceNum());contentRow.createCell(4).setCellValue(transaction.getStatus().name());contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());contentRow.createCell(6).setCellValue("N/A");contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");contentRow.createCell(8).setCellValue(transaction.getAmount());contentRow.createCell(9).setCellValue(transaction.getDiscount());contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());}for(RechargeTransaction transaction : refundedRecharges) {serialNo++;Row contentRow = reportSheet.createRow((short)serialNo);contentRow.createCell(0).setCellValue(transaction.getId());contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));contentRow.createCell(3).setCellValue(transaction.getDeviceNum());contentRow.createCell(4).setCellValue(transaction.getStatus().name());contentRow.createCell(5).setCellValue(transaction.getPayMethod().name());contentRow.createCell(6).setCellValue(formatter.format(new Date(transaction.getResponseTime())));contentRow.createCell(7).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");contentRow.createCell(8).setCellValue(transaction.getAmount());contentRow.createCell(9).setCellValue(transaction.getDiscount());contentRow.createCell(10).setCellValue(transaction.getPaymentAmount());}try {wb.write(baosXLS);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return baosXLS;}public String create() throws Exception{long sDate = -1;long eDate = -1;RechargeOrderStatus st = null;String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");if(loginStatus == null || !loginStatus.equals("TRUE")){return "authfail";}if(dateselector.equals("1")) {sDate = new Date().getTime();eDate = sDate;}else if (dateselector.equals("2")) {sDate = new Date().getTime() - 86400*1000;eDate = sDate;}else {if(!(startDate.equals(""))) {sDate = dateFormatter.parse(startDate).getTime();startDate = dateFormatter.format(sDate);}if(!endDate.equals("")) {eDate = dateFormatter.parse(endDate).getTime();endDate = dateFormatter.format(sDate);}}if(!status.equals("-1")){st = RechargeOrderStatus.findByValue(Integer.parseInt(status));}ByteArrayOutputStream baos = generateReport(tClient.getRechargeTrans(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate, st));response.setContentType("application/vnd.ms-excel");String st1 = "ALL";if(st!=null){st1 = st.name();}String fileName = st1 + "-recharge-report";if (!startDate.equals("")) {fileName = fileName + "-" + startDate.replaceAll("\\\\", "_") ;}if (!endDate.equals("")) {fileName = fileName + "-" + endDate.replaceAll("\\\\", "_") ;}fileName = fileName + ".xls";response.setHeader("Content-disposition", "inline; filename=" + fileName);ServletOutputStream sos;try {sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {e.printStackTrace();}return "index";}private ByteArrayOutputStream generateReport(List<RechargeTransaction> rechargeTrans) {ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();Workbook wb = new HSSFWorkbook();Sheet reportSheet = wb.createSheet("Recharge Report");Row reportSheetHeader = reportSheet.createRow((short)0);reportSheetHeader.createCell(0).setCellValue("Order ID");reportSheetHeader.createCell(1).setCellValue("Order Date");reportSheetHeader.createCell(2).setCellValue("Operator");reportSheetHeader.createCell(3).setCellValue("Device");reportSheetHeader.createCell(4).setCellValue("Status");reportSheetHeader.createCell(5).setCellValue("Recharge Amount");reportSheetHeader.createCell(6).setCellValue("Discount");reportSheetHeader.createCell(7).setCellValue("Net Amount");reportSheetHeader.createCell(8).setCellValue("Type");reportSheetHeader.createCell(9).setCellValue("Pay Method");reportSheetHeader.createCell(10).setCellValue("Refund Date");int serialNo = 0;for(RechargeTransaction transaction : rechargeTrans) {serialNo++;Row contentRow = reportSheet.createRow((short)serialNo);contentRow.createCell(0).setCellValue(transaction.getId());contentRow.createCell(1).setCellValue(formatter.format(new Date(transaction.getTransactionTime())));contentRow.createCell(2).setCellValue(getOperatorName(transaction.getOperatorId()));contentRow.createCell(3).setCellValue(transaction.getDeviceNum());contentRow.createCell(4).setCellValue(transaction.getStatus().name());contentRow.createCell(5).setCellValue(transaction.getAmount());contentRow.createCell(6).setCellValue(transaction.getDiscount());contentRow.createCell(7).setCellValue(transaction.getPaymentAmount());contentRow.createCell(8).setCellValue(transaction.isIsFrc() ? "FRC" : "Normal");contentRow.createCell(9).setCellValue(transaction.getPayMethod().name());if(transaction.getStatus() == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED) {contentRow.createCell(10).setCellValue(transaction.getResponseTime());} else {contentRow.createCell(10).setCellValue("N/A");}}try {wb.write(baosXLS);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return baosXLS;}public String sendPassword() throws Exception {String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");if(loginStatus == null || !loginStatus.equals("TRUE")){return "authfail";}Long storeId = Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));char[] buf = new char[LENGTH];for (int i = 0; i < buf.length; i++) {buf[i] = chars.charAt(random.nextInt(chars.length()));}String password = new String(buf);try {TransactionClient tcl = new TransactionClient();HotspotStore hotSpotStore = tcl.getClient().getHotspotStore(storeId, "");boolean wasPasswordSet = tcl.getClient().updateHotspotStorePassword(storeId, password);if(!wasPasswordSet) {passwordGeneration = "FAIL";return index();}List<String> toList = new ArrayList<String>();toList.add(hotSpotStore.getEmail());HelperClient helperServiceClient = null;helperServiceClient = new HelperClient();in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();Mail mail = new Mail();mail.setSubject("New Password for Saholic Recharge");mail.setTo(toList);mail.setData("Your new password is : " + password);client.sendMail(mail);} catch(Exception e) {passwordGeneration = "FAIL";logger.error("Password generation/sending failed for storeId : " + storeId, e);}passwordGeneration = "SUCCESS";return index();}public String getDateTime(long milliseconds) {Calendar cal = Calendar.getInstance();cal.setTimeInMillis(milliseconds);return formatter.format(cal.getTime());}public List<RechargeTransaction> getTxns(){return txns;}public void setServletRequest(HttpServletRequest req) {this.request = req;this.session = req.getSession();}public void setServletContext(ServletContext context) {this.context = context;}public void setServletResponse(HttpServletResponse response) {this.response = response;}public String getServletContextPath() {return context.getContextPath();}public String getOperatorName(long operatorId) {String operatorName = "";if (HomeController.getMobileProvidersMap().containsKey(operatorId)) {operatorName = HomeController.getMobileProvidersMap().get(operatorId);} else if(HomeController.getDthProvidersMap().containsKey(operatorId)) {operatorName = HomeController.getDthProvidersMap().get(operatorId);} else {operatorName = "N/A";}return operatorName;}public String getStartDate() {return startDate;}public void setStartDate(String startDate) {this.startDate = startDate;}public String getEndDate() {return endDate;}public void setEndDate(String endDate) {this.endDate = endDate;}public String getStatus() {return status;}public void setStatus(String status) {this.status = status;}public String getDateselector() {return dateselector;}public void setDateselector(String dateselector) {this.dateselector = dateselector;}public void setSearchError(String searchError) {this.searchError = searchError;}public String getSearchError() {return searchError;}public void setNumber(String number) {this.number = number;}public String getNumber() {return number;}public void setSearchResult(List<RechargeTransaction> searchResult) {this.searchResult = searchResult;}public List<RechargeTransaction> getSearchResult() {if(searchResult == null)searchResult = new ArrayList<RechargeTransaction>();return searchResult;}public void setShowReprintColumn(boolean showReprintColumn) {this.showReprintColumn = showReprintColumn;}public boolean shouldShowReprintColumn() {return showReprintColumn;}public void setPasswordGeneration(String passwordGeneration) {this.passwordGeneration = passwordGeneration;}public String getPasswordGeneration() {return passwordGeneration;}}