Subversion Repositories SmartDukaan

Rev

Rev 7423 | Rev 7527 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;


import in.shop2020.model.v1.order.HotspotStore;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.RechargeOrderStatus;
import in.shop2020.model.v1.order.RechargeTransaction;
import in.shop2020.model.v1.order.StoreOrderCollection;
import in.shop2020.model.v1.order.StoreOrderDetail;
import in.shop2020.model.v1.order.TransactionService;
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.nio.ByteBuffer;
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.thrift.meta_data.SetMetaData;
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 Long number = null;
    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 String returnType;
    private List<Order> orders = null;
    private List<Order> searchResult = null;
    private Long orderId;

    private Long refundAmount;
    
    private boolean showReprintColumn = false;
    
    public ReportController(){
        super();
        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 {
            List<OrderStatus> statuses = new ArrayList<OrderStatus>();
            orders = tClient.getOrdersForStore(0, storeId, today, today, statuses);
        } 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() {
        String loginStatus = (String) request.getSession().getAttribute("LOGGED_IN");
        if(loginStatus == null || !loginStatus.equals("TRUE")){
            return "authfail";
        }
        if(number != null) {
            try {
                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                setSearchResult(tClient.getOrdersForStore(number, Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), -1, -1, statuses));
                if(searchResult.size() == 0) {
                    setSearchError("Could not find any orders with this number. Please try again.");
                }
            } 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 sDate = -1;
        long eDate = -1;

        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(eDate);
            }
        }
        
        long today = -1;
        today = new Date().getTime();
        List<StoreOrderCollection> collections = tClient.getCollectionsForStore(Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate);
        ByteArrayOutputStream baos = generateCollectionReport(collections);
        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<StoreOrderCollection> collections) {
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
        Workbook wb = new HSSFWorkbook();
        Sheet reportSheet = wb.createSheet("Collection Report");
        Row reportSheetHeader = reportSheet.createRow((short)0);
        reportSheetHeader.createCell(0).setCellValue("Order ID");
        reportSheetHeader.createCell(1).setCellValue("Date");
        reportSheetHeader.createCell(2).setCellValue("Product");
        reportSheetHeader.createCell(3).setCellValue("Collection Type");
        reportSheetHeader.createCell(4).setCellValue("Amount");
        reportSheetHeader.createCell(5).setCellValue("Cash");
        reportSheetHeader.createCell(6).setCellValue("Card");
        
        
        
        int serialNo = 0;
        
        for(StoreOrderCollection collection : collections) {
            serialNo++;
            Row contentRow = reportSheet.createRow((short)serialNo);
            contentRow.createCell(0).setCellValue(collection.getOrderId());
            contentRow.createCell(1).setCellValue(formatter.format(new Date(collection.getPushedAt())));
            contentRow.createCell(2).setCellValue(collection.getProductName());
            contentRow.createCell(3).setCellValue(collection.getCollectionType());
            contentRow.createCell(4).setCellValue(collection.getAdvanceAmount());
            contentRow.createCell(5).setCellValue(collection.getCash());
            contentRow.createCell(6).setCellValue(collection.getCard());
        }
        try {
            wb.write(baosXLS);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return baosXLS;
    }

    
    public String create() throws Exception{
        long sDate = -1;
        long eDate = -1;
        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);
            }
        }
            
        List<OrderStatus> statuses = new ArrayList<OrderStatus>();
        statuses.add(OrderStatus.DELIVERY_SUCCESS);
        orders = tClient.getOrdersForStore(0, Long.parseLong((String) request.getSession().getAttribute("STORE_ID")), sDate, eDate, statuses);

        ByteArrayOutputStream baos = generateReport(orders);
        
        response.setContentType("application/vnd.ms-excel");
        String fileName = "sales-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<Order> orders) {
        
        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("Product");
        reportSheetHeader.createCell(3).setCellValue("Status");
        reportSheetHeader.createCell(4).setCellValue("Order Amount");
        reportSheetHeader.createCell(5).setCellValue("Advance");
        
        int serialNo = 0;
        
        for(Order order : orders) {
            serialNo++;
            Row contentRow = reportSheet.createRow((short)serialNo);
            contentRow.createCell(0).setCellValue(order.getId());
            contentRow.createCell(1).setCellValue(formatter.format(new Date(order.getCreated_timestamp())));
            contentRow.createCell(2).setCellValue(getProductName(order.getLineitems().get(0)));
            contentRow.createCell(3).setCellValue(order.getStatusDescription());
            contentRow.createCell(4).setCellValue(order.getTotal_amount());
            contentRow.createCell(5).setCellValue(order.getAdvanceAmount());
        }
        try {
            wb.write(baosXLS);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return baosXLS;
    }
    
    public String downloadInvoice() {
        ByteBuffer buffer = null;
        try {
            if (number == null || number == 0) {
                log.error("rechargeId is 0");
                return "index";
            }
            TransactionClient transactionServiceClient = new TransactionClient();
            TransactionService.Client orderClient = transactionServiceClient.getClient();
            //TODO : dynamically get StoreId
            buffer = orderClient.getStoreOrderAdvanceInvoice(number, Long.parseLong((String) request.getSession().getAttribute("STORE_ID")));
            if(!buffer.hasArray()) {
                log.error("The invoice was not found for orderId : " + number);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=receipt-" + number.toString() + ".pdf");

        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            sos.write(buffer.array());
            sos.flush();
        } catch (Exception e) {
            System.out.println("Unable to stream the invoice file");
        }
        return "index";
    }
    
    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 String cancelRequest() {
        try{
        TransactionClient tcl = new TransactionClient();
        long storeId =  Long.parseLong((String) request.getSession().getAttribute("STORE_ID"));
        StoreOrderDetail sod = tcl.getClient().getStoreOrderDetail(orderId, storeId);
        tcl.getClient().saveRefundAmountsForStoreOrder(orderId, storeId, sod.getCashAmount(), sod.getCardAmount());
        tcl.getClient().markOrderCancellationRequestReceived(orderId);
        tcl.getClient().markOrderCancellationRequestConfirmed(orderId);
        tcl.getClient().refundOrder(orderId, "Store", "User requested for cancellation");
        } catch (Exception e) {
            logger.error("Could not mark order as cancellation requested for id : " + orderId.toString(), e);
            setSearchError("Request failed. Try again or call customer care.");
        }
        number = orderId;
        return search();
    }
    
    public String requestReturn() {
        try{
            TransactionClient tcl = new TransactionClient();
            if(returnType.equals("doa")) {
                tcl.getClient().markOrderDoaRequestReceived(orderId);
            } else if(returnType.equals("return")) {
                tcl.getClient().markOrderReturnRequestReceived(orderId);
            } else {
                setSearchError("Error in requesting return. Try Again.");
            }
        } catch (Exception e) {
            logger.error("Could not mark order as return requested for id : " + orderId.toString(), e);
            setSearchError("Request failed. Try again or call customer care.");
        }
        number = orderId;
        return search();
    }
    
    public String refundOrder() {
        number = orderId;
        try{
            TransactionClient tcl = new TransactionClient();
            Order order = tcl.getClient().getOrder(number);
            if(order.getTotal_amount() < refundAmount) {
                setSearchError("You cannot refund more than Rs. " + refundAmount.toString());
                return search();
            }
            tcl.getClient().refundOrder(orderId, "ANU", "Cancelled");
            setSearchError("SUCCESSFUL. Please refund Rs. " + refundAmount.toString() + " to the customer.");
        } catch (Exception e) {
            logger.error("Could not mark order as return requested for id : " + orderId.toString(), e);
            setSearchError("Could not refund. Try again or call customer care.");
        }
        return search();
    }

    public List<Order> getOrders(){
        return orders;
    }
    
    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 getProductName(LineItem item) {
        return item.getBrand() 
                + (item.getModel_name() == null ? "" : " " + item.getModel_name())
                + (item.getModel_number() == null ? "" : " " + item.getModel_number())
                + (item.getColor() == null || item.getColor() == "" ? "" : " (" + item.getColor() + ")");
    }
    
    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(Long number) {
        this.number = number;
    }


    public Long getNumber() {
        return number;
    }


    public void setSearchResult(List<Order> searchResult) {
        this.searchResult = searchResult;
    }


    public List<Order> getSearchResult() {
        if(searchResult == null)
            searchResult = new ArrayList<Order>();
        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;
    }


    public void setOrderId(Long orderId) {
        this.orderId = orderId;
    }


    public Long getOrderId() {
        return orderId;
    }


    public void setReturnType(String returnType) {
        this.returnType = returnType;
    }


    public String getReturnType() {
        return returnType;
    }


    public void setRefundAmount(Long refundAmount) {
        this.refundAmount = refundAmount;
    }


    public Long getRefundAmount() {
        return refundAmount;
    }
    
    public boolean isOrderPlacedOnSameDay(long orderTime) {
        Calendar calOrderDate = Calendar.getInstance();
        calOrderDate.setTimeInMillis(orderTime);
        
        Calendar cal = Calendar.getInstance();
        if(cal.get(Calendar.DATE) == calOrderDate.get(Calendar.DATE) 
                && cal.get(Calendar.MONTH) == calOrderDate.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == calOrderDate.get(Calendar.YEAR)) {
            return true;
        }
        return false;
    }

}