Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

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.*;
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.*;
import com.spice.profitmandi.dao.entity.transaction.LineItem;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
import com.spice.profitmandi.dao.enumuration.fofo.Milestone;
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
import com.spice.profitmandi.dao.model.SamsungUpgradeOfferModel;
import com.spice.profitmandi.dao.model.*;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
import com.spice.profitmandi.dao.repository.catalog.SamsungUpgradeOfferRepository;
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.*;
import com.spice.profitmandi.dao.repository.fofo.*;
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
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;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import static in.shop2020.model.v1.order.OrderStatus.*;


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

        List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
                        "amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com", "kanan.choudhary@smartdukaan.com");

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

        @Autowired
        private LineItemRepository lineItemRepository;

        @Autowired
        private FofoLineItemRepository fofoLineItemRepository;

        @Autowired
        private PositionRepository positionRepository;

        @Autowired
        private MonthlyTargetRepository monthlyTargetRepository;

        @Autowired
        private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
        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();
                        LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth,
                                        startOfMonth.plusMonths(1));
                        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();
                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";
                                }

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

                                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();

                                orderStatus.add(SUBMITTED_FOR_PROCESSING);
                                orderStatus.add(BILLED);
                                orderStatus.add(SHIPPED_FROM_WH);
                                orderStatus.add(DELIVERY_SUCCESS);

                                List<Order> openOrders = orderRepository.selectGrnTimestampNull(fofoId, orderStatus);
                                List<LineItem> submittedLineItemIds = openOrders.stream()
                                                .filter(x -> x.getStatus().equals(SUBMITTED_FOR_PROCESSING)).map(x -> x.getLineItem())
                                                .collect(Collectors.toList());
                                List<LineItem> billedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(BILLED))
                                                .map(x -> x.getLineItem()).collect(Collectors.toList());
                                List<LineItem> shippedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH))
                                                .map(x -> x.getLineItem()).collect(Collectors.toList());
                                List<LineItem> grnPendingLineItemIds = openOrders.stream()
                                                .filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getLineItem())
                                                .collect(Collectors.toList());

                                long imeiActivationPendingCount = 0;
                                long imeiActivationPendingValue = 0;
                                List<Integer> grnPendingOrderIds = openOrders.stream()
                                                .filter(x -> x.getStatus().equals(SHIPPED_FROM_WH) || x.getStatus().equals(DELIVERY_SUCCESS))
                                                .map(x -> x.getId()).collect(Collectors.toList());
                                if (grnPendingOrderIds.size() > 0) {
                                        List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository
                                                        .selectActivatedImeisByOrders(grnPendingOrderIds);
                                        imeiActivationPendingCount = imeiActivationTimestampModels.size();
                                        imeiActivationPendingValue = imeiActivationTimestampModels.stream()
                                                        .collect(Collectors.summingDouble(x -> x.getSellingPrice())).longValue();
                                }

                                long grnPendingCount = grnPendingLineItemIds.stream()
                                                .collect(Collectors.summingLong(LineItem::getQuantity));
                                long grnPendingValue = grnPendingLineItemIds.stream()
                                                .collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
                                model.addAttribute("grnPendingCount", grnPendingCount);
                                model.addAttribute("grnPendingValue", grnPendingValue);

                                long submittedCount = submittedLineItemIds.stream()
                                                .collect(Collectors.summingLong(LineItem::getQuantity));
                                long submittedValue = submittedLineItemIds.stream()
                                                .collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
                                model.addAttribute("submittedCount", submittedCount);
                                model.addAttribute("submittedValue", submittedValue);

                                long billedCount = billedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
                                long billedValue = billedOrderIds.stream()
                                                .collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
                                model.addAttribute("billedValue", billedValue);
                                model.addAttribute("billedCount", billedCount);
                                LOGGER.info("billedCount {}", billedCount);

                                long shippedCount = shippedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
                                model.addAttribute("shippedCount", shippedCount);
                                LOGGER.info("shippedCount {}", shippedCount);
                                long shippedValue = shippedOrderIds.stream()
                                                .collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
                                model.addAttribute("shippedValue", shippedValue);

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

                                LocalDateTime currentMonthStart = curDate.withDayOfMonth(1);
                                LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
                                LocalDateTime currentMonthEnd = currentMonthStart.withDayOfMonth(1);

                                LOGGER.info("lastMonthStart" + lastMonthStart);
                                LOGGER.info("currentMonthEnd" + currentMonthEnd);

                                model.addAttribute("countOrder", countOrder);
                                model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());

                                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("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()));
                                model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
                                model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);

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

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

                                MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
                                model.addAttribute("monthlyTarget", monthlyTarget);

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

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

                        }
                        return "dashboard1";
                }

        }

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                List<Order> grnPendingOrders = orderRepository.selectGrnTimestampNull(fofoId,
                                Arrays.asList(in.shop2020.model.v1.order.OrderStatus.DELIVERY_SUCCESS));

                model.addAttribute("grnPendingOrders", grnPendingOrders);
                return "purchase-grn-order-status";
        }

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();

                orderStatus.add(in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING);

                List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
                List<Integer> submittedOrderIds = order.stream()
                                .filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING)
                                .map(x -> x.getId()).collect(Collectors.toList());
                model.addAttribute("submittedOrderIds", submittedOrderIds);
                if (!submittedOrderIds.isEmpty()) {

                        List<LineItem> submittedLineItem = lineItemRepository.selectLineItem(submittedOrderIds);
                        Map<Integer, LineItem> submittedLineItemMap = submittedLineItem.stream()
                                        .collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
                        LOGGER.info("submittedLineItemMap {}", submittedLineItemMap);
                        model.addAttribute("submittedLineItemMap", submittedLineItemMap);
                }

                return "purchase-pending-order-status";
        }

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
                orderStatus.add(in.shop2020.model.v1.order.OrderStatus.BILLED);

                List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
                List<Integer> billedOrderIds = order.stream()
                                .filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.BILLED).map(x -> x.getId())
                                .collect(Collectors.toList());
                LOGGER.info("billedOrderIds {}", billedOrderIds);
                model.addAttribute("billedOrderIds", billedOrderIds);

                if (!billedOrderIds.isEmpty()) {
                        List<LineItem> billedLineItem = lineItemRepository.selectLineItem(billedOrderIds);
                        Map<Integer, LineItem> billedLineItemMap = billedLineItem.stream()
                                        .collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
                        LOGGER.info("billedLineItemMap {}", billedLineItemMap);
                        model.addAttribute("billedLineItemMap", billedLineItemMap);
                }

                return "purchase-billed-order-status";
        }

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();

                orderStatus.add(SHIPPED_FROM_WH);

                List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
                List<Integer> shippedOrderIds = order.stream().filter(x -> x.getPartnerGrnTimestamp() == null)
                                .map(x -> x.getId()).collect(Collectors.toList());
                model.addAttribute("shippedOrderIds", shippedOrderIds);
                LOGGER.info("shippedOrderIds {}", shippedOrderIds);

                if (!shippedOrderIds.isEmpty()) {
                        List<LineItem> shippedLineItem = lineItemRepository.selectLineItem(shippedOrderIds);
                        Map<Integer, LineItem> shippedLineItemMap = shippedLineItem.stream()
                                        .collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
                        LOGGER.info("shippedLineItemMap {}", shippedLineItemMap);

                        model.addAttribute("shippedLineItemMap", shippedLineItemMap);
                }
                return "purchase-shipped-order-status";
        }


        @Autowired
        OfferRepository offerRepository;

        @Autowired
        OfferPayoutRepository offerPayoutRepository;

        @RequestMapping(value = "/partnerTotalIncomeByMonth/{yearMonth}", method = RequestMethod.GET)
        public String getPartnerTotalIncomeByMonth(HttpServletRequest request, @PathVariable int yearMonth, Model model)
                        throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                long pendingIncome = 0;
                long partnerPurchaseIn = 0;
                long partnerCreditedSale = 0;
                long partnerFrontIncome = 0;

                LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
                LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();

                AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository
                                .selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
                AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository
                                .selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
                AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository
                                .selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);

                AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository
                                .selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);

                List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
                                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);

                long additionalIncome = offerPayoutImeiIncomeModels.stream().collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
                //AllPurchaseInventoryModel partnerAdditionalIncome = offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth, endOfMonth);

                LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);

                LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
                LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
                LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);

                if (partnerlPendingSaleAmount != null) {

                        pendingIncome = partnerlPendingSaleAmount.getAmount();

                        LOGGER.info("pendingIncome" + pendingIncome);

                }

                if (partnerCreditedSaleAmount != null) {

                        partnerCreditedSale = partnerCreditedSaleAmount.getAmount();

                        LOGGER.info("partnerCreditedSale" + partnerCreditedSale);

                }
                if (partnerFrontIncomes != null) {

                        partnerFrontIncome = partnerFrontIncomes.getAmount();
                        LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);

                }
                if (partnerPurchaseInAmount != null) {

                        partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
                        LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);

                }

                LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
                LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
                LOGGER.info("pendingIncomeTT" + pendingIncome);

                long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome + additionalIncome;

                long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;

                long pendingTotalIncome = pendingIncome;
                LOGGER.info("totalIncome" + totalIncome);
                LOGGER.info("creditedIncome" + creditedIncome);
                LOGGER.info("pendingTotalIncome" + pendingTotalIncome);

                model.addAttribute("totalIncome", totalIncome);
                model.addAttribute("creditedIncome", creditedIncome);
                model.addAttribute("pendingTotalIncome", pendingTotalIncome);

                Map<Integer, String> monthValueMap = new HashMap<>();
                for (int i = 0; i <= 5; i++) {
                        LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
                        monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
                }

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

                return "partner-total-income";
        }

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

                LOGGER.info("startfMonthTotal" + startfMonthTotal);

                LOGGER.info("endMonthTotal" + endMonthTotal);
                List<YearMonth> yms = new ArrayList<YearMonth>();

                for (int i = 0; i <= 5; 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 = 5; i >= 0; 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()));

                }

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

                model.addAttribute("sortedBrandValue", sortedBrandValue);

                return "price-drop-tabular";
        }

        @RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
        public String getMonthlyActivation(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);

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

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

                List<ActivationYearMonthModel> pendingActivationModels = schemeInOutRepository
                                .selectPendingActivationGroupByBrandYearMonth(fofoId, startOfMonth);

                List<ActivationBrandModel> pendingActivationBeforeSixMonth = schemeInOutRepository
                                .selectByYearMonthActivationGroupByBrand(fofoId, startOfMonth);

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

                model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);

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

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

                for (ActivationYearMonthModel pam : pendingActivationModels) {
                        Map<YearMonth, Double> brandValue = new HashMap<>();

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

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

                        }
                        activationBrandMonthMap.put(pam.getBrand(), brandValue);
                }

                List<String> brands = new ArrayList<>();
                brands.add("Oppo");
                brands.add("Vivo");
                brands.add("Samsung");
                brands.add("Realme");
                brands.add("MI");
                brands.add("Tecno");
                brands.add("Itel");
                brands.add("Nokia");
                brands.add("Lava");
                Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();

                model.addAttribute("brands", brands);

                for (String brand : brands) {
                        Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
                        for (int i = 5; i >= 0; 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);
                        activationBrandMonthMap.put(brand, sortedMonthBrandValue);
                        sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
                }

                LOGGER.info("sortedBrandValue" + sortedBrandValue);
                model.addAttribute("sortedBrandValue", sortedBrandValue);
                model.addAttribute("fofoId", fofoId);
                return "activation-tabular";
        }

        @RequestMapping(value = "/getMonthlyActivationItemDetail", method = RequestMethod.GET)
        public String getMonthlyActivationItemDetail(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<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
                                .selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);

                for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {

                        List<FofoLineItem> flis = fofoLineItemRepository
                                        .selectByInventoryItemId(activationItemDetail.getInventoryItemId());

                        LOGGER.info("flis" + flis);

                        int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
                                        .orElseThrow(NoSuchElementException::new);
                        LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);

                        FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);

                        FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());

                        activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());

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

                model.addAttribute("activationItemDetails", activationItemDetails);

                return "activation-pending-item-details";
        }

        @RequestMapping(value = "/getMonthlyActivationBeforeSixMonthsItemDetail", method = RequestMethod.GET)
        public String getMonthlyActivationItemDetail(HttpServletRequest request,
                        @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
                        @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
                        throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();

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

                List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
                                .selectBrandPendingActivationItemDetailByYearMonth(fofoId, brand, startOfMonth);

                for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {

                        List<FofoLineItem> flis = fofoLineItemRepository
                                        .selectByInventoryItemId(activationItemDetail.getInventoryItemId());
                        LOGGER.info("flis" + flis);

                        int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
                                        .orElseThrow(NoSuchElementException::new);
                        LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);

                        FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);

                        FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());

                        activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());

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

                model.addAttribute("activationItemDetails", activationItemDetails);

                return "activation-pending-item-details";
        }

        @RequestMapping(value = "/getMonthlySamsungUpgradeOffer", method = RequestMethod.GET)
        public String getMonthlySamsungUpgradeOffer(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);

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

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

                List<SamsungUpgradeOfferModel> suos = samsungUpgradeOfferRepository.selectUpgradeOfferGroupByYearMonth(fofoId,
                                UpgradeOfferStatus.approved, startOfMonth);

                LOGGER.info("suos" + suos);

                List<BrandAmountModel> beforeSixMonthOffers = samsungUpgradeOfferRepository
                                .selectUpgradeOfferByYearMonthGroupByBrand(fofoId, UpgradeOfferStatus.approved, startOfMonth);

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

                model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);

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

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

                for (SamsungUpgradeOfferModel suo : suos) {
                        Map<YearMonth, Double> brandValue = new HashMap<>();

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

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

                        }
                        upgradeOfferBrandMonthMap.put(suo.getBrand(), brandValue);
                }

                Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
                String brand = "Samsung";

                Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
                for (int i = 5; i >= 0; 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);
                upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
                LOGGER.info("sortedBrandValue" + sortedBrandValue);

                model.addAttribute("brand", brand);
                model.addAttribute("sortedBrandValue", sortedBrandValue);
                model.addAttribute("fofoId", fofoId);
                return "upgrade-offer-tabular";

        }

        @RequestMapping(value = "/getMonthlyUpgradeOfferItemDetail", method = RequestMethod.GET)
        public String getMonthlyUpgradeOfferItemDetail(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<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
                                .selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);

                model.addAttribute("offerItems", offerItems);

                return "upgrade-offer-item-detail";
        }

        @RequestMapping(value = "/getUpgradeOfferBeforeSixMonthItemDetail", method = RequestMethod.GET)
        public String getUpgradeOfferBeforeSixMonthItemDetail(HttpServletRequest request,
                        @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
                        @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
                        throws Exception {
                LocalDateTime curDate = LocalDate.now().atStartOfDay();

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

                List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
                                .selectUpgradeOfferItemDetailByYearMonth(fofoId, UpgradeOfferStatus.approved, brand, startOfMonth);

                model.addAttribute("offerItems", offerItems);

                return "upgrade-offer-item-detail";
        }

        @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<>();
                authfofoIds = csService.getAuthFofoIds(email);
                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));

                Map<Integer, MonthlyTarget> monthlyTargetMap = monthlyTargetRepository.selectByDate(YearMonth.now()).stream()
                                .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

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

                List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values()).stream()
                                .filter(x -> !x.equals(PartnerType.ALL)).collect(Collectors.toList());

                model.addAttribute("partnerTypes", partnerTypes);

                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();
                Set<Integer> authfofoIds = csService.getAuthFofoIds(email);
                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("response1", 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();

                Set<Integer> authfofoIds = csService.getAuthFofoIds(email);

                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();
                Set<Integer> authfofoIds = csService.getAuthFofoIds(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);
                Set<Integer> fofoIds = csService.getAuthFofoIds(email);

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

                Set<Integer> fofoIds = csService.getAuthFofoIds(email);

                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) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
                        @RequestParam List<Integer> fofoIds, @RequestParam String filterType, 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.toLocalDate(),
                                        endDate.toLocalDate(), filterType);
                } else {
                        cm = adminUser.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
                                        endDate.toLocalDate(), filterType);

                }

                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) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
                        Model model) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();

                if (date == null) {
                        LocalDateTime curDate = LocalDate.now().atStartOfDay();

                        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
                        date = startOfMonth.toLocalDate().atStartOfDay();
                }

                if (endDate == null) {
                        LocalDateTime curDate = LocalDate.now().atTime(LocalTime.MAX);

                        endDate = curDate;

                }

                Map<String, Object> map = adminUser.getFilter(warehouseId, email, date, endDate);
                model.addAttribute("warehouseId", warehouseId);
                model.addAllAttributes(map);

                return "chart-filter-lms";
        }

        @RequestMapping(value = "/getMobileLMPGraph", method = RequestMethod.GET)
        public String getMobileLMPGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
                        @RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
                        @RequestParam List<Integer> fofoIds, @RequestParam String filterType, 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.toLocalDate(),
                                        endDate.toLocalDate(), filterType);
                } else {
                        cm = adminUser.getBrandWiseLmp(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                                        fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
                                        endDate.toLocalDate(), filterType);

                }

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

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Set<Integer> fofoIds = csService.getAuthFofoIds(email);
                Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
                                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);

                if (fofoIds != null && fofoIds.size() > 0) {
                        if (warehouseId != 0) {
                                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
                                                .stream().map(x -> x).collect(Collectors.toSet());
                        }
                        Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
                        if (partnerStats != null) {
                                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
                                                .map(x -> partnerStats.get(x)).collect(Collectors.toList());
                                Map<Milestone, List<Integer>> avg3Monthlms = new HashMap<>();
                                if (!last3MonthSale.isEmpty()) {
                                        int days = 60 + LocalDateTime.now().getDayOfMonth();
                                        for (Entry<Integer, Double> last3MonthEntry : last3MonthSale.entrySet()) {
                                                if (fofoIds.contains(last3MonthEntry.getKey())) {
                                                        Double monthSale = last3MonthEntry.getValue();
                                                        if (monthSale == null) {
                                                                monthSale = (double) 0;

                                                        }
                                                        double avg3MonthSale = (monthSale / days) * 30;
                                                        Milestone milestone = Milestone.get((int) avg3MonthSale);

                                                        List<Integer> values = null;

                                                        if (avg3Monthlms.containsKey(milestone)) {

                                                                values = avg3Monthlms.get(milestone);
                                                                values.add(last3MonthEntry.getKey());
                                                                avg3Monthlms.put(milestone, values);

                                                        } else {
                                                                values = new ArrayList<>();

                                                                values.add(last3MonthEntry.getKey());
                                                                avg3Monthlms.put(milestone, values);

                                                        }
                                                }

                                        }

                                }

                                if (partnerDetails != null) {

                                        Map<Milestone, List<Integer>> mtdMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getMtd()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
                                        Map<Milestone, List<Integer>> lmtdMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getLmtd()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));

                                        Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getLms()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));

                                        model.addAttribute("mtdMap", mtdMap);
                                        model.addAttribute("lmtdMap", lmtdMap);
                                        model.addAttribute("avg3Monthlms", avg3Monthlms);
                                        model.addAttribute("lmsMap", lmsMap);
                                }

                        }
                }

                model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
                model.addAttribute("warehouseId", warehouseId);
                model.addAttribute("milestones", Milestone.values());

                return "sale-milestone";

        }

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

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                Set<Integer> fofoIds = csService.getAuthFofoIds(email);
                Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
                                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());

                if (fofoIds != null && fofoIds.size() > 0) {
                        if (warehouseId != 0) {
                                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
                                                .stream().map(x -> x).collect(Collectors.toSet());
                        }
                        Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
                        if (partnerStats != null) {
                                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
                                                .map(x -> partnerStats.get(x)).collect(Collectors.toList());
                                Map<Milestone, List<Integer>> avg3MonthS = new HashMap<>();
                                if (!last3MonthS.isEmpty()) {
                                        int days = 60 + LocalDateTime.now().getDayOfMonth();
                                        for (Entry<Integer, Double> last3MonthSEntry : last3MonthS.entrySet()) {
                                                if (fofoIds.contains(last3MonthSEntry.getKey())) {
                                                        Double monthSec = last3MonthSEntry.getValue();
                                                        if (monthSec == null) {
                                                                monthSec = (double) 0;

                                                        }
                                                        double avg3MonthSale = (monthSec / days) * 30;
                                                        Milestone milestone = Milestone.get((int) avg3MonthSale);

                                                        List<Integer> values = null;
                                                        if (avg3MonthS.containsKey(milestone)) {
                                                                values = avg3MonthS.get(milestone);
                                                                values.add(last3MonthSEntry.getKey());

                                                                avg3MonthS.put(milestone, values);
                                                        } else {

                                                                values = new ArrayList<>();

                                                                values.add(last3MonthSEntry.getKey());

                                                                avg3MonthS.put(milestone, values);

                                                        }
                                                }

                                        }

                                }

                                if (partnerDetails != null) {
                                        Map<Milestone, List<Integer>> smtdMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarymtd()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
                                        Map<Milestone, List<Integer>> slmtdMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylmtd()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
                                        Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
                                                        .collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylms()),
                                                                        Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));

                                        model.addAttribute("smtdMap", smtdMap);
                                        model.addAttribute("slmtdMap", slmtdMap);
                                        model.addAttribute("avg3MonthS", avg3MonthS);
                                        model.addAttribute("lmsMap", lmsMap);

                                }

                        }
                }

                model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
                model.addAttribute("warehouseId", warehouseId);
                model.addAttribute("milestones", Milestone.values());

                return "purchase-milestone";

        }

        @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);
                Set<Integer> fofoIds = csService.getAuthFofoIds(loginDetails.getEmailId());

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

        @RequestMapping(value = "/getMonthWiseSale", method = RequestMethod.GET)
        public String getPartnerSaleByMonth(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model)
                        throws Exception {

                YearMonth now = YearMonth.now();
                YearMonth ym = YearMonth.now().minusMonths(12);
                List<YearMonth> list = new ArrayList<>();
                while (!now.isBefore(ym)) {
                        list.add(now);
                        now = now.minusMonths(1);
                }

                model.addAttribute("yearMonth", list);

                List<PartnerMonthlySaleModel> partnerMonthlySaleModels = fofoOrderItemRepository
                                .selectPartnerMonthlySale(fofoIds, LocalDateTime.now().minusMonths(12).withDayOfMonth(1));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
                Map<Integer, Map<YearMonth, Double>> partnerMonthSaleMap = new HashMap<>();
                if (!partnerMonthlySaleModels.isEmpty()) {

                        partnerMonthSaleMap = partnerMonthlySaleModels.stream()
                                        .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toMap(
                                                        x -> YearMonth.parse(x.getYearMonth(), dateTimeFormatter), x -> (double) x.getAmount())));
                }

                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
                                .filter(x -> fofoIds.contains(x.getKey()))
                                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

                model.addAttribute("customRetailerMap", customRetailerMap);

                model.addAttribute("customRetailerMap", customRetailerMap);

                model.addAttribute("partnerMonthSaleMap", partnerMonthSaleMap);
                return "monthly-partner-sale";

        }

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

                YearMonth now = YearMonth.now();
                YearMonth ym = YearMonth.now().minusMonths(12);
                List<YearMonth> list = new ArrayList<>();
                while (!now.isBefore(ym)) {
                        list.add(now);
                        now = now.minusMonths(1);
                }

                model.addAttribute("yearMonth", list);

                List<PartnerMonthlySaleModel> partnerMonthlySaleModels = orderRepository.selectSecondaryGroupByYearMonth(fofoIds, LocalDate.now().withDayOfMonth(1).atStartOfDay().minusMonths(12));
                Map<Integer, Map<YearMonth, Double>> partnerMonthPurchaseMap = partnerMonthlySaleModels.stream()
                                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.groupingBy(y -> YearMonth.parse(y.getYearMonth(), DateTimeFormatter.ofPattern("MM-yyyy")),
                                                Collectors.summingDouble(x -> x.getAmount()))));

                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
                                .filter(x -> fofoIds.contains(x.getKey()))
                                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
                model.addAttribute("customRetailerMap", customRetailerMap);
                model.addAttribute("partnerMonthPurchaseMap", partnerMonthPurchaseMap);
                return "monthly-partner-purchase";

        }
}