Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.dao.repository.cs;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Random;
import java.util.Set;
import java.util.function.IntPredicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

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.util.Utils;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.cs.Activity;
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.cs.Region;
import com.spice.profitmandi.dao.entity.cs.Ticket;
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
import com.spice.profitmandi.dao.entity.cs.TicketCategory;
import com.spice.profitmandi.dao.entity.cs.TicketSubCategory;
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.service.user.RetailerService;

import in.shop2020.utils.HelperService.authenticateCatalogUser_args;

@Component
public class CsServiceImpl implements CsService {

        private static final int ALL_PARTNERS_REGION = 5;

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

        private static final String ASSIGNED_TICKET = "Dear %s, New ticket #%s created by %s has been assigned to you. Regards\nSmartdukaan";
        private static final String ESCALATED_TICKET = "Dear %s, Ticket #%s created by %s has been escalated to you. Regards\nSmartdukaan";
        private static final String CATEGORY_CHANGED_TICKET = "Dear team, Category of Ticket #%s created by %s has been changed to %s. Regards\nSmartdukaan";
        private static final String ASSINMENT_SUBJECT = "Assignment Ticket";

        @Autowired
        TicketRepository ticketRepository;

        @Autowired
        JavaMailSender mailSender;

        @Autowired
        TicketCategoryRepository ticketCategoryRepository;

        @Autowired
        TicketSubCategoryRepository ticketSubCategoryRepository;

        @Autowired
        ActivityRepository activityRepository;

        @Autowired
        PartnerRegionRepository partnerRegionRepository;

        @Autowired
        private PositionRepository positionRepository;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private RegionRepository regionRepository;

        @Autowired
        private TicketAssignedRepository ticketAssignedRepository;

        @Autowired
        private PartnersPositionRepository partnersPositionRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Override
        public void createTicket(int fofoId, int categoryId, int subcategoryId, String message)
                        throws ProfitMandiBusinessException {

                ActivityType type = ActivityType.OPENED;
                Ticket ticket = new Ticket();
                ticket.setSubCategoryId(subcategoryId);
                ticket.setFofoId(fofoId);
                ticket.setCreateTimestamp(LocalDateTime.now());
                ticket.setUpdateTimestamp(LocalDateTime.now());
                ticket.setHappyCode(getRandomString());
                ticketRepository.persist(ticket);
                this.addActivity(ticket, this.createActivity(type, message, 0));
                this.assignTicket(ticket);

        }

