Subversion Repositories SmartDukaan

Rev

Rev 30821 | Rev 31677 | 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.csv.CSVRecord;
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.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import com.mongodb.DBObject;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BrandStockPrice;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.InvoicePdfModel;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.common.util.PdfUtils;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionPlan;
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
import com.spice.profitmandi.dao.entity.auth.PartnerSecondaryPlan;
import com.spice.profitmandi.dao.entity.cs.Ticket;
import com.spice.profitmandi.dao.entity.cs.TicketCategory;
import com.spice.profitmandi.dao.entity.cs.TicketSubCategory;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.entity.fofo.PartnerOnBoardingPanel;
import com.spice.profitmandi.dao.entity.user.FranchiseeActivity;
import com.spice.profitmandi.dao.entity.user.FranchiseeVisit;
import com.spice.profitmandi.dao.entity.user.Lead;
import com.spice.profitmandi.dao.entity.user.LeadActivity;
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
import com.spice.profitmandi.dao.enumuration.dtr.FranchiseeActivityStatus;
import com.spice.profitmandi.dao.enumuration.dtr.FranchiseeVisitStatus;
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
import com.spice.profitmandi.dao.enumuration.dtr.StoreTimeline;
import com.spice.profitmandi.dao.model.CreateRefferalRequest;
import com.spice.profitmandi.dao.model.OnBoardingTimelineModel;
import com.spice.profitmandi.dao.model.PartnerCollectionAchievementModel;
import com.spice.profitmandi.dao.model.PartnerCollectionPlanModel;
import com.spice.profitmandi.dao.model.PartnerCollectionRemarkModel;
import com.spice.profitmandi.dao.model.PartnerSecondaryPlanModel;
import com.spice.profitmandi.dao.model.PartnerTargetAchievementModel;
import com.spice.profitmandi.dao.model.TargetModel;
import com.spice.profitmandi.dao.model.TicketViewModel;
import com.spice.profitmandi.dao.model.UserCart;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.auth.AuthUserPartnerMappingRepository;
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionPlanRepository;
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
import com.spice.profitmandi.dao.repository.auth.PartnerSecondaryPlanRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
import com.spice.profitmandi.dao.repository.cs.TicketSubCategoryRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.FranchiseeActivityRepository;
import com.spice.profitmandi.dao.repository.dtr.FranchiseeVisitRepository;
import com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository;
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
import com.spice.profitmandi.service.PartnerCollectionService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.user.StoreTimelineTatService;
import com.spice.profitmandi.web.req.CreateFranchiseeRequest;
import com.spice.profitmandi.web.res.Partner;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class LeadController {
        private static final Logger LOGGER = LogManager.getLogger(LeadController.class);
        @Autowired
        private ResponseSender<?> responseSender;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private LeadRepository leadRepository;

        @Autowired
        private CsService csService;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private LeadActivityRepository leadActivityRepository;

        @Autowired
        private FranchiseeVisitRepository franchiseeVisitRepository;

        @Autowired
        private FranchiseeActivityRepository franchiseeActivityRepository;

        @Autowired
        private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private StoreTimelineTatService storeTimelineTatService;

        @Autowired
        private PartnerCollectionService partnerCollectionService;

        @Autowired
        private TicketRepository ticketRepository;

        @Autowired
        private TicketCategoryRepository ticketCategoryRepository;

        @Autowired
        private TicketSubCategoryRepository ticketSubCategoryRepository;

        @Autowired
        private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private PositionRepository positionRepository;

        @Autowired
        private UserWalletRepository userWalletRepository;

        @Autowired
        private PartnerCollectionPlanRepository partnerCollectionPlanRepository;

        @Autowired
        private PartnerSecondaryPlanRepository partnerSecondaryPlanRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        private AuthUserPartnerMappingRepository authUserPartnerMappingRepository;

        @RequestMapping(value = "/lead", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> LeadUser(HttpServletRequest request,
                        @RequestBody CreateRefferalRequest createRefferalRequest) throws Exception {
                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.setSource(createRefferalRequest.getSource());
                lead.setNotinterestedReason(createRefferalRequest.getReason());
                if (createRefferalRequest.getColorCheck() == true) {
                        lead.setColor("Green");
                } else {
                        lead.setColor("Yellow");
                }
                AuthUser authUser = authRepository.selectByGmailId(createRefferalRequest.getReffereeEmail());
                String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
                lead.setCreatedBy(authUserName);
                lead.setAuthId(authUser.getId());
                lead.setAssignTo(authUser.getId());

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

                if (createRefferalRequest.getStatus().equals(LeadStatus.followUp)) {
                        leadActivity.setSchelduleTimestamp(createRefferalRequest.getSchelduleTimestamp());
                        leadActivity.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
                        lead.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
                } else {
                        leadActivity.setSchelduleTimestamp(null);
                        leadActivity.setClosureTimestamp(null);
                        lead.setClosureTimestamp(null);
                }
                leadActivity.setCreatedTimestamp(LocalDateTime.now());
                leadActivityRepository.persist(leadActivity);

                return responseSender.ok(true);
        }

        @RequestMapping(value = "/lead-description", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> leadDescription(HttpServletRequest request, @RequestParam(name = "gmailId") String gmailId,
                        @RequestParam(name = "status") LeadStatus status) throws ProfitMandiBusinessException {
                AuthUser authUser = authRepository.selectByGmailId(gmailId);
                List<Lead> leads = null;
                LOGGER.info("emails" + status);
                if (status.equals(LeadStatus.followUp)) {

                        leads = leadRepository.selectLeadsScheduledBetweenDate(Arrays.asList(authUser.getId()), null, null);
                        leads = leads.stream()
                                        .sorted(Comparator.comparing(Lead::getScheduledTimestamp,
                                                        Comparator.nullsFirst(Comparator.reverseOrder())))
                                        .collect(Collectors
                                                        .toList());/*
                                                                                 * Collections.sort(leads, (o1, o2) -> { if (o1.getScheduledTimestamp() != null
                                                                                 * && o2.getScheduledTimestamp() != null) { return
                                                                                 * o1.getScheduledTimestamp().isBefore(o2.getScheduledTimestamp()) ? -1 : 1; }
                                                                                 * else if (o1.getScheduledTimestamp() != null) { return 1; } else { return -1;
                                                                                 * } });
                                                                                 */

                } else {
                        leads = leadRepository.selectByAssignAuthIdAndStatus(authUser.getId(), status);

                }

                return responseSender.ok(leads);

        }

        @RequestMapping(value = "/getlead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getLead(HttpServletRequest request, @RequestParam(name = "id") int id)
                        throws ProfitMandiBusinessException {

                List<LeadActivity> leadActivities = leadActivityRepository.selectBYLeadId(id);
                Lead lead = leadRepository.selectById(id);
                lead.setLeadActivities(leadActivities);
                return responseSender.ok(lead);

        }

        @RequestMapping(value = "/leadUpdate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> leadUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
                        @RequestParam(name = "status") LeadStatus status, @RequestParam(name = "colorCheck") Boolean colorCheck,
                        @RequestParam(name = "remark") String remark, @RequestParam(name = "reason") String reason,
                        @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp,
                        @RequestParam(name = "closureTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime closureTimestamp)
                        throws ProfitMandiBusinessException {

                Lead lead = leadRepository.selectById(id);

                LeadActivity leadActivity = new LeadActivity();
                lead.setStatus(status);
                lead.setNotinterestedReason(reason);
                leadActivity.setRemark(remark);
                leadActivity.setLeadId(id);
                leadActivity.setCreatedTimestamp(LocalDateTime.now());
                leadActivity.setSchelduleTimestamp(null);
                leadActivity.setClosureTimestamp(null);
                lead.setUpdatedTimestamp(LocalDateTime.now());
                if (colorCheck == true) {
                        lead.setColor("Green");
                } else {
                        lead.setColor("Yellow");
                }
                if (status == LeadStatus.followUp) {

                        leadActivity.setSchelduleTimestamp(schelduleTimestamp);
                        leadActivity.setClosureTimestamp(closureTimestamp);
                        lead.setClosureTimestamp(closureTimestamp);

                } else {

                        leadActivity.setSchelduleTimestamp(null);
                        leadActivity.setClosureTimestamp(null);
                        lead.setClosureTimestamp(null);

                }
                leadActivityRepository.persist(leadActivity);
                return responseSender.ok(true);

        }

        @RequestMapping(value = ProfitMandiConstants.URL_NEW_LEAD, method = RequestMethod.POST)
        public ResponseEntity<?> newLead(HttpServletRequest request,
                        @RequestBody CreateRefferalRequest createRefferalRequest) throws ProfitMandiBusinessException {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                Lead lead = new Lead();
                lead.setAddress(createRefferalRequest.getCity());
                Long.parseLong(createRefferalRequest.getMobile());
                if (createRefferalRequest.getMobile().length() != 10) {
                        throw new ProfitMandiBusinessException("Mobile Number", createRefferalRequest.getMobile(),
                                        "Number should be of 10 digits");
                }
                lead.setLeadMobile(createRefferalRequest.getMobile());
                lead.setCity(createRefferalRequest.getCity());
                lead.setState(createRefferalRequest.getState());
                lead.setLastName(createRefferalRequest.getLastName());
                if (lead.getState().equals("Uttar Pradesh")) {
                        lead.setAssignTo(53);
                } else if (lead.getState().equals("Haryana")) {
                        lead.setAssignTo(53);
                } else if (lead.getState().equals("Delhi")) {
                        lead.setAssignTo(53);
                } else {
                        // Assign to sm
                        lead.setAssignTo(53);
                        // Assign to neha
                        // lead.setAssignTo(1);
                }
                lead.setAuthId(lead.getAssignTo());
                lead.setCreatedBy("daily-sync");
                lead.setSource("SD-WEB");
                lead.setFirstName(createRefferalRequest.getFirstName());
                lead.setStatus(LeadStatus.followUp);
                lead.setColor("yellow");
                lead.setCreatedTimestamp(LocalDateTime.now());
                lead.setUpdatedTimestamp(LocalDateTime.now());
                leadRepository.persist(lead);

                return responseSender.ok(true);

        }

        @RequestMapping(value = "/getPartnersList", method = RequestMethod.GET)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getPartners(HttpServletRequest request, @RequestParam(name = "gmailId") String gmailId)
                        throws ProfitMandiBusinessException {

                AuthUser authUser = authRepository.selectByGmailId(gmailId);

                Map<String, Set<String>> storeGuyMap = csService.getAuthUserPartnerEmailMapping();

                Set<String> emails = storeGuyMap.get(authUser.getEmailId());
                LOGGER.info("emails" + emails);
                List<User> users = userRepository.selectAllByEmailIds(new ArrayList<>(emails));
                List<Partner> partners = new ArrayList<>();
                for (User user : users) {

                        UserAccount uc = userAccountRepository.selectSaholicByUserId(user.getId());
                        com.spice.profitmandi.dao.entity.user.User userInfo = userUserRepository.selectById(uc.getAccountKey());
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(userInfo.getId());

                        Partner partner = new Partner();
                        partner.setBusinessName(customRetailer.getBusinessName());
                        partner.setPartnerId(customRetailer.getPartnerId());
                        partner.setCartId(customRetailer.getCartId());
                        partner.setEmail(customRetailer.getEmail());
                        partner.setGstNumber(customRetailer.getGstNumber());
                        partner.setDisplayName(customRetailer.getDisplayName());
                        partner.setCity(customRetailer.getAddress().getCity());
                        partner.setUserId(user.getId());
                        partners.add(partner);
                }
                LOGGER.info("partners" + partners);
                return responseSender.ok(partners);
        }

        @RequestMapping(value = "/franchise-first-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> FranchiseFirstVisit(HttpServletRequest request,
                        @RequestBody CreateFranchiseeRequest createFranchiseeRequest) throws Exception {

                FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
                franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
                CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());

                franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
                franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
                franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
                franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
                franchiseeVisit.setScheduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
                // change
                AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());

                String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
                franchiseeVisit.setCreatedBy(authUserName);
                franchiseeVisit.setAuthId(authUser.getId());

                franchiseeVisitRepository.persist(franchiseeVisit);

                return responseSender.ok(true);
        }

        @RequestMapping(value = "/franchise-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> FranchiseVisit(HttpServletRequest request,
                        @RequestBody CreateFranchiseeRequest createFranchiseeRequest) throws Exception {

                FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(createFranchiseeRequest.getId());
                franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
                CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());

                franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
                franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
                franchiseeVisit.setPartnerRemark(createFranchiseeRequest.getPartnerRemark());
                franchiseeVisit.setOutsideVisibity(createFranchiseeRequest.getOutsideVisibity());
                franchiseeVisit.setInstoreVisibility(createFranchiseeRequest.getInstoreVisibility());
                franchiseeVisit.setOutsideStock(createFranchiseeRequest.getOutsideStock());
                franchiseeVisit.setSystemKnowledge(createFranchiseeRequest.getSystemKnowledge());
                franchiseeVisit.setWorkingDevice(createFranchiseeRequest.getWorkingDevice());
                franchiseeVisit.setWorkingPrinter(createFranchiseeRequest.getWorkingPrinter());
                franchiseeVisit.setCarryBags(createFranchiseeRequest.getCarryBags());
                franchiseeVisit.setSmartdukaanTshirt(createFranchiseeRequest.getSmartdukaanTshirt());
                franchiseeVisit.setLatestDummies(createFranchiseeRequest.getLatestDummies());
                franchiseeVisit.setInvestment(createFranchiseeRequest.getInvestment());
                franchiseeVisit.setMtd(createFranchiseeRequest.getMtd());
                franchiseeVisit.setHygiene(createFranchiseeRequest.getHygiene());
                franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
                franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                franchiseeVisit.setInformedAboutOnline(createFranchiseeRequest.getOnline());
                franchiseeVisit.setPendingBilling(createFranchiseeRequest.getPendingBilling());
                if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
                } else {
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
                }

                // AuthUser authUser =
                // authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
                // change
                AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());

                String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
                franchiseeVisit.setCreatedBy(authUserName);
                franchiseeVisit.setAuthId(authUser.getId());

                franchiseeVisitRepository.persist(franchiseeVisit);

                FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
                franchiseeActivity.setAction(createFranchiseeRequest.getAction());
                franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
                franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
                if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
                        franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getSchelduleTimestamp());
                } else {
                        franchiseeActivity.setSchelduleTimestamp(null);
                }
                franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
                franchiseeActivityRepository.persist(franchiseeActivity);

                franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
                return responseSender.ok(true);
        }

        @RequestMapping(value = "/getFranchiseVisit", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getFranchiseVisit(HttpServletRequest request,
                        @RequestParam(name = "gmailId") String gmailId, @RequestParam(name = "status") FranchiseeVisitStatus status,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
                AuthUser authUser = authRepository.selectByGmailId(gmailId);

                List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectByAuthIdAndStatus(authUser.getId(),
                                status, offset, limit);

                for (FranchiseeVisit fv : franchiseeVisits) {
                        if (fv.getFranchiseActivityId() != 0) {
                                FranchiseeActivity fA = franchiseeActivityRepository.selectById(fv.getFranchiseActivityId());
                                fv.setFranchiseeActivity(fA);
                        }
                }

                return responseSender.ok(franchiseeVisits);

        }

        @RequestMapping(value = "/getFranchiseActivity", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getFranchiseActivity(HttpServletRequest request, @RequestParam(name = "id") int id)
                        throws ProfitMandiBusinessException {

                List<FranchiseeActivity> franchiseeActivities = franchiseeActivityRepository.selectByFranchiseeVisitId(id);
                return responseSender.ok(franchiseeActivities);

        }

        @RequestMapping(value = "/getFranchiseeInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getFranchiseeInfo(HttpServletRequest request, @RequestParam(name = "id") int id)
                        throws ProfitMandiBusinessException {
                FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);

                List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);

                List<String> brands = mobileBrands.stream().filter(x -> (boolean) x.get("active"))
                                .map(x -> (String) x.get("name")).collect(Collectors.toList());

                franchiseeVisit.setBrands(brands);

                return responseSender.ok(franchiseeVisit);

        }

        @RequestMapping(value = "/franchise-visit-update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> franchiseVisitUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
                        @RequestParam(name = "action") FranchiseeActivityStatus action,
                        @RequestParam(name = "resolution") String resolution,
                        @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp)
                        throws ProfitMandiBusinessException {
                FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);

                FranchiseeActivity franchiseeActivity = new FranchiseeActivity();

                if (action == FranchiseeActivityStatus.FOLLOWUP) {

                        franchiseeActivity.setSchelduleTimestamp(schelduleTimestamp);
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
                        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                        franchiseeVisitRepository.persist(franchiseeVisit);

                } else {

                        franchiseeActivity.setSchelduleTimestamp(null);
                        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
                        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                        franchiseeVisitRepository.persist(franchiseeVisit);

                }

                franchiseeActivity.setResolution(resolution);
                franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
                franchiseeActivity.setAction(action);

                franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
                franchiseeActivityRepository.persist(franchiseeActivity);

                franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
                franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
                franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                franchiseeVisitRepository.persist(franchiseeVisit);

                return responseSender.ok(true);

        }

        @RequestMapping(value = "/onBoardingTimelineStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> onBoardingTimelineStatus(HttpServletRequest request, Model model)
                        throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute("userId");
                UserCart uc = userAccountRepository.getUserCart(userId);
                FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
                PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
                Map<StoreTimeline, OnBoardingTimelineModel> timelineStatus = null;
                LOGGER.info("partnerOnBoardingPanel" + partnerOnBoardingPanel);
                if (partnerOnBoardingPanel != null) {

                        timelineStatus = storeTimelineTatService.getTimeline(partnerOnBoardingPanel.getId());
                }
                List<OnBoardingTimelineModel> onBoardingModel = new ArrayList<>();
                if (timelineStatus != null) {
                        onBoardingModel = timelineStatus.values().stream().skip(2).map(x -> x).collect(Collectors.toList());
                }
                return responseSender.ok(onBoardingModel);

        }

        @RequestMapping(value = "/onBoardingTimelineVisibility", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> onBoardingTimelineVisibility(HttpServletRequest request, Model model)
                        throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute("userId");
                UserCart uc = userAccountRepository.getUserCart(userId);

                FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
                PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
                boolean status = true;
                if (partnerOnBoardingPanel != null) {

                        status = storeTimelineTatService.getTimelineCompleted(partnerOnBoardingPanel.getId());
                }

                LOGGER.info("status" + status);

                return responseSender.ok(status);

        }

        @RequestMapping(value = "/getPartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getPartnerTarget(HttpServletRequest request,
                        @RequestParam(name = "gmailId") String gmailId, @RequestParam String dayValue)
                        throws ProfitMandiBusinessException {

                AuthUser authUser = authRepository.selectByGmailId(gmailId);
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
                List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");

                float totalPartnerTargetSecondary = 0;
                float totalPartnerTargetCollection = 0;
                float totalPartnerAchievementSecondary = 0;
                float totalPartnerAchievementCollection = 0;
                TargetModel tm = new TargetModel();
                Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
                Map<Integer, Long> partnerTicketCount = ticketRepository.selectAllOpenTicketsGroupByRetailer();

                LOGGER.info("partnerTicketCount {}", partnerTicketCount);

                List<PartnerTargetAchievementModel> ptams = new ArrayList<>();

                if (fofoIds != null && fofoIds.size() > 0) {
                        List<Integer> fofoIdl = new ArrayList<>(fofoIds);
                        List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(fofoIdl).stream()
                                        .filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toList());

                        LocalDateTime startDate = LocalDate.now().atStartOfDay();

                        if (dayValue.equals("previous")) {
                                startDate = LocalDate.now().minusDays(1).atStartOfDay();

                        }

                        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
                                        .selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));

                        if (!partnerDailyInvestments.isEmpty()) {
                                partnerDailyInvestmentMap = partnerDailyInvestments.stream()
                                                .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
                        }

                        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();

                        Map<Integer, CustomRetailer> customRetailers = fofoIdList.stream().map(x -> customRetailerMap.get(x))
                                        .filter(x -> x != null).collect(Collectors.toList()).stream()
                                        .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));

                        List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);

                        LOGGER.info("remarkIds {}", remarkIds);

                        long todayCollectionCount = 0;
                        if (!remarkIds.isEmpty()) {
                                todayCollectionCount = partnerCollectionRemarkRepository
                                                .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
                                                .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
                                                .collect(Collectors.counting());

                        }

                        Map<Integer, PartnerCollectionPlanModel> CollectionMap = partnerCollectionService
                                        .getCollectionMap(fofoIdList, startDate);

                        Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondayPlans = orderRepository
                                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
                                        .collect(Collectors.groupingBy(x -> x.getFofoId()));

                        LOGGER.info("partnerSecondayPlans {}", partnerSecondayPlans);
                        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
                                int fofoId = customRetailerEntry.getKey();
                                CustomRetailer customRetailer = customRetailerEntry.getValue();
                                float totalSecondaryPlan = 0;
                                float totalSecondaryAchivement = 0;

                                PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
                                ptam.setFofoId(fofoId);
                                ptam.setBusinessName(customRetailer.getBusinessName());
                                ptam.setMobile(customRetailer.getMobileNumber());

                                if (partnerDailyInvestmentMap.get(fofoId) != null) {
                                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
                                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
                                }

                                if (CollectionMap.get(fofoId) != null) {
                                        PartnerCollectionPlanModel collectionPlan = CollectionMap.get(fofoId);

                                        ptam.setRemark(collectionPlan.getRemark());
                                        ptam.setMessage(collectionPlan.getMessage());
                                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
                                        ptam.setRank(collectionPlan.getRank());
                                        Integer authId = collectionPlan.getAuthId();

                                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;

                                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));

                                        LOGGER.info("authId" + authId);

                                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
                                                float targetCollection = 0;

                                                if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
                                                        targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
                                                } else {
                                                        targetCollection = collectionPlan.getTargetPlan();
                                                }

                                                if (authId != null && authId == authUser.getId()) {

                                                        if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
                                                                totalPartnerTargetCollection += targetCollection;
                                                        }
                                                }

                                                ptam.setCollectionTarget(targetCollection);

                                                if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
                                                                && collectionPlan.getWalletTimestamp() != null
                                                                && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
                                                        if (authId != null && authId == authUser.getId()) {

                                                                totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
                                                        }
                                                        ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
                                                } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
                                                                && collectionPlan.getAchievementPlan() != null) {
                                                        if (authId != null && authId == authUser.getId()) {

                                                                totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
                                                        }
                                                        ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());

                                                }
                                        }

                                        if (authId != null && authId != authUser.getId()) {
                                                ptam.setAuthUser(authRepository.selectById(authId));

                                        }

                                        if (collectionPlan.getCommittedDate() != null) {

                                                ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
                                        }

                                }

                                // Secondary

                                PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
                                Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
                                if (partnerSecondayPlans.get(fofoId) != null) {
                                        long otherBrandSecondary = 0;
                                        for (PartnerSecondaryPlanModel pspm : partnerSecondayPlans.get(fofoId)) {
                                                Integer authId = pspm.getAuthId();
                                                if (!brands.contains(pspm.getBrand())) {
                                                        if (pspm.getAchievementPlan() != null) {
                                                                otherBrandSecondary += pspm.getAchievementPlan();
                                                        }
                                                } else {
                                                        otherPartnerSecondaryPlanModel = pspm;
                                                }
                                                if (pspm.getTargetPlan() != null) {
                                                        totalSecondaryPlan += pspm.getTargetPlan();
                                                }

                                                if (pspm.getAchievementPlan() != null) {
                                                        totalSecondaryAchivement += pspm.getAchievementPlan();
                                                }

                                                if (pspm.getCommittedDate() != null) {

                                                        ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
                                                }
                                                if (authId != null && authId == authUser.getId()) {

                                                        if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {

                                                                if (pspm.getCommittedDate().isEqual(startDate)) {
                                                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
                                                                }
                                                        }

                                                        if (pspm.getAchievementPlan() != null) {
                                                                totalPartnerAchievementSecondary += pspm.getAchievementPlan();
                                                        }

                                                }
                                        }
                                        if (otherPartnerSecondaryPlanModel != null) {
                                                otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
                                        }
                                        secondaryModelMap = partnerSecondayPlans.get(fofoId).stream()
                                                        .filter(x -> brands.contains(x.getBrand()))
                                                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));

                                        if (secondaryModelMap.containsKey("Others")) {
                                                PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
                                                psp.setAchievementPlan(otherBrandSecondary);
                                        } else {
                                                secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0,
                                                                otherBrandSecondary, authUser.getId(), null));
                                        }
                                        for (String brand : brands) {
                                                if (!secondaryModelMap.containsKey(brand)) {
                                                        secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0,
                                                                        (long) 0, authUser.getId(), null));
                                                }
                                        }

                                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
                                                Integer authId = secondaryModelEntry.getValue().getAuthId();
                                                if (authId != null && authId != authUser.getId()) {
                                                        secondaryModelEntry.getValue().setAuthUser(authRepository.selectById(authId));
                                                        ptam.setSecondaryColor("red");
                                                }

                                        }

                                        ptam.setPartnerSecondaryModel(secondaryModelMap);
                                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
                                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
                                        // Secondary

                                } else {
                                        for (String brand : brands) {
                                                PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
                                                pspm.setAchievementPlan((long) 0);
                                                pspm.setTargetPlan((long) 0);
                                                pspm.setBrand(brand);
                                                pspm.setFofoId(fofoId);
                                                secondaryModelMap.put(brand, pspm);
                                        }
                                        ptam.setPartnerSecondaryModel(secondaryModelMap);
                                }

                                if (!partnerTicketCount.isEmpty()) {
                                        if (partnerTicketCount.get(fofoId) != null) {
                                                ptam.setTicketCount(partnerTicketCount.get(fofoId));
                                        } else {
                                                ptam.setTicketCount(0);

                                        }
                                }

                                ptams.add(ptam);

                        }

                        tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
                        tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
                        tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
                        tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
                        tm.setTodayCollectionCount((int) todayCollectionCount);

                        tm.setTargetAchievement(ptams.stream().sorted(Comparator.comparing(PartnerTargetAchievementModel::getRank))
                                        .collect(Collectors.toList()));

                }

                return responseSender.ok(tm);

        }

        @RequestMapping(value = "/target", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> createPartnerTarget(HttpServletRequest request,
                        @RequestBody PartnerTargetAchievementModel ptam) throws ProfitMandiBusinessException {

                LOGGER.info("ptam" + ptam);

                AuthUser authUser = authRepository.selectByGmailId(ptam.getCreatedBy());

                if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
                                || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
                        PartnerCollectionPlan partnerCollectionPlan = partnerCollectionPlanRepository
                                        .selectByLocalDate(LocalDate.now(), ptam.getFofoId(), true);
                        LOGGER.info("pcp" + partnerCollectionPlan);

                        if (partnerCollectionPlan == null) {
                                if (ptam.getCollectionTarget() > 0) {

                                        partnerCollectionPlan = new PartnerCollectionPlan();
                                        partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
                                        partnerCollectionPlan.setAuthId(authUser.getId());
                                        partnerCollectionPlan.setFofoId(ptam.getFofoId());
                                        partnerCollectionPlan.setActive(true);
                                        partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
                                        partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
                                        partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
                                        partnerCollectionPlanRepository.persist(partnerCollectionPlan);

                                }

                        } else {

                                if (partnerCollectionPlan.getCollectionPlan() != ptam.getCollectionTarget()) {
                                        float totalCollectionPlan = partnerCollectionPlan.getCollectionPlan() + 10000;
                                        if (authUser.getId() == partnerCollectionPlan.getAuthId()) {

                                                if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
                                                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
                                                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
                                                        partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
                                                        partnerCollectionPlan.setActive(true);
                                                        partnerCollectionPlan
                                                                        .setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
                                                        partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
                                                } else {
                                                        throw new ProfitMandiBusinessException("collection target", "",
                                                                        "collection target should be more than " + totalCollectionPlan);
                                                }

                                        } else {

                                                if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
                                                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
                                                                || ptam.getCollectionTarget() >= totalCollectionPlan) {

                                                        partnerCollectionPlan.setActive(false);
                                                        partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
                                                        partnerCollectionPlan = new PartnerCollectionPlan();
                                                        partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
                                                        partnerCollectionPlan.setAuthId(authUser.getId());
                                                        partnerCollectionPlan.setFofoId(ptam.getFofoId());
                                                        partnerCollectionPlan.setActive(true);
                                                        partnerCollectionPlan
                                                                        .setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
                                                        partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
                                                        partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
                                                        partnerCollectionPlanRepository.persist(partnerCollectionPlan);
                                                } else {
                                                        throw new ProfitMandiBusinessException("collection target", "",
                                                                        "collection target should be more than " + totalCollectionPlan);
                                                }
                                        }
                                }

                                if ((LocalDate.now().atStartOfDay().equals(ptam.getCollectionCommitmentDate().atStartOfDay())
                                                || ptam.getCollectionCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
                                                && partnerCollectionPlan.getCollectionPlan() == ptam.getCollectionTarget()) {
                                        partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
                                        partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
                                }

                        }

                        PartnerCollectionRemark pcr = new PartnerCollectionRemark();
                        pcr.setFofoId(ptam.getFofoId());
                        pcr.setAuthId(authUser.getId());
                        pcr.setMessage("Collection plan for" + ptam.getCollectionCommitmentDate());
                        pcr.setRemark(CollectionRemark.COLLECTION_PLAN);
                        pcr.setCreateTimestamp(LocalDateTime.now());
                        partnerCollectionRemarkRepository.persist(pcr);
                } else {
                        throw new ProfitMandiBusinessException("Date", "",
                                        "you can't select the back date " + ptam.getCollectionCommitmentDate());
                }

                for (Entry<String, PartnerSecondaryPlanModel> pspm : ptam.getPartnerSecondaryModel().entrySet()) {

                        if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
                                        || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
                                PartnerSecondaryPlanModel plan = pspm.getValue();
                                PartnerSecondaryPlan psp = partnerSecondaryPlanRepository.selectByLocalDateBrand(plan.getBrand(),
                                                LocalDate.now(), ptam.getFofoId(), true);
                                LOGGER.info("psp" + psp);

                                if (psp == null) {
                                        if (plan.getTargetPlan() != null && plan.getTargetPlan() > 0) {

                                                psp = new PartnerSecondaryPlan();
                                                psp.setAuthId(authUser.getId());
                                                psp.setBrand(pspm.getKey());
                                                psp.setFofoId(pspm.getValue().getFofoId());
                                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
                                                psp.setCreateTimestamp(LocalDateTime.now());
                                                psp.setUpdatedTimestamp(LocalDateTime.now());
                                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
                                                psp.setActive(true);
                                                partnerSecondaryPlanRepository.persist(psp);
                                        }

                                } else {
                                        if (plan.getTargetPlan() != psp.getSecondaryPlan()) {
                                                float totalSecondaryPlan = psp.getSecondaryPlan() + 10000;
                                                if (authUser.getId() == plan.getAuthId()) {
                                                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
                                                                        || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
                                                                        || plan.getTargetPlan() >= totalSecondaryPlan) {
                                                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
                                                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
                                                                psp.setUpdatedTimestamp(LocalDateTime.now());
                                                                psp.setActive(true);
                                                        } else {
                                                                throw new ProfitMandiBusinessException("secondary target", "",
                                                                                "secondary target should be more than " + totalSecondaryPlan);
                                                        }

                                                } else {

                                                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
                                                                        || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
                                                                        || plan.getTargetPlan() >= totalSecondaryPlan) {

                                                                psp.setUpdatedTimestamp(LocalDateTime.now());
                                                                psp.setActive(false);
                                                                psp = new PartnerSecondaryPlan();
                                                                psp.setAuthId(authUser.getId());
                                                                psp.setBrand(pspm.getKey());
                                                                psp.setFofoId(pspm.getValue().getFofoId());
                                                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
                                                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
                                                                psp.setCreateTimestamp(LocalDateTime.now());
                                                                psp.setUpdatedTimestamp(LocalDateTime.now());
                                                                psp.setActive(true);
                                                                partnerSecondaryPlanRepository.persist(psp);
                                                        } else {
                                                                throw new ProfitMandiBusinessException("secondary target", "",
                                                                                "secondary target should be more than " + totalSecondaryPlan);
                                                        }
                                                }
                                        }

                                        if ((LocalDate.now().atStartOfDay().equals(ptam.getSecondaryCommitmentDate().atStartOfDay())
                                                        || ptam.getSecondaryCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
                                                        && plan.getTargetPlan() == psp.getSecondaryPlan()) {
                                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
                                                psp.setUpdatedTimestamp(LocalDateTime.now());
                                        }

                                }
                        } else {
                                throw new ProfitMandiBusinessException("Date", "",
                                                "you can't select the back date " + ptam.getSecondaryCommitmentDate());
                        }

                }

                return responseSender.ok(true);

        }

        @RequestMapping(value = "/viewTickets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> viewTickets(HttpServletRequest request, @RequestParam int fofoId)
                        throws ProfitMandiBusinessException {
                List<Ticket> tickets = ticketRepository.selectAllOpenTicketByRetailer(fofoId);

                List<TicketViewModel> viewList = new ArrayList<>();
                for (Ticket ticket : tickets) {

                        TicketViewModel ticketViewModel = new TicketViewModel();
                        ticketViewModel.setId(ticket.getId());
                        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
                        TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());

                        ticketViewModel.setCategoryName(ticketCategory.getName());
                        ticketViewModel.setSubCategoryName(ticketSubCategory.getName());
                        ticketViewModel.setCreatedTimestamp(ticket.getCreateTimestamp());

                        viewList.add(ticketViewModel);
                }
                return responseSender.ok(viewList);

        }

        @RequestMapping(value = "/viewRecentTickets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> viewRecentTickets(HttpServletRequest request, @RequestParam int fofoId)
                        throws ProfitMandiBusinessException {
                List<TicketViewModel> viewList = ticketRepository.selectRecentClosedTicket(fofoId,
                                LocalDateTime.now().minusDays(20));

                return responseSender.ok(viewList);

        }

        @RequestMapping(value = "/createTicket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> createTicket(HttpServletRequest request) throws ProfitMandiBusinessException {
                List<TicketCategory> ticketCategories = csService.getAllTicketCategotyFromSubCategory();

                return responseSender.ok(ticketCategories);
        }

        @RequestMapping(value = "/getSubCategoriesByCategoryId", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })

        public ResponseEntity<?> getSubCategoriesByCategoryId(HttpServletRequest request,
                        @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, Model model) {
                List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll(categoryId);
                LOGGER.info(ticketSubCategories);
                return responseSender.ok(ticketSubCategories);
        }

        @RequestMapping(value = "/createTicket", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> createTicket(HttpServletRequest request, @RequestParam(name = "categoryId") int categoryId,
                        @RequestParam(name = "subCategoryId") int subCategoryId, @RequestParam(name = "message") String message,
                        @RequestParam(name = "fofoId") int fofoId) throws Exception {

                int id = (int) request.getAttribute("userId");

                LOGGER.info("id" + id);

                User user = userRepository.selectById(id);

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

                List<Ticket> tickets = ticketRepository.selectAllResolvedMarkedTicketByCreator(fofoId);
                if (tickets.size() > 3 || tickets.size() == 3) {
                        return responseSender.ok(false);
                } else {
                        csService.createTicket(fofoId, categoryId, subCategoryId, message);

                        PartnerCollectionRemark pcr = new PartnerCollectionRemark();
                        pcr.setFofoId(fofoId);
                        pcr.setAuthId(authUser.getId());
                        pcr.setMessage("Ticket Created");
                        pcr.setRemark(CollectionRemark.TICKET_CREATED);
                        pcr.setCreateTimestamp(LocalDateTime.now());
                        partnerCollectionRemarkRepository.persist(pcr);

                }
                return responseSender.ok(true);
        }

        @RequestMapping(value = "/getCollectionRemark", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> getCollectionRemark(HttpServletRequest request) throws ProfitMandiBusinessException {
                List<CollectionRemark> remarks = Arrays.asList(CollectionRemark.values()).stream()
                                .filter(x -> !x.equals(CollectionRemark.COLLECTION_PLAN)).collect(Collectors.toList());
                return responseSender.ok(remarks);
        }

        @RequestMapping(value = "/createPartnerColectionRemark", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({

                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> createPartnerColectionRemark(HttpServletRequest request,
                        @RequestBody PartnerCollectionRemarkModel partnerCollectionRemarkModel)
                        throws ProfitMandiBusinessException {
                AuthUser authUser = authRepository.selectByGmailId(partnerCollectionRemarkModel.getGmailId());

                PartnerCollectionRemark pcr = new PartnerCollectionRemark();
                pcr.setFofoId(partnerCollectionRemarkModel.getFofoId());
                pcr.setAuthId(authUser.getId());
                pcr.setMessage(partnerCollectionRemarkModel.getMessage());
                pcr.setRemark(partnerCollectionRemarkModel.getRemark());
                pcr.setCreateTimestamp(LocalDateTime.now());
                partnerCollectionRemarkRepository.persist(pcr);
                return responseSender.ok(true);

        }

        @RequestMapping(value = "/uploadFranchiseeVisit", method = RequestMethod.POST)
        public ResponseEntity<?> readCsvFileAndSetLead(HttpServletRequest request, @RequestPart MultipartFile multipartFile)
                        throws Throwable {

                int id = (int) request.getAttribute("userId");

                LOGGER.info("id" + id);

                User user = userRepository.selectById(id);

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

                String fileName = multipartFile.getName();
                String fileNames = multipartFile.getOriginalFilename();

                LOGGER.info("fileName" + fileName);
                LOGGER.info("fileNames" + fileNames);

                List<CSVRecord> records = FileUtil.readFile(multipartFile);

                for (CSVRecord record : records) {
                        FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
                        franchiseeVisit.setFofoId(Integer.parseInt(record.get(0)));
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(Integer.parseInt(record.get(0)));

                        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
                        franchiseeVisit.setAgenda(record.get(1));
                        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
                        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);

                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
                        LOGGER.info(record.get(1));
                        LocalDate dateTime = LocalDate.parse(record.get(2), formatter);

                        franchiseeVisit.setScheduleTimestamp(dateTime.atStartOfDay());
                        // change

                        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
                        franchiseeVisit.setCreatedBy(authUserName);
                        franchiseeVisit.setAuthId(authUser.getId());

                        franchiseeVisitRepository.persist(franchiseeVisit);

                        return responseSender.ok(true);
                }

                return responseSender.ok(true);

        }

        @RequestMapping(value = "/downloadFranchiseeVisitTemplate", method = RequestMethod.GET)
        public ResponseEntity<?> downloadFranchiseeVisitTemplate(HttpServletRequest request) throws Exception {

                // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                List<List<?>> rows = new ArrayList<>();

                org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = FileUtil
                                .getCSVByteStream(Arrays.asList("Partner Id", "Agenda", "Schedule Timestamp"), rows);

                try {
                        byteArrayOutputStream.close();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

                String filename = "template.csv";
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/csv");
                headers.setContentDispositionFormData(filename, filename);

                headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

                ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
                                HttpStatus.OK);
                return response;

        }

        @RequestMapping(value = "/markVisitAttendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> markVisitAttendance(HttpServletRequest request, @RequestParam(name = "id") int id)
                        throws ProfitMandiBusinessException {
                FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);

                franchiseeVisit.setVisitTimestamp(LocalDateTime.now());

                return responseSender.ok(true);

        }
}