Subversion Repositories SmartDukaan

Rev

Rev 30162 | Rev 33092 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.enumuration.ReporticoProject;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ReporticoUrlInfo;
import com.spice.profitmandi.common.services.ReporticoService;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.model.CollectionSummary;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.RoleRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.order.OrderService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class ReportsController {

        @Autowired
        private RoleRepository roleRepository;

        @Autowired
        private CookiesProcessor cookiesProcessor;
        
        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private ReporticoService reporticoService;

        @Autowired
        private OrderRepository orderRepository;
        @Autowired
        private RoleManager roleManager;
        
        @Autowired
        private OrderService  orderService;

        @Autowired
        private CsService csService;

        @Autowired
        private AuthRepository authRepository;

        private static final Logger Logger = LogManager.getLogger(OrderController.class);

        @RequestMapping(value = "/reports/{projectName}/{fileName}")
        public ResponseEntity<?> fetchReport(HttpServletRequest request, @PathVariable String fileName,
                        @PathVariable ReporticoProject projectName, @RequestBody(required = false) Map<String, String> paramsMap)
                        throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                HttpResponse response;
                if (roleManager.isAdmin(loginDetails.getRoleIds())) {

                        if (fileName.equalsIgnoreCase("LeadsReport")) {
                                if (paramsMap == null) {
                                        paramsMap = new HashMap<String, String>();
                                }
                                Map<Integer, List<Integer>> mapping = csService.getL2L1Mapping();

                                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());

                                List<Integer> authIds = mapping.get(authUser.getId());
                                if (authIds == null) {
                                        authIds = new ArrayList<>();
                                }
                                authIds.add(authUser.getId());

                                paramsMap.put("authId", authIds + "");
                        }
                } else {
                        if (paramsMap == null) {
                                paramsMap = new HashMap<String, String>();
                        }

                        paramsMap.put("MANUAL_fofoId", loginDetails.getFofoId() + "");

                }
                response = getAdminReportFile(loginDetails.getEmailId(), projectName, fileName + ".xml", paramsMap);
                HttpHeaders headers = new HttpHeaders();
                InputStreamResource is = new InputStreamResource(response.getEntity().getContent());
                headers.set("Content-Type", "application/vnd.ms-excel");
                headers.set("Content-disposition", "inline; filename=report-" + fileName + ".csv");
                headers.setContentLength(response.getEntity().getContentLength());
                return new ResponseEntity<InputStreamResource>(is, headers, HttpStatus.OK);
        }

        private HttpResponse getAdminReportFile(String email, ReporticoProject projectName, String fileName,
                        Map<String, String> reportParams) throws ProfitMandiBusinessException, IOException {
                return reporticoService.getReportFile(projectName, fileName, reportParams);
        }
        
        @RequestMapping(value = "/collectionSummary", method = RequestMethod.GET)
        public String getCollectionSummary(HttpServletRequest request,
                        Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                
                LocalDateTime currentDate = LocalDate.now().atStartOfDay();
                LocalDateTime currentStartMonth = currentDate.minusDays(30).toLocalDate().atStartOfDay();
                
                List<CollectionSummary> collectionSummaryList =orderRepository.selectCollectionSummary(fofoDetails.getFofoId(),currentStartMonth, currentDate);
                
                Logger.info("CollectionSummaryList {}", collectionSummaryList);
                
                model.addAttribute("startDate",currentDate.minusDays(30).toLocalDate());
                model.addAttribute("endDate", LocalDate.now());
                model.addAttribute("collectionSummaryList", collectionSummaryList);
                return "partner-collection-summary";
        }
        
        @RequestMapping(value = "/downloadCollectionSummary", method = RequestMethod.GET)
        public ResponseEntity<?>  getDownloadCollectionSummary(HttpServletRequest request,
                        @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
                        @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate,Model model) throws Exception {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                List<List<?>> rows = new ArrayList<>();

                
                List<CollectionSummary> collectionSummaryList =orderRepository.selectCollectionSummary(fofoDetails.getFofoId(),startDate.atStartOfDay(), endDate.atStartOfDay());
                
                Logger.info("CollectionSummaryList {}", collectionSummaryList);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
                
                for( CollectionSummary cs : collectionSummaryList) {
                        
                        rows.add(Arrays.asList(cs.getDate().format(
                                        dateTimeFormatter), cs.getReferenceType(),cs.getCash(),cs.getPinelabs(),cs.getBajajFinserv(),cs.getHomeCredit(),cs.getPaytm(),
                                        cs.getCapitalFirst(),cs.getZestMoney(),cs.getSamsungSure(),cs.getTotalAmount()));
                        
                        
                }
                
                org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
                                .getCSVByteStream(Arrays.asList("Date", "Reference Type", "Cash","Pinelabs", "Bajaj Finservice", "Home Credit", "Paymt",
                                                "Capital First", "Zest Money", "Samsung Sure", "Total Amount"), rows);
                
                ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows,"Collection Summary Report");

                
                return responseEntity;
        }
        
        
        


        @RequestMapping(value = "/reports", method = RequestMethod.GET)
        public String reports(HttpServletRequest httpServletRequest, Model model) throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
                
                //LoginDetails loginDetails = cookiesProcessor.getCookiesObject(httpServletRequest);
                Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap = ReporticoProject.reporticoProjectMap;
                /*if(fofoStoreRepository.getWarehousePartnerMap().get(7720).stream().filter(x->x.getId()==loginDetails.getFofoId()).count() > 0) {
                        Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap1 = new HashMap<ReporticoProject, List<ReporticoUrlInfo>>();
                        returnMap1.put(ReporticoProject.FOCO, returnMap.get(ReporticoProject.FOCO));
                        returnMap1.put(ReporticoProject.FOCOR, returnMap.get(ReporticoProject.FOCOR).stream().skip(1).collect(Collectors.toList()));
                        returnMap = returnMap1;
                }*/
                model.addAttribute("reporticoProjectMap", returnMap);
                
                return "reports";
        }
}