        @Override
        public void assignTicket(Ticket ticket) throws ProfitMandiBusinessException {
                TicketAssigned ticketAssigned = null;
                EscalationType newEscalationType = EscalationType.L1;
                if (ticket.getAssignmentId() > 0) {
                        ticketAssigned = ticketAssignedRepository.selectById(ticket.getAssignmentId());
                        newEscalationType = ticketAssigned.getEscalationType().next();
                        if (newEscalationType == null || newEscalationType.equals(EscalationType.Final)) {
                                LOGGER.info("Cant escalate further");
                                return;
                        }
                } else {
                        ticket.setL1AuthUser(0);
                        ticket.setL2AuthUser(0);
                        ticket.setL3AuthUser(0);
                        ticket.setL4AuthUser(0);
                        ticket.setL5AuthUser(0);
                }
                ticket.setUpdateTimestamp(LocalDateTime.now());
                TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
                TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
                Map<Integer, EscalationType> escalationUserMap = new HashedMap<>();
                Set<Integer> assigneeUserIds = new LinkedHashSet<>();
                EscalationType escalationTypeNext = newEscalationType;
                do {
                        int assigneeUserId = this.getAuthUserId(ticketCategory.getId(), escalationTypeNext, ticket.getFofoId());
                        if (assigneeUserId == 0) {
                                escalationTypeNext = escalationTypeNext.next();
                                LOGGER.info("Escalation type next {}", escalationTypeNext);
                                continue;
                        }
                        assigneeUserIds.add(assigneeUserId);
                        escalationUserMap.put(assigneeUserId, escalationTypeNext);
                        switch (escalationTypeNext) {
                        case L1:
                                ticket.setL1AuthUser(assigneeUserId);
                                break;
                        case L2:
                                ticket.setL2AuthUser(assigneeUserId);
                                break;
                        case L3:
                                ticket.setL3AuthUser(assigneeUserId);
                                break;
                        case L4:
                                ticket.setL4AuthUser(assigneeUserId);
                                break;
                        case L5:
                                ticket.setL5AuthUser(assigneeUserId);
                                break;

                        default:
                                break;
                        }
                        escalationTypeNext = escalationTypeNext.next();
                        // LOGGER.info("Escalation type next {}", escalationTypeNext);
                } while (!escalationTypeNext.equals(EscalationType.Final));

                int assigneeAuthId = assigneeUserIds.stream().findFirst().orElse(0);

                int managerAuthId = 0;
                EscalationType assigneeEscalationType = null;
                if (assigneeAuthId == 0) {
                        assigneeAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
                        assigneeEscalationType = EscalationType.Final;
                        managerAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
                } else {
                        assigneeEscalationType = escalationUserMap.get(assigneeAuthId);
                        managerAuthId = assigneeUserIds.stream().skip(1).findFirst().orElse(0);
                        if (managerAuthId == 0) {
                                managerAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
                        }
                }

                TicketAssigned ticketAssignedNew = new TicketAssigned();
                ticketAssignedNew.setTicketId(ticket.getId());
                ticketAssignedNew.setAssineeId(assigneeAuthId);
                ticketAssignedNew.setEscalationType(assigneeEscalationType);
                ticketAssignedNew.setManagerId(managerAuthId);
                ticketAssignedNew.setCreateTimestamp(LocalDateTime.now());
                ticketAssignedRepository.persist(ticketAssignedNew);
                LOGGER.info(ticketAssigned);

                AuthUser authUser = authRepository.selectById(ticketAssignedNew.getAssineeId());
                AuthUser authUserManager = null;

                // Dont send cc mail if both are same
                if (managerAuthId != assigneeAuthId) {
                        authUserManager = authRepository.selectById(managerAuthId);
                }
                ticket.setAssignmentId(ticketAssignedNew.getId());
                this.sendAssignedTicketMail(authUser, Arrays.asList(authUserManager), ticket, ticketAssigned != null);
                if (!ticketAssignedNew.getEscalationType().equals(EscalationType.L1)) {
                        this.addActivity(ticket, this.createActivity(ActivityType.ESCALATED,
                                        "Ticket ecalated and assigned to " + authUser.getName(), 0));
                } else {
                        this.addActivity(ticket,
                                        this.createActivity(ActivityType.ASSIGNED, "Ticket assigned to " + authUser.getName(), 0));
                }
        }

        @Override
        public void updateTicket(int categoryId, int subCategoryId, Ticket ticket) throws ProfitMandiBusinessException {

                TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.getTicketSubCategoryMap().get(subCategoryId);
                if (ticketSubCategory == null) {
                        throw new ProfitMandiBusinessException("Could not find subCategoryId " + subCategoryId + "- " + categoryId,
                                        "Problem", "Problem");
                }
                String storeName = retailerService.getAllFofoRetailers().get(ticket.getFofoId()).getBusinessName();
                List<TicketAssigned> oldTicketAssignedList = ticketAssignedRepository
                                .selectByTicketIds(Arrays.asList(ticket.getId()));
                for (TicketAssigned oldTicketAssigned : oldTicketAssignedList) {
                        ticketAssignedRepository.delete(oldTicketAssigned);
                }

                if (ticket.getSubCategoryId() != ticketSubCategory.getId()) {
                        ticket.setSubCategoryId(ticketSubCategory.getId());
                        List<Integer> oldAssignedAuthUserIds = oldTicketAssignedList.stream().map(x -> x.getAssineeId())
                                        .collect(Collectors.toList());
                        List<String> oldAssignedEmailIds = authRepository.selectAllAuthUserByIds(oldAssignedAuthUserIds).stream()
                                        .map(x -> x.getEmailId()).collect(Collectors.toList());
                        String mailTo = oldAssignedEmailIds.remove(0);
                        String message = String.format(CATEGORY_CHANGED_TICKET, ticket.getId(), storeName,
                                        ticketSubCategory.getTicketCategory().getName() + " - " + ticketSubCategory.getName());
                        try {
                                Utils.sendMailWithAttachments(mailSender, mailTo, oldAssignedEmailIds.toArray(new String[0]),
                                                "Ticket Category/Subcategory Changed", message, null);
                        } catch (Exception e) {
                                LOGGER.info("Could not send mail for ticket {}", ticket.toString());
                        }
                }

                Activity categoryChangedActivity = this.createActivity(ActivityType.CATEGORY_CHANGED, "Category changed to "
                                + ticketSubCategory.getTicketCategory().getName() + " - " + ticketSubCategory.getName(), 0);
                this.addActivity(ticket, categoryChangedActivity);
                ticket.setAssignmentId(0);
                this.assignTicket(ticket);

        }

