Subversion Repositories SmartDukaan

Rev

Rev 29287 | Rev 29445 | 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.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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.google.gson.Gson;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ChartInvestmentModel;
import com.spice.profitmandi.common.model.Data;
import com.spice.profitmandi.common.model.DataInvestmentModel;
import com.spice.profitmandi.common.model.Legend;
import com.spice.profitmandi.common.model.OptionModel;
import com.spice.profitmandi.common.model.PieLables;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.entity.user.Lead;
import com.spice.profitmandi.dao.entity.user.LeadActivity;
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
import com.spice.profitmandi.dao.model.ChartLeadModel;
import com.spice.profitmandi.dao.model.CreateLeacdActivityRequest;
import com.spice.profitmandi.dao.model.CreateRefferalRequest;
import com.spice.profitmandi.dao.model.DataLeadModel;
import com.spice.profitmandi.dao.model.LeadStatusData;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
import com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository;
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
import com.spice.profitmandi.service.AuthService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

@Controller
@Transactional(rollbackOn = Throwable.class)
public class LeadController {
        private static final Logger LOGGER = LogManager.getLogger(LeadController.class);

        @Autowired
        private LeadRepository leadRepository;

        @Autowired
        private LeadActivityRepository leadActivityRepository;

        @Autowired
        private StateRepository stateRepository;

        @Autowired
        private AuthService authService;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private Gson gson;

        @Autowired
        private CookiesProcessor cookiesProcessor;
        
        @Autowired
        PositionRepository positionRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        List<LeadStatus> status = Arrays.asList(LeadStatus.notInterested, LeadStatus.finalized);

        @RequestMapping(value = "/getOpenLead", method = RequestMethod.GET)
        public String getOpenLead(HttpServletRequest request,
                        @RequestParam(name = "leadStatus", required = false, defaultValue = "followUp") List<LeadStatus> leadStatus,
                        @RequestParam(name = "color", required = false, defaultValue = "") List<String> color, Model model)
                        throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String emailId = loginDetails.getEmailId();
                AuthUser authUser = authRepository.selectByEmailOrMobile(emailId);
                
                
        boolean authPositon  =  positionRepository.hasCategory(authUser.getId(),ProfitMandiConstants.TICKET_CATEGORY_SALES);
        
                if (leadStatus.contains(LeadStatus.All)) {

                        leadStatus.addAll(Arrays.asList(LeadStatus.values()));
                }

                List<Lead> leads = null;
                Map<Integer, LeadActivity> leadActivityMap = new HashMap<>();
                List<Integer> authUserIds = null;
                if (!color.isEmpty()) {
                        if (color.contains("All")) {
                                color.add("yellow");
                                color.add("green");
                        }
                        if(authPositon)
                        {
                                authUserIds = authService.getAllReportees(authUser.getId());
                                authUserIds.add(authUser.getId());
                                LOGGER.info("authIds" + authUserIds);
                        leads = leadRepository.selectAllByColorStatusAndUpdatedTimestampAndAuthIds(leadStatus, authUserIds, color,
                                        LocalDateTime.now().withDayOfMonth(1).minusMonths(3));
                        
                        }
                        else {
                                
                                leads = leadRepository.selectAllByColorStatusAndUpdatedTimestamp(leadStatus, color,
                                                LocalDateTime.now().withDayOfMonth(1).minusMonths(3));
                        }
                        
                } else {

                        if(authPositon) {
                                authUserIds = authService.getAllReportees(authUser.getId());
                                authUserIds.add(authUser.getId());
                                LOGGER.info("authIds" + authUserIds);
                                leads = leadRepository.selectAllByStatusAndUpdatedTimestampAndAuthId(leadStatus,
                                                LocalDateTime.now().withDayOfMonth(1).minusMonths(3),authUserIds);
                        
                        }
                        else {
                        leads = leadRepository.selectAllByStatusAndUpdatedTimestamp(leadStatus,
                                        LocalDateTime.now().withDayOfMonth(1).minusMonths(3));
                        }
                        // List<Lead> leads = leadRepository.selectAllBylistStatus(leadStatus);
                        if (!leads.isEmpty()) {
                                leads.addAll(leadRepository.selectAllByStatus(LeadStatus.pending));
                        }
                }
                if(authPositon && authUserIds.size() > 0) {
                        List<String> leadCreators = new ArrayList<>();
                        leadCreators.add("daily-sync");
                        leadCreators.addAll(authRepository.selectAllAuthUserByIds(authUserIds).stream().map(x->x.getFullName()).collect(Collectors.toList()));
                        model.addAttribute("leadCreators", leadCreators);
                }
                List<Lead> weekLast = new ArrayList<>();
                List<Lead> weekThird = new ArrayList<>();
                List<Lead> weekSecond = new ArrayList<>();
                List<Lead> weekFirst = new ArrayList<>();
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                List<LeadWeakWiseModel> lwDays = new ArrayList<>();
                

