Subversion Repositories SmartDukaan

Rev

Rev 28825 | Rev 29580 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.ContentType;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ActivateItemModel;
import com.spice.profitmandi.common.model.ChartInvestmentModel;
import com.spice.profitmandi.common.model.ChartModel;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.Data;
import com.spice.profitmandi.common.model.DataInvestmentModel;
import com.spice.profitmandi.common.model.Legend;
import com.spice.profitmandi.common.model.Notification;
import com.spice.profitmandi.common.model.OnlineDeliveredOrderSum;
import com.spice.profitmandi.common.model.OptionModel;
import com.spice.profitmandi.common.model.PieLables;
import com.spice.profitmandi.common.model.ProfitMandiConstants;

import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
import com.spice.profitmandi.dao.model.ActivationImeiUpdationModel;
import com.spice.profitmandi.dao.model.BrandWiseActivatedModel;
import com.spice.profitmandi.dao.model.BrandWisePartnerSaleModel;
import com.spice.profitmandi.dao.model.BrandWiseUnbilledActivateStockModel;
import com.spice.profitmandi.dao.model.CreateOfferRequest;
import com.spice.profitmandi.dao.model.InStockBrandItemModel;
import com.spice.profitmandi.dao.model.InStockBrandModel;
import com.spice.profitmandi.dao.model.ItemWiseTertiaryModel;
import com.spice.profitmandi.dao.model.MonthSaleModel;
import com.spice.profitmandi.dao.model.PartnerDetailModel;
import com.spice.profitmandi.dao.model.PartnerPendingIndentItemModel;
import com.spice.profitmandi.dao.model.PriceDropBrandModel;
import com.spice.profitmandi.dao.model.PriceDropWithDetailsByYearMonthModel;
import com.spice.profitmandi.dao.model.PriceDropYearMonthModel;
import com.spice.profitmandi.dao.model.WarehouseBrandItemUnbilledActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemSaleModel;
import com.spice.profitmandi.dao.model.WarehouseWiseActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandSaleModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandUnbilledActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
import com.spice.profitmandi.service.AdminUser;
import com.spice.profitmandi.service.FofoUser;
import com.spice.profitmandi.service.PartnerInvestmentService;
import com.spice.profitmandi.service.PartnerStatsService;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.offers.OfferService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

@Controller
@Transactional(rollbackOn = Throwable.class)
public class DashboardController {

