Subversion Repositories SmartDukaan

Rev

Rev 30306 | Rev 30332 | 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 com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
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.PartnerSecondaryPlan;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
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.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.*;
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.PartnerSecondaryPlanRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
import com.spice.profitmandi.dao.repository.dtr.*;
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.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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
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 javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@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;

        @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.setSchelduleTimestamp(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());
                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);

                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.setResolution(resolution);
                        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
                        franchiseeActivity.setAction(action);
                        franchiseeActivity.setSchelduleTimestamp(schelduleTimestamp);
                        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
                        franchiseeActivityRepository.persist(franchiseeActivity);
                        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
                        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
                        franchiseeVisitRepository.persist(franchiseeVisit);

                } else {
                        franchiseeActivity.setResolution(resolution);
                        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
                        franchiseeActivity.setAction(action);
                        franchiseeActivity.setSchelduleTimestamp(null);
                        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
                        franchiseeActivityRepository.persist(franchiseeActivity);
                        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
                        franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
                        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);

        }

        @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 = "/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);

                Set<Integer> fofoIds = authUserPartnerMappingRepository.selectByAuthId(authUser.getId()).stream()
                                .map(x -> x.getFofoId()).collect(Collectors.toSet());

                if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")) {

                        fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> !x.isInternal() && x.isActive())
                                        .map(x -> x.getId()).collect(Collectors.toSet());

                }

                if (authUser.getEmailId().equals("mohit.gulati@smartdukaan.com")
                                || authUser.getEmailId().equals("manish.gupta@smartdukaan.com")) {

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

                        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<>();

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

                if (fofoIds.size() > 0 && fofoIds != null) {
                        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> customRetailers = retailerService.getFofoRetailers(fofoIdList);

                        /*
                         * Map<Integer, PartnerCollectionPlanModel> collectionPlans =
                         * userWalletRepository .getPartnerWiseTargetCollections(fofoIdList,
                         * startDate).stream() .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
                         */

                        Map<Integer, PartnerCollectionAchievementModel> collectionAchievementMap = userWalletRepository
                                        .getPartnerWiseCollectionAchievement(fofoIdList, startDate).stream()
                                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

                        Set<Integer> maxCommitedIds = partnerCollectionPlanRepository.selectMaxCommitedDate(fofoIdList, startDate)
                                        .stream().map(x -> x.getId()).collect(Collectors.toSet());

                        List<PartnerCollectionPlanModel> foundCollections = partnerCollectionPlanRepository
                                        .getUntouchedPartner(new ArrayList<>(maxCommitedIds));

                        List<Integer> foundCollectionIds = foundCollections.stream().map(x -> x.getPcpId())
                                        .collect(Collectors.toList());

                        Set<Integer> foundCollectionFofoIds = foundCollections.stream().map(x -> x.getFofoId())
                                        .collect(Collectors.toSet());

                        List<Integer> unfoundCollectionIds = maxCommitedIds.stream().filter(x -> !foundCollectionIds.contains(x))
                                        .collect(Collectors.toList());

                        List<PartnerCollectionPlan> unfoundCollections = partnerCollectionPlanRepository
                                        .selectByIds(unfoundCollectionIds);

                        Set<Integer> unfoundCollectionFofoIds = unfoundCollections.stream().map(x -> x.getFofoId())
                                        .collect(Collectors.toSet());

                        List<Integer> untouchedCollectionFofoIds = fofoIdList.stream()
                                        .filter(x -> !foundCollectionFofoIds.contains(x) && !unfoundCollectionFofoIds.contains(x))
                                        .collect(Collectors.toList());

                        for (PartnerCollectionPlan unfoundCollection : unfoundCollections) {
                                PartnerCollectionPlanModel pcpm = new PartnerCollectionPlanModel();

                                pcpm.setFofoId(unfoundCollection.getFofoId());
                                pcpm.setTargetPlan((long) unfoundCollection.getCollectionPlan());
                                pcpm.setAuthId(unfoundCollection.getAuthId());
                                pcpm.setCommittedDate(unfoundCollection.getCommitedTimestamp());
                                pcpm.setCreatedDate(unfoundCollection.getCreateTimestamp());
                                pcpm.setPcpId(unfoundCollection.getId());

                                foundCollections.add(pcpm);

                        }
                        for (Integer fofoId : untouchedCollectionFofoIds) {

                                PartnerCollectionPlanModel pcpm = new PartnerCollectionPlanModel();
                                pcpm.setFofoId(fofoId);
                                foundCollections.add(pcpm);
                        }

                        Map<Integer, PartnerCollectionPlanModel> foundCollectionMap = foundCollections.stream()
                                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

                        Map<Integer, PartnerCollectionPlan> todayTarget = partnerCollectionPlanRepository
                                        .selectByLocalDateAndFofoIds(startDate.toLocalDate(), fofoIdList, true).stream()
                                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

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

                        int todayCollectionCount = todayTarget.size();

                        for (PartnerCollectionPlanModel collectionModel : foundCollections) {

                                if (collectionModel.getAchievementPlan() == null) {
                                        collectionModel.setAchievementPlan((long) 0);
                                }
                                if (collectionModel.getCommittedDate() == null) {
                                        collectionModel.setRank(3);
                                } else if (collectionModel.getCommittedDate().toLocalDate().equals(LocalDate.now())
                                                && collectionModel.getCreatedDate().toLocalDate().isBefore(LocalDate.now())) {
                                        collectionModel.setRank(1);
                                } else if (collectionModel.getCommittedDate().toLocalDate().isAfter(LocalDate.now())) {
                                        collectionModel.setRank(4);
                                } else if (collectionModel.getCommittedDate().toLocalDate().isBefore(LocalDate.now().minusDays(4))
                                                && collectionModel.getAchievementPlan() >= 5000) {
                                        collectionModel.setRank(3);
                                        collectionModel.setTargetPlan((long) 0);
                                        collectionModel.setAuthId(0);
                                        collectionModel.setCommittedDate(null);

                                        if (todayTarget.get(collectionModel.getFofoId()) != null) {
                                                if (todayTarget.get(collectionModel.getFofoId()).getCreateTimestamp().toLocalDate()
                                                                .isEqual(LocalDate.now())) {
                                                        collectionModel.setTargetPlan(
                                                                        (long) todayTarget.get(collectionModel.getFofoId()).getCollectionPlan());
                                                }
                                        }

                                } else if (collectionModel.getCommittedDate().toLocalDate().isBefore(LocalDate.now())
                                                && collectionModel.getAchievementPlan() < 5000) {
                                        collectionModel.setRank(2);
                                } else {

                                        collectionModel.setRank(5);
                                        if (!collectionModel.getCreatedDate().toLocalDate().equals(LocalDate.now())) {
                                                collectionModel.setTargetPlan((long) 0);
                                        }
                                }

                        }
                        LOGGER.info("updatedList {}", foundCollections);
                        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());

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

                                if (foundCollectionMap.get(fofoId) != null) {
                                        PartnerCollectionPlanModel collectionPlan = foundCollectionMap.get(fofoId);
                                        PartnerCollectionAchievementModel collectionAchievement = collectionAchievementMap.get(fofoId);

                                        ptam.setRank(collectionPlan.getRank());
                                        Integer authId = collectionPlan.getAuthId();

                                        if (collectionPlan.getRank() == 1) {
                                                ptam.setCollectionColor("#007bff");
                                        } else if (collectionPlan.getRank() == 2) {
                                                ptam.setCollectionColor("#ffc107");
                                        } else if (collectionPlan.getRank() == 3) {
                                                ptam.setCollectionColor("#dc3545");
                                        } else if (collectionPlan.getRank() == 4) {
                                                ptam.setCollectionColor("#6c757d");
                                        } else {
                                                ptam.setCollectionColor("White");
                                        }

                                        LOGGER.info("authId" + authId);

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

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

                                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
                                                        totalPartnerTargetCollection += targetCollection;
                                                }
                                                ptam.setCollectionTarget(targetCollection);
                                        }
                                        if (collectionAchievement.getAmount() != null) {
                                                totalPartnerAchievementCollection += collectionAchievement.getAmount();

                                                ptam.setCollectionAchievement(collectionAchievement.getAmount());
                                        }

                                        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);
                                }

                                ptams.add(ptam);

                        }

                        tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
                        tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
                        tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
                        tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
                        tm.setTodayCollectionCount(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());
                                }
                        }
                } 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() > 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);

        }

}