                for (int i = 7; i >= 1; i--) {
                        LocalDateTime startOfDay = curDate.minusDays(i);

                        LeadWeakWiseModel lm = new LeadWeakWiseModel();
                        lm.setMonth(startOfDay.toLocalDate());
                        lwDays.add(lm);
                }
      if(!leads.isEmpty())
      {
                for (Lead lead : leads) {

                        if (lead.getCreatedTimestamp().isAfter(curDate.minusDays(28))
                                        && lead.getCreatedTimestamp().isBefore(curDate.minusDays(21))) {
                                weekLast.add(lead);

                        } else if(lead.getCreatedTimestamp().isAfter(curDate.minusDays(21))
                                        && lead.getCreatedTimestamp().isBefore(curDate.minusDays(14))) {
                                weekThird.add(lead);
                        } else if (lead.getCreatedTimestamp().isAfter(curDate.minusDays(14))
                                        && lead.getCreatedTimestamp().isBefore(curDate.minusDays(7))) {

                                weekSecond.add(lead);
                        } else if (lead.getCreatedTimestamp().isAfter(curDate.minusDays(7))) {
                                weekFirst.add(lead);
                        }

                }
        }
                LOGGER.info("weekLast" + weekLast);
                LOGGER.info("weekThird" + weekThird);
                LOGGER.info("weekSecond" + weekSecond);
                Map<String, Long> leadLasts = weekLast.stream().collect(Collectors.groupingBy(x -> x.getCreatedBy(), Collectors.counting()));
                Map<String, Long> leadThirds = weekThird.stream().collect(Collectors.groupingBy(x -> x.getCreatedBy(), Collectors.counting()));
                Map<String, Long> leadSeconds = weekSecond.stream().collect(Collectors.groupingBy(x -> x.getCreatedBy(),
                                Collectors.mapping(Lead::getCreatedBy, Collectors.counting())));

                Map<String, Map<LocalDate, Long>> leadFirsts = weekFirst.stream()
                                .collect(Collectors.groupingBy(x -> x.getCreatedBy(),
                                                Collectors.groupingBy(x -> x.getCreatedTimestamp().toLocalDate(), Collectors.counting())));

                LOGGER.info("leadFirsts" + leadFirsts);

                List<Integer> authIds = new ArrayList<>();
                if (!leads.isEmpty()) {

                        authIds.addAll(leads.stream().map(x -> x.getAssignTo()).collect(Collectors.toList()));

                        for (Lead lead : leads) {
                                List<LeadActivity> leadActivity = leadActivityRepository.selectBYLeadId(lead.getId());
                                if (!leadActivity.isEmpty()) {
                                        leadActivityMap.put(lead.getId(), leadActivity.get(0));
                                }
                        }
                        Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
                        model.addAttribute("leadActivityMap", leadActivityMap);
                        model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
                }

                ChartLeadModel cm = this.getLeadChart(leads);
                model.addAttribute("chartLead", gson.toJson(cm));

                LOGGER.info("ChartLeadModel" + gson.toJson(cm));
                LOGGER.info("lwDays" + lwDays);