        List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
                        "niranjan.kala@smartdukaan.com", "hemant.kaura@smartdukaan.com", "amit.gupta@shop2020.in",
                        "tejbeer.kaur@shop2020.in");

        @Value("${web.api.host}")
        private String webApiHost;

        @Value("${web.api.scheme}")
        private String webApiScheme;

        @Value("${web.api.root}")
        private String webApiRoot;

        @Value("${web.api.port}")
        private int webApiPort;

        @Autowired
        private PriceDropRepository priceDropRepository;

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private PendingOrderRepository pendingOrderRepository;

        @Autowired
        private PartnerStatsService partnerStatsService;

        @Autowired
        private CsService csService;

        @Autowired
        private ResponseSender<?> responseSender;

        @Autowired
        RetailerService retailerService;

        @Autowired
        private AdminUser adminUser;

        @Autowired
        private RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

        @Autowired
        DocumentRepository documentRepository;

        @Autowired
        InventoryItemRepository inventoryItemRepository;

        @Autowired
        InventoryService inventoryService;

        @Autowired
        private PendingOrderItemRepository pendingOrderItemRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        private PartnerTypeChangeService partnerTypeChangeService;

        @Autowired
        private HygieneDataRepository hygieneDataRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private NotificationCampaignRepository notificationCampaignRepository;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private Gson gson;

        @Autowired
        TicketRepository ticketRepository;

        @Autowired
        private OfferService offerService;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private SaholicInventoryCISRepository saholicInventoryCISRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private ReporticoCacheTableRepository reporticoCacheTableRepository;

        @Autowired
        private TransactionService transactionService;

        @Autowired
        private TagListingRepository tagListingRepository;

        @Autowired
        private TicketAssignedRepository ticketAssignedRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private FofoUser fofoUser;

        @Autowired
        private ActivatedImeiRepository activatedImeiRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private PositionRepository positionRepository;
        private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);

        @RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
        public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
                boolean isAdmin = false;
                model.addAttribute("isAdmin", isAdmin);

                model.addAttribute("webApiHost", webApiHost);
                model.addAttribute("webApiPort", webApiPort);
                model.addAttribute("webApiScheme", webApiScheme);
                model.addAttribute("webApiRoot", webApiRoot);
                if (isAdmin) {
                        return "dashboard1";
                }

                FofoStore fofoStore = null;
                try {
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                        fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
                        if (!fofoStore.isActive()) {
                                return "redirect:/login";
                        }

                        PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
                        model.addAttribute("partnerType", partnerType);
                        model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
                        model.addAttribute("fofoStore", customRetailer);
                        model.addAttribute("partnerType", partnerType);
                        model.addAttribute("hasGift", fofoUser.hasGift(fofoId));
                        model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);

                        model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId));
                        model.addAttribute("salesMap", fofoUser.getSales(fofoId));
                        model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
                        // this.setInvestments
                        //
                        Map<Integer, String> monthValueMap = new HashMap<>();
                        for (int i = 0; i <= 5; i++) {
                                LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
                                monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
                        }
                        LOGGER.info("monthValueMap" + monthValueMap);
                        model.addAttribute("monthValueMap", monthValueMap);
                        model.addAttribute("investments", fofoUser.getInvestments(fofoId));
                        model.addAttribute("isInvestmentOk",
                                        partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);

                }

                return "12dashboard34";
        }

        @RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
        public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                int dayOfMonth = curDate.getDayOfMonth();
                for (int i = 1; i <= 6; i++) {
                        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
                        int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
                        double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
                                        startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);

                        double mtdSales = fofoOrderItemRepository
                                        .selectSumMopGroupByRetailer(startOfMonth,
                                                        startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
                                        .get(fofoId);

                        PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());

                        MonthSaleModel ms = new MonthSaleModel();
                        ms.setMtdSales(fofoUser.format((long) mtdSales));
                        ms.setMonthlySales(fofoUser.format(((long) monthSales)));
                        ms.setPartnerType(partnerType);
                        ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
                        monthSaleMap.put(i, ms);

                }

                model.addAttribute("monthSales", monthSaleMap);
                return "monthSales";
        }

        @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
        public String dashboard(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                int fofoId = loginDetails.getFofoId();

                LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
                LocalDateTime endtDate = LocalDateTime.now();
                OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository
                                .selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);

                LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());

                long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
                LOGGER.info("countOrder" + countOrder);

                model.addAttribute("countOrder", countOrder);
                model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
                boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
                model.addAttribute("isAdmin", isAdmin);

                model.addAttribute("webApiHost", webApiHost);
                model.addAttribute("webApiPort", webApiPort);
                model.addAttribute("webApiScheme", webApiScheme);
                model.addAttribute("webApiRoot", webApiRoot);
                if (isAdmin) {
                        return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
                } else {
                        FofoStore fofoStore = null;
                        try {
                                fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
                                if (!fofoStore.isActive()) {
                                        return "redirect:/login";
                                }

                                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
                                model.addAttribute("partnerType", partnerType);
                                model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
                                model.addAttribute("fofoStore", fofoStore);
                                model.addAttribute("partnerType", partnerType);
                                model.addAttribute("maa", loginDetails.getFofoId() == 175138885);

                                model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
                                model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
                                model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
                                                .append("partnerId", fofoStore.getId()).toString());
                                model.addAttribute("activatedImeis",
                                                inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
                                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
                                                .selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
                                                                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));

                                Double accesoriesStock = currentInventorySnapshotRepository
                                                .selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
                                                                Optional.of(false))
                                                .get(loginDetails.getFofoId());

                                model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
                                model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(loginDetails.getFofoId()));
                                model.addAttribute("salesMap", fofoUser.getSales(loginDetails.getFofoId()));
                                ChartModel cm = fofoUser.getBrandChart(loginDetails.getFofoId());

                                LOGGER.info("chartMap" + gson.toJson(cm));
                                model.addAttribute("chartMap", gson.toJson(cm));

                                List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
                                                YearMonth.from(LocalDateTime.now()));
                                model.addAttribute("publishedOffers", publishedOffers);
                                model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
                                model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
                                                10, ProfitMandiConstants.CUTOFF_INVESTMENT));

                        } catch (ProfitMandiBusinessException e) {
                                LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());

                        }
                }

                LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
                LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
                LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
                double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
                                currentMonthEnd) / 2;
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
                                currentMonthStart) / 2;
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
                                currentMonthEnd) / 2;
                model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
                model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
                model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);

                long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
                                currentMonthEnd);

                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
                                currentMonthStart, currentMonthEnd);
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
                        invalidHygieneCount = 1;
                }
                Map<Integer, String> monthValueMap = new HashMap<>();
                for (int i = 0; i <= 5; i++) {
                        LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
                        monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
                }

                model.addAttribute("monthValueMap", monthValueMap);
                model.addAttribute("month", 0);

                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));

                model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
                model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
                /*
                 * if (loginDetails.isReadOnly()) { return "dashboard-readonly"; } else { }
                 */

                return "dashboard1";

        }

        @RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
        public String getMonthsInvestment(HttpServletRequest request,
                        @RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model)
                        throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                Map<String, Object> investment = fofoUser.getInvestmentsMonths(fofoId, month);

                LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
                LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
                LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
                double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
                                currentMonthEnd) / 2;
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
                                currentMonthStart) / 2;
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
                                currentMonthEnd) / 2;
                model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
                model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
                model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);

                long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
                                currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));

                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
                                currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
                        invalidHygieneCount = 1;
                }
                Map<Integer, String> monthValueMap = new HashMap<>();
                for (int i = 0; i <= 5; i++) {
                        LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
                        monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
                }
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
                model.addAttribute("monthValueMap", monthValueMap);
                model.addAttribute("investments", investment);
                model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
                model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
                model.addAttribute("month", month);
                return "performance";
        }

        @RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
        public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ChartInvestmentModel cm = fofoUser.getInvestmentChart(fofoId);
                model.addAttribute("chartPieMap", gson.toJson(cm));

                LOGGER.info("InvestmentChart" + gson.toJson(cm));
                LOGGER.info("InvestmentChart" + cm);
                return "investmentdetails";
        }

        @RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
        public String getlmsLineChart(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ChartModel cm = fofoUser.getLmsLineChart(loginDetails.getFofoId());

                LOGGER.info("linechartMap" + gson.toJson(cm));
                model.addAttribute("linechartMap", gson.toJson(cm));
                return "lmsLineChart";
        }

        @RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
        public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ChartModel cm = fofoUser.getPurchaseOrderChart(fofoId);

                LOGGER.info("chartMap" + gson.toJson(cm));
                model.addAttribute("chartMap", gson.toJson(cm));

                return "purchase_chart";
        }

        @RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
        public String getBarChart(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ChartModel cm = fofoUser.getBrandChart(fofoId);

                LOGGER.info("chartMap" + gson.toJson(cm));
                model.addAttribute("chartMap", gson.toJson(cm));

                return "bar_chart";
        }

        @RequestMapping(value = "/getPriceDropDetails", method = RequestMethod.GET)
        public String getPriceDropDetails(HttpServletRequest request,
                        @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
                        @RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
                        @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
                        throws Exception {

                LOGGER.info("params" + fofoId + brand + yearMonth);

                List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
                                .selectBrandPendingPriceDropWithDetailsByYearMonth(fofoId, brand, yearMonth);

                LOGGER.info("priceDropdetailsList" + priceDropdetailsList);

                model.addAttribute("priceDropdetailsList", priceDropdetailsList);

                return "price-drop-details";
        }

        @RequestMapping(value = "/getPriceDropDetailSixMonths", method = RequestMethod.GET)
        public String getPriceDropDetailSixMonths(HttpServletRequest request,
                        @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
                        @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
                        throws Exception {

                LOGGER.info("params" + fofoId + brand);
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                LocalDateTime startfMonthSixMonth = curDate.withDayOfMonth(1).minusMonths(12);
                LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);

                List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
                                .selectBrandPendingPriceDropWithDetailsAndSixMonth(fofoId, brand, startfMonthSixMonth, endMonthTotal);

                LOGGER.info("priceDropdetailsList" + priceDropdetailsList);

                model.addAttribute("priceDropdetailsList", priceDropdetailsList);

                return "price-drop-details";
        }

        @RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
        public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                LocalDateTime curDate = LocalDate.now().atStartOfDay();

                LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
                LocalDateTime startfMonthTotal = curDate.withDayOfMonth(1).minusMonths(12);
                LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);

                List<YearMonth> yms = new ArrayList<YearMonth>();

                for (int i = 1; i <= 6; i++) {
                        yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
                }
                Collections.reverse(yms);
                model.addAttribute("yms", yms);
                LOGGER.info("ym" + yms);

                List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository
                                .selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);

                List<PriceDropBrandModel> priceDropBrandSixMonthTotals = priceDropRepository
                                .selectSixMonthBrandPriceDropByYearMonth(fofoId, startfMonthTotal, endMonthTotal);

                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");

                Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();

                LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);

                Map<String, Double> priceDropBrandSixMonthMap = priceDropBrandSixMonthTotals.stream()
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));

                model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);

                LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);

                for (PriceDropYearMonthModel pdm : priceDropYearMonthModels) {
                        Map<YearMonth, Double> brandValue = new HashMap<>();

                        if (brandMonthValue.containsKey(pdm.getBrand())) {
                                brandValue = brandMonthValue.get(pdm.getBrand());
                                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
                        } else {

                                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());

                        }
                        brandMonthValue.put(pdm.getBrand(), brandValue);
                }
                List<String> brands = new ArrayList<>();
                brands.add("Accessories");
                brands.add("Oppo");
                brands.add("Vivo");
                brands.add("Samsung");
                brands.add("Realme");
                brands.add("MI");
                brands.add("Tecno");
                brands.add("Itel");
                brands.add("Nokia");
                Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();

                model.addAttribute("brands", brands);

                for (String brand : brands) {
                        Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
                        for (int i = 6; i >= 1; i--) {

                                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);

                                if (yearMonthValue != null) {
                                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
                                                yearMonthValue.put(YearMonth.from(startMonth), 0.0);
                                        }

                                } else {
                                        yearMonthValue = new HashMap<>();
                                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
                                }
                        }

                        Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);

                        brandMonthValue.put(brand, sortedMonthBrandValue);

                        sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));

                }

                Map<String, List<Double>> brandValues = new LinkedHashMap<>();

                for (Entry<String, List<Double>> vv : sortedBrandValue.entrySet()) {

                        Double total = vv.getValue().stream().mapToDouble(x -> x.doubleValue()).sum();

                        if (total != 0.0) {
                                brandValues.put(vv.getKey(), vv.getValue());

                        }

                        LOGGER.info("total" + total);
                }

                LOGGER.info("sortedBrandValue" + brandValues);
                model.addAttribute("fofoId", fofoId);

                model.addAttribute("sortedBrandValue", brandValues);

                return "price-drop-tabular";
        }

        @RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
        public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
                        throws Exception {

                Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
                Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);

                Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
                if (authId != 0) {
                        List<Integer> fofoIds = pp.get(authId);
                        fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
                } else {
                }

                model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
                model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);

                return "auth_user_partner_detail";
        }

        @RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
        public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
                        throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();

                Set<Integer> authfofoIds = new HashSet<>();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                authfofoIds = storeGuyMap.get(email);

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                if (authfofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
                                                .flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
                                .selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
                                                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));

                Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
                Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
                if (warehouseId != 0) {
                        List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
                        /*
                         * List<Integer> fofoIds =
                         * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
                         * .map(x -> x.getId()).collect(Collectors.toList());
                         */
                        fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
                } else {

                        List<Integer> fofoIds = new ArrayList<>(authfofoIds);
                        fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
                }
                ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
                model.addAttribute("chartPieMap", gson.toJson(cm));

                LOGGER.info("adminUserChart" + gson.toJson(cm));
                      

                model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
                model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);

                return "auth_user_partner_detail";
        }

        @RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
        public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(email);
                AuthUser authUser = authRepository.selectByEmailOrMobile(email);

                if (authfofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
                                                .flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }

                Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
                                .selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
                                                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
                List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
                if (!warehouseId.contains(0)) {
                        warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
                } else {
                        LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
                        warehouseWiseBrandStock = saholicInventoryCISRepository
                                        .selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));

                }
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
                model.addAttribute("warehouseId", warehouseId);
                model.addAttribute("warehouseMap", warehouseMap);

                return "warehouse_brand_stock";
        }

        @RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
        public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
                inventoryService.getItemAvailabilityAndIndent();
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";
        }

        @RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
        public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
                Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
                ObjectOutputStream oos = null;
                FileOutputStream fout = null;
                try {
                        fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
                        oos = new ObjectOutputStream(fout);
                        oos.writeObject(partnerStats);

                } catch (Exception ex) {
                        ex.printStackTrace();
                } finally {
                        if (oos != null) {
                                oos.close();
                        }
                }
                ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
                if (rct == null) {
                        rct = new ReporticoCacheTable();
                        rct.setTableName("partnerStat");

                }
                rct.setLastCreatedTimestamp(LocalDateTime.now());
                reporticoCacheTableRepository.persist(rct);
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";
        }

        @RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
        public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
                        throws Exception {

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
                List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();

                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("brands", listbrands);
                model.addAttribute("listCategory", listCategory);

                model.addAttribute("selectedBrand", brands);
                model.addAttribute("selectedWarehouse", warehouseId);
                model.addAttribute("selectedCategory", category);

                return "warehouse_brand_item_stock";
        }

        @RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
        public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
                        throws Exception {
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                if (warehouseId.contains(0)) {
                        warehouseId.addAll(warehouseMap.keySet());
                }
                List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
                                .selectWarehouseItemStock(warehouseId, brands, category);

                model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
                model.addAttribute("warehouseMap", warehouseMap);
                return "warehouse_item_details";
        }

        @RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
        public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
                        throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(email);

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                if (authfofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
                                                .flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }

                Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
                                .selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
                                .collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));

                List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
                                .selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));

                for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
                        WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
                        if (bpt != null) {
                                bpt.setAmtd(un.getUnbilledMtd());
                                bpt.setUamtdQty(un.getUnbilledQty());
                        } else {
                                bpt = new WarehouseWiseBrandSaleModel();
                                bpt.setWarehouseId(un.getWarehouseId());
                                bpt.setAmtd(un.getUnbilledMtd());
                                bpt.setUamtdQty(un.getUnbilledQty());
                                bpt.setLms(0);
                                bpt.setLmtd(0);
                                bpt.setMtd(0);
                                bpt.setMtdQty(0);
                                bpt.setLmtd(0);
                                bpt.setLmtdQty(0);
                                warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
                        }
                }
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

                Set<String> brands = inventoryService.getAllTagListingBrands();
                model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("brands", brands);
                model.addAttribute("selectedbrand", brand);
                return "warehousewise_brand_partners_sale";
        }

        @RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
        public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
                        @RequestParam String brand) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(email);

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                if (authfofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
                                                .flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }
                List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
                                .selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

                Set<String> brands = inventoryService.getAllTagListingBrands();
                model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("brands", brands);
                model.addAttribute("selectedbrand", brand);
                return "warehousewise_accessoriesbrand_sale";
        }

        @RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
        public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(email);
                Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
                                .selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));

                List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
                                .selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));

                for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
                        WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
                        if (bpt != null) {
                                bpt.setAmtd(un.getAmtd());
                                bpt.setUamtdQty(un.getUnmtdQty());
                        } else {
                                bpt = new WarehouseBrandWiseItemSaleModel();
                                bpt.setWarehouseId(un.getWarehouseId());
                                bpt.setItemId(un.getItemId());
                                bpt.setAmtd(un.getAmtd());
                                bpt.setUamtdQty(un.getUnmtdQty());
                                bpt.setBrand(un.getBrand());
                                bpt.setModelName(un.getModelName());
                                bpt.setModelNumber(un.getModelNumber());
                                bpt.setColor(un.getColor());
                                bpt.setLms(0);
                                bpt.setLmtd(0);
                                bpt.setMtd(0);
                                bpt.setMtdQty(0);
                                bpt.setLmtd(0);
                                bpt.setLmtdQty(0);
                                branditemSalesMap.put(un.getItemId(), bpt);
                        }
                }
                model.addAttribute("branditemSales", branditemSalesMap);
                model.addAttribute("warehouseMap", warehouseMap);
                return "warehouse_partner_itemwise_sale";
        }

        @RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
        public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(email);
                List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
                                .selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
                model.addAttribute("branditemSales", branditemSales);
                model.addAttribute("warehouseMap", warehouseMap);
                return "warehouse_accessories_itemwsie_sale";
        }

        @RequestMapping(value = "/contactUs", method = RequestMethod.GET)
        public String contactUs(HttpServletRequest request, Model model) throws Throwable {
                model.addAttribute("appContextPath", request.getContextPath());
                return "contact-us";
        }

        @RequestMapping(value = "/notifications", method = RequestMethod.GET)
        public String getNotificationsWithType(HttpServletRequest request,
                        @RequestParam(required = false) MessageType messageType,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int userId = 0;
                boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
                if (isAdmin) {
                        userId = loginDetails.getFofoId();
                } else {
                        userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
                }
                List<Notification> notifications = null;

                List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
                                userId, offset, limit);
                LOGGER.info("messageType" + messageType);
                notifications = fofoUser.getNotifications(notificationCampaigns, messageType);

                model.addAttribute("notifications", notifications);

                LOGGER.info("notifications" + notifications);
                return "notification-template";
        }

        @RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
        public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
                        throws ProfitMandiBusinessException {
                Document document = documentRepository.selectById(documentId);
                NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
                if (nc.getDocumentId() == null) {
                        throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
                }
                if (nc.getDocumentId() != documentId) {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
                }
                return responseSender.ok(document);
        }

        @RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
        public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
                        throws ProfitMandiBusinessException {

                NotificationCampaign nc = notificationCampaignRepository.selectById(cid);

                if (nc.getDocumentId() == null) {
                        throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
                }

                Document document = documentRepository.selectById(nc.getDocumentId());

                FileInputStream file = null;
                try {
                        file = new FileInputStream(document.getPath() + File.separator + document.getName());
                } catch (FileNotFoundException e) {
                        LOGGER.error("Retailer Document file not found : ", e);
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
                }
                // ByteArrayOutputStream byteArrayOutputStream = new
                // ByteArrayOutputStream();
                // ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);

                final HttpHeaders headers = new HttpHeaders();
                String contentType = "";
                if (document.getContentType() == ContentType.JPEG) {
                        contentType = "image/jpeg";
                } else if (document.getContentType() == ContentType.PNG) {
                        contentType = "image/png";
                } else if (document.getContentType() == ContentType.PDF) {
                        contentType = "application/pdf";
                }
                headers.set("Content-Type", contentType);
                headers.set("Content-disposition", "inline; filename=" + document.getName());
                headers.setContentLength(document.getSize());
                final InputStreamResource inputStreamResource = new InputStreamResource(file);
                return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }

        @RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
        public String getItemWiseTertiary(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
                        throws ProfitMandiBusinessException {
                List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);

                LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                model.addAttribute("customRetailer", customRetailer);
                model.addAttribute("itemWiseTertiary", itemWiseTertiary);
                return "item-wise-tertiary";
        }

        @RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
        public String getItemWiseIndent(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
                        throws ProfitMandiBusinessException {

                List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
                model.addAttribute("unbilledOrders", unbilledOrders);

                return "item-wise-indent";
        }

        @RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
        public String getPartnerInvestment(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
                PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                model.addAttribute("partnerDetailModel", partnerDetailModel);
                model.addAttribute("customRetailer", customRetailer);
                return "partner-investment";
        }

        @RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
        public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
                        @RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
                List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
                                .selectPartnerPendingIndentItem(itemId, warehouseId);

                model.addAttribute("partnerPendingIndent", partnerPendingIndent);
                return "partner-pending-indent-item";
        }

        @RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
        public String getPartnerActivateStockItem(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                List<ActivateItemModel> activateStocks = new ArrayList<>();
                List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);

                for (InventoryItem inventoryItem : inventoryItems) {
                        TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
                        Item item = itemRepository.selectById(inventoryItem.getItemId());
                        ActivateItemModel aim = new ActivateItemModel();
                        aim.setFofoId(inventoryItem.getFofoId());
                        aim.setQuantity(inventoryItem.getGoodQuantity());
                        aim.setAmount(tagListing.getSellingPrice());
                        aim.setItemDescription(item.getItemDescription());
                        aim.setItemId(inventoryItem.getItemId());
                        activateStocks.add(aim);
                }

                model.addAttribute("activateStocks", activateStocks);
                model.addAttribute("customRetailer", customRetailer);
                return "partner-activate-stock";
        }

        @RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
        public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                Map<String, Double> brandMtdAmount = fofoOrderItemRepository
                                .selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
                Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
                                curDate.with(LocalTime.MAX), fofoId);
                Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
                                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
                Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
                                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);

                LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
                model.addAttribute("brandMtdAmount", brandMtdAmount);
                model.addAttribute("brandMtdQty", brandMtdQty);
                model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
                model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);

                model.addAttribute("customRetailer", customRetailer);
                return "partner-brand-mtd-sale";
        }

        @RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
        public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
                Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);

                Double accesorieslmtdsale = fofoOrderRepository
                                .selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
                                                curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
                                .get(fofoId);
                Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
                                Optional.of(false)).get(fofoId);

                model.addAttribute("brandLMtdAmount", brandLMtdAmount);
                model.addAttribute("brandLmtdQty", brandLmtdQty);
                model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
                model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
                model.addAttribute("customRetailer", customRetailer);
                return "partner-brand-lmtd-sale";
        }

        @RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
        public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();

                Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
                Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);

                Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
                Long accesorieslmsqty = fofoOrderRepository
                                .selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
                                                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
                                .get(fofoId);

                model.addAttribute("brandLMSAmount", brandLMSAmount);
                model.addAttribute("brandLmsQty", brandLmsQty);
                model.addAttribute("accesorieslmssale", accesorieslmssale);
                model.addAttribute("accesorieslmsqty", accesorieslmsqty);
                model.addAttribute("customRetailer", customRetailer);
                return "partner-brand-lms-sale";
        }

        @RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
        public String getPatnerInStock(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {

                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);

                List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
                                .selectSumInStockMobileGroupByBrand(fofoId);
                List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
                                .selectSumInStockAccessoriesGroupByBrand(fofoId);

                List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
                                .selectInStockItemsByBrand(fofoId);

                Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
                                .collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));

                model.addAttribute("stockItemMap", stockItemMap);
                model.addAttribute("mobileStock", mobileStocks);
                model.addAttribute("accesStock", accesStock);
                model.addAttribute("customRetailer", customRetailer);
                return "partner-instock-item";
        }

        @RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
        public String getOpenTicketByFofoId(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
                Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
                                .collect(Collectors.toList());
                List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);

                for (TicketAssigned ticketAssign : ticketAssigns) {
                        AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
                        ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
                }
                model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
                model.addAttribute("ticketAssigns", ticketAssigns);
                model.addAttribute("customRetailer", customRetailer);
                return "open-ticket";
        }

        @RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
        public String getPartnerSecondarySale(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
                        throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
                LocalDateTime startDate = null;
                LocalDateTime endDate = null;
                List<InStockBrandModel> secondarySale = null;
                Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;

                if (timeValue.equals("mtd")) {
                        startDate = curDate.withDayOfMonth(1);
                        endDate = curDate.with(LocalTime.MAX);
                        secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
                        secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
                                        .stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
                        LOGGER.info("secondarySalemtd" + secondarySale);
                } else if (timeValue.equals("lmtd")) {
                        startDate = curDate.withDayOfMonth(1).minusMonths(1);
                        endDate = curDate.with(LocalTime.MAX).minusMonths(1);
                        secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
                                        .stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));

                        secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
                        LOGGER.info("secondarySalelmtd" + secondarySale);

                } else {
                        startDate = curDate.withDayOfMonth(1).minusMonths(1);
                        endDate = curDate.withDayOfMonth(1);
                        secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
                                        .stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));

                        secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
                        LOGGER.info("secondarySalelms" + secondarySale);

                }

                LOGGER.info("secondarySale" + secondarySale);
                model.addAttribute("secondarySale", secondarySale);
                model.addAttribute("secondaryItemSale", secondaryItemSale);
                model.addAttribute("customRetailer", customRetailer);

                return "partner-secondary-order";
        }

        @RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
        public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();

                Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
                if (emails.contains(authUser.getEmailId())) {
                        fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
                        LOGGER.info("fofoIds" + fofoIds);
                }

                if (fofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
                                                .map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }

                Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
                partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds))
                                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));

                List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
                                .selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
                for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
                        BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
                        if (bpt != null) {
                                bpt.setAmtd(un.getUnbilledMtd());
                                bpt.setUamtdQty(un.getUnbilledMTDQty());
                        } else {
                                bpt = new BrandWisePartnerSaleModel();
                                bpt.setBrand(un.getBrand());
                                bpt.setAmtd(un.getUnbilledMtd());
                                bpt.setUamtdQty(un.getUnbilledMTDQty());
                                bpt.setLms(0);
                                bpt.setLmtd(0);
                                bpt.setMtd(0);
                                bpt.setMtdQty(0);
                                bpt.setLmtd(0);
                                bpt.setLmtdQty(0);
                                partnersBrandSaleMap.put(un.getBrand(), bpt);
                        }
                }

                model.addAttribute("brandSalesMap", partnersBrandSaleMap);

                return "mobile-brand-wise-report";
        }

        @RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
        public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();

                Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
                if (emails.contains(authUser.getEmailId())) {
                        fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
                        LOGGER.info("fofoIds" + fofoIds);
                }

                if (fofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
                                                .map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }

                List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;

                accessoriesBrandSales = fofoStoreRepository
                                .selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));

                model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
                return "accessories-brand-wise-report";
        }

        @RequestMapping(value = "/getMobileLMSGraph", method = RequestMethod.GET)
        public String getMobileLMSGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
                        @RequestParam(required = false) LocalDate date, @RequestParam List<Integer> fofoIds, Model model)
                        throws Exception {
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
                                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
                                                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));

                ChartModel cm;
                if (warehouseId != 0) {
                        cm = adminUser.getBrandWiseLms(Arrays.asList(warehouseId),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);
                } else {
                        cm = adminUser.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);

                }

                LOGGER.info("chartMap" + gson.toJson(cm));
                model.addAttribute("chartMap", gson.toJson(cm));
                return "brand-wise-mobile-lms-chart";
        }

        @RequestMapping(value = "/getMobileLMSFilter", method = RequestMethod.GET)
        public String getMobileLMSFilter(HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "0") int warehouseId,
                        @RequestParam(required = false) LocalDate date, Model model) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Object> map = adminUser.getFilter(warehouseId, email, date);
                model.addAttribute("warehouseId", warehouseId);
                model.addAllAttributes(map);

                return "chart-filter-lms";
        }

        @RequestMapping(value = "/getMobileLMPFilter", method = RequestMethod.GET)
        public String getMobileLMPFilter(HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "0") int warehouseId,
                        @RequestParam(required = false) LocalDate date, Model model) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Map<String, Object> map = adminUser.getFilter(warehouseId, email, date);
                model.addAttribute("warehouseId", warehouseId);
                model.addAllAttributes(map);

                return "chart-filter-lmp";
        }

        @RequestMapping(value = "/getMobileLMPGraph", method = RequestMethod.GET)
        public String getMobileLMPGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
                        @RequestParam(required = false) LocalDate date, @RequestParam List<Integer> fofoIds, Model model)
                        throws Exception {
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
                                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
                                                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));

                ChartModel cm;
                if (warehouseId != 0) {
                        cm = adminUser.getBrandWiseLmp(Arrays.asList(warehouseId),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);
                } else {
                        cm = adminUser.getBrandWiseLmp(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);

                }

                LOGGER.info("chartMap" + gson.toJson(cm));
                model.addAttribute("chartMap", gson.toJson(cm));
                return "brand-wise-mobile-lmp-chart";
        }

        @RequestMapping(value = "/getActivatedModelWarehouseWise", method = RequestMethod.GET)
        public String getActivatedModelWarehouseWise(HttpServletRequest request, Model model, @RequestParam String brand)
                        throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                List<Integer> fofoIds = getFofoIds(loginDetails);
                List<WarehouseWiseActivatedModel> warehouseWiseActivatedModels = activatedImeiRepository
                                .selectActivatedModelGroupByWarehouse(brand, fofoIds);
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

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

                List<String> brands = mobileBrands.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
                LOGGER.info("brands" + brands.add("Redmi"));

                model.addAttribute("warehouseWiseActivatedModels", warehouseWiseActivatedModels);
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("brands", brands);
                model.addAttribute("selectedbrand", brand);
                return "warehousewise_activated_model";
        }

        @RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
        public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                List<Integer> fofoIds = getFofoIds(loginDetails);
                List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository
                                .selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
                model.addAttribute("activatedModels", activatedModels);
                return "activation-brandwise-report";
        }

        @RequestMapping(value = "/getWarehouseBrandWiseItemActivatedModel", method = RequestMethod.GET)
        public String getWarehouseBrandWiseItemActivatedModel(HttpServletRequest request, Model model,
                        @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                List<Integer> fofoIds = getFofoIds(loginDetails);

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                List<WarehouseBrandWiseItemActivatedModel> activatedItems = activatedImeiRepository
                                .selectWarehouseBrandActivatedItem(warehouseId, brand, fofoIds);
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("activatedItems", activatedItems);
                return "warehouse-activated-itemwise-model";

        }

        @RequestMapping(value = "/getActivatedImeiUpdationDate", method = RequestMethod.GET)
        public String getActivatedImeiUpdationDate(HttpServletRequest request, Model model) throws Exception {

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

                List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository
                                .selectActivatedUpdationDate();
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("activationImeiUpdations", activationImeiUpdations);
                return "activation-updation-timestamp";

        }

        private List<Integer> getFofoIds(LoginDetails loginDetails) throws ProfitMandiBusinessException {
                String email = loginDetails.getEmailId();

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();

                Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
                if (emails.contains(authUser.getEmailId())) {
                        fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
                        LOGGER.info("fofoIds" + fofoIds);
                }

                if (fofoIds == null) {
                        List<Position> positions1 = positionRepository.selectAll(authUser.getId());
                        if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
                                        .count() > 0) {
                                fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
                                                .map(x -> x.getPartnerId()).collect(Collectors.toSet());
                        }
                }
                return new ArrayList<>(fofoIds);
        }

}