        @Override
        public Activity createActivity(ActivityType activityType, String message, int createdBy) {
                Activity activity = new Activity();
                activity.setMessage(message);
                activity.setCreatedBy(createdBy);
                activity.setType(activityType);
                activity.setCreateTimestamp(LocalDateTime.now());
                activityRepository.persist(activity);
                return activity;
        }

        @Override
        public int getAuthUserId(int categoryId, EscalationType escalationType, int fofoId) {
                int authUserId = 0;
                List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId,
                                escalationType);
                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());
                // Add all Partner regions id
                regionIds.add(ALL_PARTNERS_REGION);
                LOGGER.info("Escalation Type {}, Region Ids {}", escalationType, regionIds);
                List<Integer> partnerPositionsIds = partnersPositionRepository
                                .selectByRegionIdAndPartnerId(regionIds, Arrays.asList(0, fofoId)).stream().map(x -> x.getPositionId())
                                .collect(Collectors.toList());
                positions = positions.stream().filter(x -> partnerPositionsIds.contains(x.getId()))
                                .collect(Collectors.toList());
                LOGGER.info("User List List {}", positions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
                if (positions.size() > 0) {
                        List<AuthUser> authUsers = authRepository.selectAllAuthUserByIds(
                                        positions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
                        authUsers = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toList());
                        if (authUsers.size() > 0) {
                                authUserId = authUsers.get(0).getId();
                                /*
                                 * Random rand = new Random(); authUserId =
                                 * authUsers.get(rand.nextInt(authUsers.size())).getId();
                                 */
                        }
                }
                return authUserId;

        }

        @Override
        public void addActivity(Ticket ticket, Activity activity) {
                activity.setTicketId(ticket.getId());
                ticket.setLastActivity(activity.getType());
                ticket.setLastActivityId(activity.getId());
        }

        private String getRandomString() {
                int length = 4;
                boolean useLetters = false;
                boolean useNumbers = true;
                String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
                return generatedString;
        }

        @Override
        public void addPartnerToRegion(int regionId, List<Integer> fofoIds) {

                for (int fofoId : fofoIds) {
                        PartnerRegion partnerRegion = new PartnerRegion();
                        partnerRegion.setFofoId(fofoId);
                        partnerRegion.setRegionId(regionId);
                        partnerRegionRepository.persist(partnerRegion);
                }
        }

        @Override
        public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMap(List<TicketAssigned> ticketAssigneds) {
                Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();

                for (TicketAssigned ticketAssigned : ticketAssigneds) {
                        AuthUser authUser = authRepository.selectById(ticketAssigned.getAssineeId());
                        authUserIdAndAuthUserMap.put(ticketAssigned.getTicketId(), authUser);
                }
                return authUserIdAndAuthUserMap;
        }

        @Override
        public Map<Integer, AuthUser> getTicketIdAndAuthUserMapUsingTickets(List<Ticket> tickets) {
                Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();

                for (Ticket ticket : tickets) {
                        AuthUser authUser = authRepository.selectById(ticket.getL1AuthUser());
                        authUserIdAndAuthUserMap.put(ticket.getId(), authUser);
                }
                return authUserIdAndAuthUserMap;
        }

        @Override
        public Map<Integer, TicketSubCategory> getSubCategoryIdAndSubCategoryMap(List<Ticket> tickets) {
                Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = new HashMap<>();
                if (tickets != null) {
                        for (Ticket ticket : tickets) {
                                TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
                                subCategoryIdAndSubCategoryMap.put(ticket.getSubCategoryId(), ticketSubCategory);
                        }
                }
                return subCategoryIdAndSubCategoryMap;
        }

        @Override
        public Map<Integer, CustomRetailer> getPartnerByFofoIds(List<Ticket> tickets) {
                List<Integer> fofoIds = new ArrayList<>();
                LOGGER.info(tickets);
                if (tickets == null) {
                        return null;
                }
                for (Ticket ticket : tickets) {
                        fofoIds.add(ticket.getFofoId());
                }
                Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = retailerService.getFofoRetailers(fofoIds);
                return fofoIdsAndCustomRetailer;
        }

        @Override
        public List<TicketCategory> getAllTicketCategotyFromSubCategory() {

                List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll();
                HashSet<Integer> categoryIds = new HashSet<>();
                for (TicketSubCategory ticketSubcategory : ticketSubCategories) {
                        categoryIds.add(ticketSubcategory.getCategoryId());
                }
                List<TicketCategory> ticketcategories = ticketCategoryRepository.selectAll(new ArrayList<>(categoryIds));
                return ticketcategories;
        }

        @Override
        public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMapUsingPositions(List<Position> positions) {
                Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
                for (Position position : positions) {
                        AuthUser authUser = authRepository.selectById(position.getAuthUserId());
                        authUserIdAndAuthUserMap.put(position.getAuthUserId(), authUser);
                }
                return authUserIdAndAuthUserMap;
        }

        @Override
        public Map<Integer, TicketCategory> getCategoryIdAndCategoryUsingPositions(List<Position> positions) {
                Map<Integer, TicketCategory> categoryIdAndCategoryMap = new HashMap<>();
                for (Position position : positions) {
                        TicketCategory ticketCategory = ticketCategoryRepository.selectById(position.getCategoryId());
                        categoryIdAndCategoryMap.put(position.getCategoryId(), ticketCategory);
                }
                return categoryIdAndCategoryMap;
        }

        @Override
        public Map<Integer, Region> getRegionIdAndRegionMap(List<Position> positions) {
                Map<Integer, Region> regionIdAndRegionMap = new HashMap<>();
                for (Position position : positions) {
                        Region region = regionRepository.selectById(position.getRegionId());
                        regionIdAndRegionMap.put(position.getRegionId(), region);
                }
                return regionIdAndRegionMap;
        }

        private void sendAssignedTicketMail(AuthUser authUserTo, List<AuthUser> authUsersCc, Ticket ticket,
                        boolean isEscalated) throws ProfitMandiBusinessException {
                try {
                        String[] ccTo = authUsersCc.stream().filter(x -> x != null).map(x -> x.getEmailId()).toArray(String[]::new);

                        String messageFormat = null;
                        if (isEscalated) {
                                messageFormat = ESCALATED_TICKET;
                        } else {
                                messageFormat = ASSIGNED_TICKET;
                        }
                        String message = String.format(messageFormat, authUserTo.getName(), ticket.getId(),
                                        retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName());
                        Utils.sendMailWithAttachments(mailSender, authUserTo.getEmailId(), ccTo, ASSINMENT_SUBJECT, message, null);
                } catch (Exception e) {
                        e.printStackTrace();
                        throw new ProfitMandiBusinessException("Ticket Assingment", authUserTo.getEmailId(),
                                        "Could not send ticket assignment mail");
                }
        }

        @Override
        public Map<Integer, List<CustomRetailer>> getPositionCustomRetailerMap(List<Position> positions) {
                Map<Integer, List<CustomRetailer>> positionRetailerMap = new HashMap<>();
                for (Position position : positions) {
                        List<Integer> fofoIds = partnersPositionRepository.selectByPositionId(position.getId()).stream()
                                        .map(x -> x.getFofoId()).collect(Collectors.toList());

                        LOGGER.info("fofoIds - {}", fofoIds);
                        if (!fofoIds.isEmpty()) {
                                if (fofoIds.contains(0)) {
                                        fofoIds = partnerRegionRepository.selectByRegionId(position.getRegionId()).stream()
                                                        .map(x -> x.getFofoId()).collect(Collectors.toList());
                                        if (fofoIds.contains(0)) {
                                                fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
                                                                .collect(Collectors.toList());
                                        }

                                }
                                LOGGER.info("fofoIds - {}", fofoIds);
                                positionRetailerMap.put(position.getId(),
                                                new ArrayList<CustomRetailer>(retailerService.getFofoRetailers(fofoIds).values()));

                        }
                }
                return positionRetailerMap;
        }

        @Override
        public Map<Integer, List<CustomRetailer>> getRegionPartners(List<Position> positions) {
                Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = new HashedMap<>();
                for (Position position : positions) {
                        List<Integer> fofoIds = partnerRegionRepository.selectByRegionId(position.getRegionId()).stream()
                                        .map(x -> x.getFofoId()).collect(Collectors.toList());

                        if (!fofoIds.isEmpty()) {
                                if (fofoIds.contains(0)) {
                                        fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());

                                }

                                Map<Integer, CustomRetailer> fofoRetailers = retailerService.getFofoRetailers(fofoIds);
                                positionIdAndpartnerRegionMap.put(position.getRegionId(),
                                                new ArrayList<CustomRetailer>(fofoRetailers.values()));
                        }

                }

                return positionIdAndpartnerRegionMap;
        }

        @Override
        @Cacheable(value = "authUserEmailMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<String, Set<String>> getAuthUserPartnerEmailMapping() {
                Map<String, Set<String>> storeGuyMap = new HashMap<>();
                Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
                                .collect(Collectors.toSet());
                List<Position> categoryPositions = positionRepository
                                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
                Map<Integer, Position> positionsMap = categoryPositions.stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
                for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
                        int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
                        Set<String> partnerEmails = positionPartnerEntry.getValue().stream()
                                        .filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getEmail())
                                        .collect(Collectors.toSet());
                        AuthUser authUser = authRepository.selectById(authUserId);
                        if (authUser.isActive()) {
                                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
                                        storeGuyMap.put(authUser.getEmailId(), partnerEmails);
                                } else {
                                        storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
                                }
                        }
                }
                return storeGuyMap;
        }

        @Override
        @Cacheable(value = "authUserEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<String, Set<Integer>> getAuthUserPartnerIdMapping() {
                Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
                Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
                                .collect(Collectors.toSet());
                List<Position> categoryPositions = positionRepository
                                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
                Map<Integer, Position> positionsMap = categoryPositions.stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
                for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
                        int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
                        Set<Integer> partnerIds = positionPartnerEntry.getValue().stream()
                                        .filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId())
                                        .collect(Collectors.toSet());
                        AuthUser authUser = authRepository.selectById(authUserId);
                        if (authUser.isActive()) {
                                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
                                        storeGuyMap.put(authUser.getEmailId(), partnerIds);
                                } else {
                                        storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
                                }
                        }
                }
                return storeGuyMap;
        }

        @Override
        public List<String> getAuthUserByPartnerId(int fofoId) {

                List<String> emails = new ArrayList<>();
                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                regionIds.add(5);// All partners Id;
                List<Integer> fofoIds = new ArrayList<>();
                fofoIds.add(fofoId);
                fofoIds.add(0);

                LOGGER.info("fofoIds" + fofoIds);
                List<Integer> partnerPositionIds = partnersPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds)
                                .stream().map(x -> x.getPositionId()).collect(Collectors.toList());

                LOGGER.info("partnerPositionIds" + partnerPositionIds);

                for (Integer partnerPostionId : partnerPositionIds) {
                        Position position = positionRepository.selectByIdAndCategoryId(partnerPostionId,
                                        ProfitMandiConstants.TICKET_CATEGORY_SALES);
                        LOGGER.info("position" + position);
                        if (position != null) {

                                AuthUser authUser = authRepository.selectById(position.getAuthUserId());
                                LOGGER.info("authUser" + authUser);
                                emails.add(authUser.getEmailId());
                        }
                }

                return emails;
        }

        @Override
        public Map<EscalationType, String> getAuthUserAndEsclationTypeByPartnerId(int fofoId) {

                List<String> emails = new ArrayList<>();
                Map<EscalationType, String> emailEsclationTypeMap = new HashMap<>();
                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                regionIds.add(5);// All partners Id;
                List<Integer> fofoIds = new ArrayList<>();
                fofoIds.add(fofoId);
                fofoIds.add(0);

                LOGGER.info("fofoIds" + fofoIds);
                List<Integer> partnerPositionIds = partnersPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds)
                                .stream().map(x -> x.getPositionId()).collect(Collectors.toList());

                LOGGER.info("partnerPositionIds" + partnerPositionIds);

                for (Integer partnerPostionId : partnerPositionIds) {
                        Position position = positionRepository.selectByIdAndCategoryId(partnerPostionId,
                                        ProfitMandiConstants.TICKET_CATEGORY_SALES);
                        LOGGER.info("position" + position);
                        if (position != null) {

                                AuthUser authUser = authRepository.selectById(position.getAuthUserId());
                                LOGGER.info("authUser" + authUser);

                                emailEsclationTypeMap.put(position.getEscalationType(), authUser.getEmailId());
                        }
                }

                LOGGER.info("emailEsclationTypeMap" + emailEsclationTypeMap);

                return emailEsclationTypeMap;
        }

        @Override
        @Cacheable(value = "authUserIdPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, List<Integer>> getAuthUserIdPartnerIdMapping() {
                Map<Integer, List<Integer>> storeGuyMap = new HashMap<>();
                Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
                                .collect(Collectors.toSet());
                List<Position> categoryPositions = positionRepository
                                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
                Map<Integer, Position> positionsMap = categoryPositions.stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
                for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
                        int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
                        List<Integer> partnerIds = positionPartnerEntry.getValue().stream()
                                        .filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId())
                                        .collect(Collectors.toList());
                        AuthUser authUser = authRepository.selectById(authUserId);
                        if (authUser != null && authUser.isActive()) {
                                if (!storeGuyMap.containsKey(authUserId)) {
                                        storeGuyMap.put(authUserId, partnerIds);
                                } else {
                                        storeGuyMap.get(authUserId).addAll(partnerIds);
                                }
                        }
                }
                return storeGuyMap;
        }

        @Override
        @Cacheable(value = "L1L2Mapping", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, List<Integer>> getL2L1Mapping() {
                List<Position> l1SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
                                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
                List<Position> l2SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
                                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);

                LOGGER.info("position" + l1SalesPositions);
                Map<Integer, List<Integer>> authUserPartnerListMap = this.getAuthUserIdPartnerIdMapping();
                LOGGER.info("map" + authUserPartnerListMap);

                Map<Integer, List<Integer>> l2l1ListMap = new HashMap<>();

                for (Position l2SalePosition : l2SalesPositions) {
                        int l2AuthUserId = l2SalePosition.getAuthUserId();
                        if (authUserPartnerListMap.containsKey(l2SalePosition.getAuthUserId())) {
                                List<Integer> mappedL1AuthUsers = new ArrayList<>();
                                l2l1ListMap.put(l2AuthUserId, mappedL1AuthUsers);
                                List<Integer> l2FofoIds = authUserPartnerListMap.get(l2AuthUserId);
                                for (Position l1SalePosition : l1SalesPositions) {
                                        int l1AuthUserId = l1SalePosition.getAuthUserId();
                                        if (authUserPartnerListMap.containsKey(l1AuthUserId)) {
                                                List<Integer> l1FofoIds = authUserPartnerListMap.get(l1SalePosition.getAuthUserId());
                                                if (l2FofoIds.containsAll(l1FofoIds)) {
                                                        mappedL1AuthUsers.add(l1AuthUserId);
                                                }
                                        }

                                }
                        }

                }

                return l2l1ListMap;
        }

        @Override
        public Map<Integer, List<AuthUser>> getAssignedAuthList(List<Ticket> tickets) {
                if (tickets.size() == 0) {
                        return new HashMap<>();
                }
                List<TicketAssigned> ticketAssignedList = ticketAssignedRepository
                                .selectByTicketIds(tickets.stream().map(x -> x.getId()).collect(Collectors.toList()));
                List<Integer> authUserIds = ticketAssignedList.stream().map(x -> x.getAssineeId()).distinct()
                                .collect(Collectors.toList());
                Map<Integer, AuthUser> authUserMap = authRepository.selectAllAuthUserByIds(authUserIds).stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));
                return ticketAssignedList.stream().collect(Collectors.groupingBy(x -> x.getTicketId(),
                                Collectors.mapping(x -> authUserMap.get(x.getAssineeId()), Collectors.toList())));
        }

        @Override
        public Map<EscalationType, AuthUser> getAuthUserAndEsclationByPartnerId(int fofoId) {
                Map<EscalationType, AuthUser> authuserEsclationTypeMap = new HashMap<>();
                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                regionIds.add(5);// All partners Id;
                List<Integer> fofoIds = new ArrayList<>();
                fofoIds.add(fofoId);
                fofoIds.add(0);

                LOGGER.info("fofoIds" + fofoIds);
                List<Integer> partnerPositionIds = partnersPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds)
                                .stream().map(x -> x.getPositionId()).collect(Collectors.toList());

                LOGGER.info("partnerPositionIds" + partnerPositionIds);

                for (Integer partnerPostionId : partnerPositionIds) {
                        Position position = positionRepository.selectByIdAndCategoryId(partnerPostionId,
                                        ProfitMandiConstants.TICKET_CATEGORY_SALES);
                        LOGGER.info("position" + position);
                        if (position != null) {

                                AuthUser authUser = authRepository.selectById(position.getAuthUserId());
                                LOGGER.info("authUser" + authUser);

                                authuserEsclationTypeMap.put(position.getEscalationType(), authUser);
                        }
                }

                LOGGER.info("emailEsclationTypeMap" + authuserEsclationTypeMap);

                return authuserEsclationTypeMap;
        }

}