                LOGGER.info("leads" + leads);
                List<String> stateNames = stateRepository.selectAll().stream().map(x -> x.getName())
                                .collect(Collectors.toList());
                List<AuthUser> authUsers = authRepository.selectAllActiveUser();
                LocalDate lastDate = curDate.minusDays(1).toLocalDate();
                
                List<LocalDate> weekDates = new ArrayList<>();
                
                weekDates.add(curDate.minusDays(28).toLocalDate());
                weekDates.add(curDate.minusDays(22).toLocalDate());
                weekDates.add(curDate.minusDays(21).toLocalDate());
                weekDates.add(curDate.minusDays(15).toLocalDate());
                weekDates.add(curDate.minusDays(14).toLocalDate());
                weekDates.add(curDate.minusDays(8).toLocalDate());
                weekDates.add(curDate.minusDays(7).toLocalDate());
                LOGGER.info("lastDate" + lastDate);
                
                
                model.addAttribute("weekDates", weekDates);
                
                model.addAttribute("lastDate", lastDate);
                model.addAttribute("stateNames", stateNames);
                model.addAttribute("authUsers", authUsers);
                model.addAttribute("lead", leads);
                model.addAttribute("leadStatus", LeadStatus.values());
                model.addAttribute("leadLasts", leadLasts);
                model.addAttribute("leadThirds", leadThirds);
                model.addAttribute("leadSeconds", leadSeconds);
                model.addAttribute("leadFirsts", leadFirsts);
                model.addAttribute("lwDays", lwDays);

                model.addAttribute("selectedLeadStatus", leadStatus.get(0));
                return "lead";

        }

        public ChartLeadModel getLeadChart(List<Lead> leads) throws ProfitMandiBusinessException {

                Map<LeadStatus, Long> leadStatusMap = leads.stream().collect(
                                Collectors.groupingBy(x -> x.getStatus(), Collectors.mapping(Lead::getStatus, Collectors.counting())));

                ChartLeadModel cm = new ChartLeadModel();

                HashSet<LeadStatus> labels = new HashSet<LeadStatus>();
                labels.addAll(leadStatusMap.keySet());

                List<LeadStatus> labelList = new ArrayList<>(labels);
                List<String> backgroundColor = new ArrayList<>();

                List<Long> values = new ArrayList<>();

                for (LeadStatus label : labelList) {
                        values.add(leadStatusMap.get(label));

                        if (label.equals(LeadStatus.pending)) {
                                backgroundColor.add("pink");
                        }
                        if (label.equals(LeadStatus.notInterested)) {
                                backgroundColor.add("red");
                        }
                        if (label.equals(LeadStatus.followUp)) {
                                backgroundColor.add("#9ACD32");
                        }
                        if (label.equals(LeadStatus.finalized)) {
                                backgroundColor.add("blue");
                        }
                }
                LOGGER.info("labelList" + labelList);

                LOGGER.info("backgroundColor" + backgroundColor);
                LOGGER.info("labelsChartLead" + labels);
                LeadStatusData data = new LeadStatusData();
                data.setData(values);
                data.setBackgroundColor(backgroundColor);
                data.setLabel("DataSet 1");

                PieLables label = new PieLables();
                label.setFontColor("black");
                label.setFontSize(15);

                Legend legend = new Legend();
                legend.setLabels(label);
                legend.setPosition("left");

                List<LeadStatusData> dataList = new ArrayList<>();
                dataList.add(data);

                DataLeadModel datasets = new DataLeadModel();
                datasets.setDatasets(dataList);
                datasets.setLabels(labels);

                OptionModel om = new OptionModel();
                om.setLegend(legend);

                cm.setType("pie");
                cm.setData(datasets);
                cm.setOptions(om);

                return cm;
        }

        @RequestMapping(value = "/getClosedLead", method = RequestMethod.GET)
        public String getClosedLead(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws Exception {
                List<AuthUser> authUsers = authRepository.selectAllActiveUser();
                List<Lead> leads = null;
                long size = 0;
                leads = leadRepository.selectAllByStatus(status, offset, limit);
                size = leadRepository.selectCountByStatus(status);

                if (!leads.isEmpty()) {
                        List<Integer> authIds = new ArrayList<>();
                        for (Lead lead : leads) {
                                authIds.add(lead.getAssignTo());
                        }
                        Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                        .collect(Collectors.toMap(x -> x.getId(), x -> x));

                        model.addAttribute("leads", leads);
                        model.addAttribute("start", offset + 1);
                        model.addAttribute("size", size);
                        model.addAttribute("searchTerm", searchTerm);
                        model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
                        model.addAttribute("url", "/getPaginatedClosedLeads");

                        if (leads.size() < limit) {
                                model.addAttribute("end", offset + leads.size());
                        } else {
                                model.addAttribute("end", offset + limit);
                        }

                } else {
                        model.addAttribute("lead", leads);

                        model.addAttribute("size", size);
                }

                model.addAttribute("authUsers", authUsers);
                return "lead-close";
        }

        @RequestMapping(value = "/getPaginatedClosedLeads", method = RequestMethod.GET)
        public String getPaginatedClosedLeads(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
                        throws ProfitMandiBusinessException {
                List<Lead> leads = null;
                leads = leadRepository.selectAllByStatus(status, offset, limit);

                if (!leads.isEmpty()) {
                        List<Integer> authIds = new ArrayList<>();
                        for (Lead lead : leads) {
                                authIds.add(lead.getAssignTo());
                        }
                        Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
                        model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
                        model.addAttribute("leads", leads);
                        model.addAttribute("url", "/getPaginatedClosedLeads");

                } else {
                        model.addAttribute("leads", leads);

                }
                return "lead-close-paginated";
        }

        @RequestMapping(value = "/searchLeads")
        public String getClosedLeads(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws ProfitMandiBusinessException {
                List<AuthUser> authUsers = authRepository.selectAllActiveUser();
                List<Lead> leads = null;
                long size = 0;
                if (!(searchTerm.equals(""))) {
                        leads = leadRepository.selectBySearchTerm(status, searchTerm, offset, limit);
                        if (!(leads.size() == 0)) {
                                size = leadRepository.selectCountByStatus(status);
                                List<Integer> authIds = new ArrayList<>();
                                for (Lead lead : leads) {
                                        authIds.add(lead.getAssignTo());
                                }
                                Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                                .collect(Collectors.toMap(x -> x.getId(), x -> x));
                                model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
                                model.addAttribute("leads", leads);
                                model.addAttribute("start", offset + 1);
                                model.addAttribute("size", size);
                                model.addAttribute("searchTerm", searchTerm);

                                if (leads.size() < limit) {
                                        model.addAttribute("end", offset + leads.size());
                                } else {
                                        model.addAttribute("end", offset + limit);
                                }
                        } else {
                                throw new ProfitMandiBusinessException("lead", searchTerm, "leads Not Found");
                        }
                } else {
                        leads = leadRepository.selectAllByStatus(status, offset, limit);
                        size = leadRepository.selectCountByStatus(status);

                        if (!leads.isEmpty()) {
                                List<Integer> authIds = new ArrayList<>();
                                for (Lead lead : leads) {
                                        authIds.add(lead.getAssignTo());
                                }
                                Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                                model.addAttribute("leads", leads);
                                model.addAttribute("start", offset + 1);
                                model.addAttribute("size", size);
                                model.addAttribute("searchTerm", searchTerm);
                                model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);

                                if (leads.size() < limit) {
                                        model.addAttribute("end", offset + leads.size());
                                } else {
                                        model.addAttribute("end", offset + limit);
                                }

                        }
                }

                model.addAttribute("authUsers", authUsers);
                return "lead-close";
        }

        @RequestMapping(value = "/searchLeadPaginated")
        public String searchLeadPaginated(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws ProfitMandiBusinessException {
                LOGGER.info("In search Item....");
                List<Lead> leads = null;
                if (!searchTerm.equals("")) {
                        leads = leadRepository.selectBySearchTerm(status, searchTerm, offset, limit);
                        if (!(leads.size() == 0)) {

                                List<Integer> authIds = new ArrayList<>();
                                for (Lead lead : leads) {
                                        authIds.add(lead.getAssignTo());
                                }
                                Map<Integer, AuthUser> authIdAndAuthUserMap = authRepository.selectAllAuthUserByIds(authIds).stream()
                                                .collect(Collectors.toMap(x -> x.getId(), x -> x));
                                model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
                                model.addAttribute("leads", leads);
                        }
                }

                return "lead-close-paginated";

        }

        @RequestMapping(value = "/getLeadActivity", method = RequestMethod.GET)
        public String getLeadActivity(HttpServletRequest request, @RequestParam int leadId, Model model) throws Exception {
                List<LeadActivity> leadActivity = leadActivityRepository.selectBYLeadId(leadId);
                model.addAttribute("leadActivity", leadActivity);
                return "lead_activity_modal";
        }

        @RequestMapping(value = "/createLead", method = RequestMethod.POST)
        public String CreateLead(HttpServletRequest request, @RequestBody CreateRefferalRequest createRefferalRequest,
                        Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                LOGGER.info("createRefferalRequest" + createRefferalRequest.getSchelduleTimestamp());
                Lead lead = new Lead();
                lead.setFirstName(createRefferalRequest.getFirstName());
                lead.setLastName(createRefferalRequest.getLastName());
                lead.setLeadMobile(createRefferalRequest.getMobile());
                lead.setState(createRefferalRequest.getState());
                lead.setCity(createRefferalRequest.getCity());
                lead.setAddress(createRefferalRequest.getAddress());
                lead.setCreatedTimestamp(LocalDateTime.now());
                lead.setUpdatedTimestamp(LocalDateTime.now());
                lead.setStatus(createRefferalRequest.getStatus());
                lead.setAssignTo(createRefferalRequest.getAssignTo());
                lead.setSource(createRefferalRequest.getSource());
                lead.setColor("yellow");
                // change
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
                String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
                lead.setCreatedBy(authUserName);
                lead.setAuthId(authUser.getId());

                leadRepository.persist(lead);
                LeadActivity leadActivity = new LeadActivity();
                leadActivity.setLeadId(lead.getId());
                leadActivity.setRemark(createRefferalRequest.getRemark());

                if (createRefferalRequest.getStatus() == LeadStatus.followUp) {
                        leadActivity.setSchelduleTimestamp(createRefferalRequest.getSchelduleTimestamp());
                } else {
                        leadActivity.setSchelduleTimestamp(null);
                }
                leadActivity.setCreatedTimestamp(LocalDateTime.now());
                leadActivityRepository.persist(leadActivity);
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";

        }

        @RequestMapping(value = "/editLead", method = RequestMethod.POST)
        public String EditLead(HttpServletRequest request,
                        @RequestBody CreateLeacdActivityRequest createLeadActivityRequest, Model model) throws Exception {

                LeadActivity leadActivity = new LeadActivity();
                leadActivity.setLeadId(createLeadActivityRequest.getId());
                leadActivity.setRemark(createLeadActivityRequest.getRemark());

                if (createLeadActivityRequest.getStatus() == LeadStatus.followUp) {
                        leadActivity.setSchelduleTimestamp(createLeadActivityRequest.getScheldule());
                } else {
                        leadActivity.setSchelduleTimestamp(null);
                }
                leadActivity.setCreatedTimestamp(LocalDateTime.now());
                leadActivityRepository.persist(leadActivity);
                Lead lead = leadRepository.selectById(createLeadActivityRequest.getId());
                lead.setAssignTo(createLeadActivityRequest.getAssignTo());
                lead.setStatus(createLeadActivityRequest.getStatus());
                lead.setNotinterestedReason(createLeadActivityRequest.getReason());
                lead.setUpdatedTimestamp(LocalDateTime.now());

                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";

        }
}