Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

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

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

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

import com.google.gson.Gson;
import com.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.ContentType;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.enumuration.ReporticoProject;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ActivateItemModel;
import com.spice.profitmandi.common.model.Axis;
import com.spice.profitmandi.common.model.BrandStockPrice;
import com.spice.profitmandi.common.model.ChartInvestmentModel;
import com.spice.profitmandi.common.model.ChartModel;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.Data;
import com.spice.profitmandi.common.model.DataInvestmentModel;
import com.spice.profitmandi.common.model.DataModel;
import com.spice.profitmandi.common.model.DatasetModel;
import com.spice.profitmandi.common.model.Legend;
import com.spice.profitmandi.common.model.LegendModel;
import com.spice.profitmandi.common.model.Notification;
import com.spice.profitmandi.common.model.OptionModel;
import com.spice.profitmandi.common.model.OptionsModel;
import com.spice.profitmandi.common.model.PieLables;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.ScalesModel;
import com.spice.profitmandi.common.model.TitleModel;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.Interface.Campaign;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.auth.Menu;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.entity.user.Lead;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
import com.spice.profitmandi.dao.model.BrandWisePartnerSaleModel;
import com.spice.profitmandi.dao.model.BrandWiseUnbilledActivateStockModel;
import com.spice.profitmandi.dao.model.CreateOfferRequest;
import com.spice.profitmandi.dao.model.InStockBrandItemModel;
import com.spice.profitmandi.dao.model.InStockBrandModel;
import com.spice.profitmandi.dao.model.ItemWiseTertiaryModel;
import com.spice.profitmandi.dao.model.MonthSaleModel;
import com.spice.profitmandi.dao.model.PartnerDetailModel;
import com.spice.profitmandi.dao.model.PartnerPendingIndentItemModel;
import com.spice.profitmandi.dao.model.SimpleCampaign;
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
import com.spice.profitmandi.dao.model.WarehouseBrandItemUnbilledActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemSaleModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandSaleModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
import com.spice.profitmandi.dao.model.WarehouseWiseBrandUnbilledActivatedModel;
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.PartnerInvestmentService;
import com.spice.profitmandi.service.PartnerStatsService;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.offers.OfferService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

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

        private static final double ONE_LAC = 1 * 1000 * 100;
        private static final double TWO_LAC = 2 * 1000 * 100;
        private static final double FOUR_LAC = 4 * 1000 * 100;

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

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

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

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

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

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private PartnerStatsService partnerStatsService;

        @Autowired
        private MenuRepository menuRepository;

        @Autowired
        private MenuCategoryRepository menuCategoryRepository;

        @Autowired
        private CsService csService;

        @Autowired
        private PartnerTargetRepository partnerTargetRepository;

        @Autowired
        private ResponseSender<?> responseSender;

        @Autowired
        RetailerService retailerService;

        @Autowired
        private RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

        @Autowired
        DocumentRepository documentRepository;

        @Autowired
        InventoryItemRepository inventoryItemRepository;

        @Autowired
        InventoryService inventoryService;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        private TicketCategoryRepository ticketCategoryRepository;

        @Autowired
        private PartnerTypeChangeService partnerTypeChangeService;

        @Autowired
        private HygieneDataRepository hygieneDataRepository;

        @Autowired
        private UserCampaignRepository userCampaignRepository;

        @Autowired
        private PositionRepository positionRepository;
        @Autowired
        private PartnerTypeChangeRepository partnerTypeChangeRepository;

        @Autowired
        private PartnersPositionRepository partnerPositionRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private NotificationCampaignRepository notificationCampaignRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private Gson gson;

        @Autowired
        TicketRepository ticketRepository;

        @Autowired
        private LeadRepository leadRepository;

        @Autowired
        private OfferRepository offerRepository;

        @Autowired
        private OfferPartnerRepository offerPartnerRepository;

        @Autowired
        private OfferService offerService;

        @Autowired
        private OfferMarginRepository offerMarginRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;

        @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;
        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", hasGift(fofoId));
                        model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);

                        model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
                        model.addAttribute("salesMap", this.getSales(fofoId));
                        model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
                        // this.setInvestments
                        //
                        model.addAttribute("investments", this.getInvestments(fofoId));
                        model.addAttribute("isInvestmentOk",
                                        partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);

                }

                LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
                LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
                double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)
                                / 2;
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, 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(fofoId, true, currentMonthStart, currentMonthEnd);

                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,
                                currentMonthEnd);
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
                        invalidHygieneCount = 1;
                }
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));

                model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
                model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
                return "12dashboard34";
        }

        private Map<String, Object> getInvestments(int fofoId) throws Exception {
                Map<String, Object> investments = new LinkedHashMap<>();
                PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
                LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
                LocalDate yesterDate = LocalDate.now().minusDays(1);
                PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
                if (yesterdayInvestment == null) {
                        yesterdayInvestment = new PartnerDailyInvestment();
                }

                List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
                                currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));

                long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
                                .collect(Collectors.counting());
                investments.put("today", investment.getTotalInvestment());
                investments.put("investment", investment);
                investments.put("inStock", investment.getInStockAmount());
                investments.put("minimum", investment.getMinInvestmentString());
                investments.put("short", investment.getShortPercentage());
                investments.put("activated_stock", investment.getActivatedStockAmount());
                investments.put("okDays", okInvestmentDays);
                return investments;
        }

        private Map<String, Object> getSales(int fofoId) {

                Map<String, Object> salesMap = new LinkedHashMap<>();
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                int monthLength = LocalDate.now().lengthOfMonth();
                Double todaySale = fofoOrderItemRepository
                                .selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
                Double mtdSale = fofoOrderItemRepository
                                .selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false)
                                .get(fofoId);
                Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
                                curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);

                List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
                                .selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
                if (partnerTargetDetails.isEmpty()) {
                        partnerTargetDetails = partnerTargetRepository
                                        .selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
                }

                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());

                int currentRate = (int) (mtdSale / curDate.getDayOfMonth());

                salesMap.put("requiredType", partnerType.next());
                float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
                int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
                if (partnerType.equals(PartnerType.PLATINUM) && requiredRate < currentRate) {
                        requiredRate = currentRate;
                }
                salesMap.put("requiredRate", requiredRate);
                salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));

                salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
                salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
                salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);

                PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
                salesMap.put("currentRate", currentRate);
                salesMap.put("currentType", currentType);
                salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
                return salesMap;
        }

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

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

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

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

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

        private String format(long value) {
                String finalval = null;

                if (value >= 100000 && value < 10000000) {
                        long reminder = value / 100000;
                        long quitonent = value % 100000;
                        finalval = reminder + "." + quitonent;
                        String secondval = String.valueOf(quitonent);
                        if (secondval.length() >= 2) {
                                secondval = secondval.substring(0, 2);
                                finalval = reminder + "." + secondval;
                        }
                        return String.valueOf(finalval) + " Lacs";
                } else if (value >= 1000 && value < 100000) {
                        long reminder = value / 1000;
                        long quitonent = value % 1000;
                        finalval = reminder + "." + quitonent;
                        String secondval = String.valueOf(quitonent);
                        if (secondval.length() >= 2) {
                                secondval = secondval.substring(0, 2);
                                finalval = reminder + "." + secondval;
                        }
                        return String.valueOf(finalval) + " K";
                } else if (value >= 10000000 && value < 1000000000) {
                        long reminder = value / 10000000;
                        long quitonent = value % 10000000;
                        finalval = reminder + "." + quitonent;
                        String secondval = String.valueOf(quitonent);
                        if (secondval.length() >= 2) {
                                secondval = secondval.substring(0, 2);
                                finalval = reminder + "." + secondval;
                        }
                        return String.valueOf(finalval) + " Cr";
                }
                return String.valueOf(finalval);

        }

        private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
                Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);

                List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
                List<BrandStockPrice> brandStockPrices = new ArrayList<>();

                mobileBrands.stream().forEach(x -> {
                        String brand = (String) x.get("name");
                        if (brandStockPricesMap.containsKey(brand)) {
                                BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
                                brandStockPrice.setBrandUrl((String) x.get("url"));
                                brandStockPrice.setRank(((Double) x.get("rank")).intValue());
                                brandStockPrices.add(brandStockPrice);
                        }
                });

                return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
                                .collect(Collectors.toList());
        }

        @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
        public String dashboard(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                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 adminPanel(loginDetails.getFofoId(), email, model);
                } else {
                        FofoStore fofoStore = null;
                        try {
                                fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
                                if (!fofoStore.isActive()) {
                                        return "redirect:/login";
                                }

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

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

                                model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
                                model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
                                model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
                                ChartModel cm = this.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", this.getInvestments(loginDetails.getFofoId()));
                                model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
                                                10, ProfitMandiConstants.CUTOFF_INVESTMENT));

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

                        }
                }

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

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

                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
                                currentMonthStart, currentMonthEnd);
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
                        invalidHygieneCount = 1;
                }
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));

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

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

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

        private ChartInvestmentModel getInvestmentChart(int fofoId) throws ProfitMandiBusinessException {
                PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);

                Map<String, Float> investmentWalletAmount = new HashMap<>();
                investmentWalletAmount.put("Wallet", investment.getWalletAmount());
                investmentWalletAmount.put("InStocks", investment.getInStockAmount()-investment.getActivatedStockAmount());
                investmentWalletAmount.put("Unbilled Order", investment.getUnbilledAmount());
                investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
                investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());

                if (investment.getShortInvestment() > 0) {
                        investmentWalletAmount.put("Short Investment", investment.getShortInvestment());
                }

                ChartInvestmentModel cm = new ChartInvestmentModel();

                HashSet<String> labels = new HashSet<String>();
                labels.addAll(investmentWalletAmount.keySet());

                List<String> labelList = new ArrayList<>(labels);
                List<String> backgroundColor = new ArrayList<>();
                List<Float> labelsValue = new ArrayList<>();
                List<Float> values = new ArrayList<>();
                for (String label : labelList) {
                        values.add(investmentWalletAmount.get(label));
                        if (label.equals("Wallet")) {
                                backgroundColor.add("pink");
                        }
                        if (label.equals("Short Investment")) {
                                backgroundColor.add("red");
                        }
                        if (label.equals("InStocks")) {
                                backgroundColor.add("#9ACD32");
                        }
                        if (label.equals("Unbilled Order")) {
                                backgroundColor.add("blue");
                        }

                        if (label.equals("ReturnInTransit")) {
                                backgroundColor.add("orange");
                        }
                        if (label.equals("GrnPending")) {
                                backgroundColor.add("yellow");
                        }

                }

                Data data = new Data();
                data.setData(values);
                data.setBackgroundColor(backgroundColor);
                data.setLabel("DataSet 1");

                PieLables label = new PieLables();
                label.setFontColor("White");
                label.setFontSize(15);

                Legend legend = new Legend();
                legend.setLabels(label);
                legend.setPosition("left");

                List<Data> dataList = new ArrayList<>();
                dataList.add(data);

                DataInvestmentModel datasets = new DataInvestmentModel();
                datasets.setDatasets(dataList);
                datasets.setLabels(labels);

                OptionModel om = new OptionModel();
                om.setLegend(legend);
                cm.setType("pie");
                cm.setData(datasets);
                cm.setOptions(om);

                return cm;
        }

        private ChartModel getBrandChart(int fofoId) {

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

                LOGGER.info("cur Date" + curDate.withDayOfMonth(1));

                LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));

                Map<String, Double> brandwisesale = fofoOrderItemRepository
                                .selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);

                LOGGER.info("brandwisesale" + brandwisesale);

                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
                                fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
                brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
                
                Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
                                .selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));

                activatedImeisWithSellingPriceMTD.put("Lava", brandwisesale.get("Lava"));

                

                
                Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
                                .selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
                                                curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
                                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));

                Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
                                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
                activatedImeisWithSellingPriceLMTD.put("Lava", lmtdBrandWiseSale.get("Lava"));

                Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
                                fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
                                Optional.of(false));

                lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));

                ChartModel cm = new ChartModel();

                HashSet<String> labels = new HashSet<String>();
                labels.addAll(brandwisesale.keySet());
                labels.addAll(lmtdBrandWiseSale.keySet());

                List<String> labelList = new ArrayList<>(labels);

                List<Double> mtdActivatedImeisValues = new ArrayList<>();

                List<Double> mtdValues = new ArrayList<>();
                List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
                List<Double> lmtdActivatedImeisValues = new ArrayList<>();
                List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
                List<Double> lmtdValues = new ArrayList<>();
                for (String label : labelList) {
                        mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
                                        : activatedImeisWithSellingPriceMTD.get(label));
                        lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
                                        : activatedImeisWithSellingPriceLMTD.get(label));

                        mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
                        if (brandwisesale.get(label) != null) {
                                mtdUnActivatedImeisValues
                                                .add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
                                                                : activatedImeisWithSellingPriceMTD.get(label)));
                        } else {
                                mtdUnActivatedImeisValues.add(0.0);
                        }
                        if (lmtdBrandWiseSale.get(label) != null) {
                                lmtdUnActivatedImeisValues
                                                .add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
                                                                : activatedImeisWithSellingPriceLMTD.get(label)));
                        } else {
                                lmtdUnActivatedImeisValues.add(0.0);
                        }

                        lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
                }
                DatasetModel dsmtotal = new DatasetModel();
                dsmtotal.setLabel("MTD");
                dsmtotal.setBackgroundColor("blue");
                dsmtotal.setData(mtdValues);
                dsmtotal.setStack("stack0");
                dsmtotal.setOrder(1);

                DatasetModel dsmUnactivated = new DatasetModel();
                dsmUnactivated.setLabel("MTD Unactivated");
                dsmUnactivated.setBackgroundColor("red");
                dsmUnactivated.setData(mtdUnActivatedImeisValues);
                dsmUnactivated.setStack("stack0");
                dsmUnactivated.setOrder(1);

                LOGGER.info("mtdValuesMoney" + mtdValues);

                DatasetModel mtdActivatedImeis = new DatasetModel();
                mtdActivatedImeis.setLabel("MTD Activation");
                mtdActivatedImeis.setData(mtdActivatedImeisValues);
                mtdActivatedImeis.setBackgroundColor("#00008b");
                mtdActivatedImeis.setStack("stack0");
                mtdActivatedImeis.setOrder(1);

                DatasetModel lmtddsmtotal = new DatasetModel();
                lmtddsmtotal.setLabel("LMTD");
                lmtddsmtotal.setBackgroundColor("blue");
                lmtddsmtotal.setData(lmtdValues);
                lmtddsmtotal.setStack("stack1");
                lmtddsmtotal.setOrder(1);

                DatasetModel lmtdUnActivated = new DatasetModel();
                lmtdUnActivated.setLabel("LMTD Unactivation");
                lmtdUnActivated.setBackgroundColor("red");
                lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
                lmtdUnActivated.setStack("stack1");
                lmtdUnActivated.setOrder(1);

                DatasetModel LmtdActivatedImeis = new DatasetModel();
                LmtdActivatedImeis.setLabel("LMTD Activation");
                LmtdActivatedImeis.setBackgroundColor("#87ceeb");
                LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
                LmtdActivatedImeis.setStack("stack1");
                LmtdActivatedImeis.setOrder(1);

                DatasetModel linemtdChart = new DatasetModel();
                linemtdChart.setLabel("MTD");
                linemtdChart.setBackgroundColor("#006400");

                linemtdChart.setData(mtdValues);
                linemtdChart.setType("line");
                linemtdChart.setOrder(2);
                linemtdChart.setFill("false");

                DatasetModel lineLmtdChart = new DatasetModel();
                lineLmtdChart.setLabel("LMTD");
                lineLmtdChart.setBackgroundColor("hotpink");
                lineLmtdChart.setData(lmtdValues);
                lineLmtdChart.setType("line");
                lineLmtdChart.setOrder(3);
                lineLmtdChart.setFill("false");

                List<DatasetModel> datasets = new ArrayList<>();
                datasets.add(mtdActivatedImeis);
                datasets.add(dsmUnactivated);
                datasets.add(LmtdActivatedImeis);
                datasets.add(lmtdUnActivated);
                datasets.add(linemtdChart);
                datasets.add(lineLmtdChart);

                DataModel dm = new DataModel();
                dm.setDatasets(datasets);
                dm.setLabels(labels);

                LegendModel lm = new LegendModel();
                lm.setPosition("top");

                TitleModel tm = new TitleModel();
                tm.setText("Brand Wise Sales");
                tm.setDisplay(true);

                List<Axis> xAxes = new ArrayList<>();
                Axis xAxis = new Axis();
                xAxis.setStacked(true);
                xAxes.add(xAxis);

                List<Axis> yAxes = new ArrayList<>();
                Axis yAxis = new Axis();
                yAxis.setStacked(false);
                yAxes.add(yAxis);

                ScalesModel sm = new ScalesModel();
                sm.setxAxes(xAxes);

                OptionsModel om = new OptionsModel();
                om.setLegend(lm);
                om.setTitle(tm);
                om.setScales(sm);

                cm.setType("bar");
                cm.setData(dm);
                cm.setOptions(om);

                LOGGER.info("cm" + cm);

                return cm;

        }

        private String adminPanel(int fofoId, String email, Model model) throws Exception {
                List<Menu> menus = null;
                try {
                        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                        List<Position> positions = positionRepository.selectAll(authUser.getId());
                        Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
                        ReporticoCacheTable rctSaholic = null;
                        ReporticoCacheTable rctPartneStat = null;

                        Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
                        LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();

                        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                        LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();

                        Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
                        List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;

                        Map<AuthUser, Long> authUserTicketCount = null;

                        for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
                                wm.put(entry.getKey(), entry.getValue());
                        }

                        wm.put(0, "Total Values");
                        long stockValue = 0;
                        long stockQty = 0;
                        long pendingIndent = 0;
                        long tertiary = 0;

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

                                Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
                                                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
                                                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
                                                                Collectors.mapping(FofoStore::getId, Collectors.toList())));
                                // warehouseStock
                                List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
                                                .selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));

                                warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));

                                if (!warehouseStockMap.isEmpty()) {
                                        for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
                                                stockValue += warehouseStock.getValue().getStockValue();
                                                stockQty += warehouseStock.getValue().getStockQty();
                                                pendingIndent += warehouseStock.getValue().getPendingIndent();
                                                tertiary += warehouseStock.getValue().getTertiary();
                                        }
                                        WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
                                        ws.setStockQty(stockQty);
                                        ws.setStockValue(stockValue);
                                        ws.setPendingIndent(pendingIndent);
                                        ws.setTertiary(tertiary);
                                        ws.setWarehouseId(0);
                                        warehouseStockMap.put(0, ws);

                                }

                                warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                                                .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));

                                rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");

                                // warehouseStock
                                warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
                                rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");

                                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);
                                        }
                                }
                                accessoriesBrandSales = fofoStoreRepository
                                                .selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
                                Set<CustomRetailer> positionRetailers = fofoIds.stream().map(x->retailerService.getAllFofoRetailers().get(x)).filter(x->x!=null).collect(Collectors.toSet());
                                model.addAttribute("retailers", gson.toJson(positionRetailers));
                                model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
                                model.addAttribute("warehouses", getWarehouses(positionRetailers));
                        }

                        if (positions.size() > 0) {
                                if (positions.stream()
                                                .filter(x -> x.getEscalationType().equals(EscalationType.L3)
                                                                || x.getEscalationType().equals(EscalationType.L4)
                                                                || x.getEscalationType().equals(EscalationType.L5))
                                                .count() > 0) {
                                        authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
                                }
                        }

                        if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
                                        .contains(email))

                        {
                                menus = menuRepository.selectAll();
                        } else if (positions.size() > 0) {
                                if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
                                        menus = menuRepository.selectAll();
                                } else {
                                        List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
                                                        .map(x -> x.getMenuId()).collect(Collectors.toList());
                                        if (menuIds.size() > 0) {
                                                menus = menuRepository.selectAllByIds(menuIds);
                                        }
                                }
                        }
                                /*List<Position> salesPositions = positions.stream()
                                                .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
                                                .collect(Collectors.toList());
                                if (salesPositions.size() > 0) {
                                        Set<CustomRetailer> positionRetailers = new HashSet<>();
                                        csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
                                                positionRetailers.addAll(customRetailers);
                                        });
                                }*/
                                if(fofoIds == null) {
                                        List<Position> warehousePositions = positions.stream()
                                                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
                                                        .collect(Collectors.toList());
                                        if (warehousePositions.size() > 0) {
                                                Set<CustomRetailer> positionRetailers = new HashSet<>();
                                                csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
                                                        positionRetailers.addAll(customRetailers);
                                                });
                                                model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
                                                model.addAttribute("retailers", gson.toJson(positionRetailers));
                                                model.addAttribute("warehouses", getWarehouses(positionRetailers));
                                        }
                                }
                                model.addAttribute("authId", authUser.getId());

                        model.addAttribute("rctPartneStat", rctPartneStat);

                        model.addAttribute("reporticoDate", rctSaholic);
                        model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
                        model.addAttribute("warehouseMap", wm);

                        model.addAttribute("authUserTicketCount", authUserTicketCount);
                        model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
                        model.addAttribute("brandSalesMap", partnersBrandSaleMap);

                        model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);

                } catch (ProfitMandiBusinessException e) {
                }
                List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
                LOGGER.info("menu" + menuList);
                model.addAttribute("menu", menuList);
                return "admin";
        }

        @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();
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
                Set<Integer> authfofoIds = storeGuyMap.get(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 = this.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 {
                        fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
                                        .filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
                }

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

                return "auth_user_partner_detail";
        }

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

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

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

                return "warehouse_brand_stock";
        }

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

        public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
                        throws Exception {

                Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
                // Map<Integer, List<FofoStore>> warehousePartnerMap =
                // fofoStoreRepository.getWarehousePartnerMap();
                Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
                List<Integer> allfofoIds = new ArrayList<>();
                if (partnerStats != null) {
                        for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
                                List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
                                allfofoIds.addAll(fofoIds);
                                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
                                                .collect(Collectors.toList());
                                if (partnerDetails != null && !partnerDetails.isEmpty()) {
                                        PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
                                        warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
                                }

                        }
                        List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
                                        .collect(Collectors.toList());
                        LOGGER.info("allPartnerDetails" + allPartnerDetails);
                        PartnerDetailModel partnerDetailModel = partnerStatsService
                                        .getAggregateStats(new ArrayList<>(allPartnerDetails));
                        warehouseIdAndallValues.put(0, partnerDetailModel);
                }
                return warehouseIdAndallValues;
        }

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

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

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

        public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
                ObjectInputStream objectinputstream = null;
                Map<Integer, PartnerDetailModel> partnerStat = null;
                try {
                        FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
                        objectinputstream = new ObjectInputStream(streamIn);
                        partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();

                        LOGGER.info("partnerStat" + partnerStat);
                        objectinputstream.close();

                } catch (Exception e) {
                        LOGGER.info("exceptionddd" + e);

                        e.printStackTrace();

                } finally {
                        if (objectinputstream != null) {
                                objectinputstream.close();
                                LOGGER.info("clofddd" + partnerStat);

                        }
                }
                return partnerStat;

        }

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

        private String getWarehouses(Set<CustomRetailer> positionRetailers) {
                Map<Integer, String> warehouses = new HashMap<>();
                positionRetailers.stream().forEach(x -> {
                        if (x.getWarehouseId() != 0) {
                                warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
                        }
                });
                return gson.toJson(warehouses);

        }

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

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

                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);
                List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
                                .selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

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

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

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

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

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

        private List<Menu> prepareMenu(List<Menu> menus) {
                List<Menu> returnMenu = new ArrayList<>();
                Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
                for (Menu menu : menus) {
                        if (menu.get_parent() == null) {
                                if (!subMenuMap.containsKey(menu)) {
                                        subMenuMap.put(menu, new ArrayList<>());
                                }
                        } else {
                                Menu parentMenu = menu.get_parent();
                                if (!subMenuMap.containsKey(parentMenu)) {
                                        subMenuMap.put(parentMenu, new ArrayList<>());
                                }
                                subMenuMap.get(parentMenu).add(menu);
                        }
                }
                subMenuMap.entrySet().stream().forEach(entry -> {
                        entry.getKey().setSubMenus(entry.getValue());
                        returnMenu.add(entry.getKey());
                });
                return returnMenu;
        }

        // This method is currently hardcoded to faciliate watches sold as gift.
        private boolean hasGift(int fofoId) {
                try {
                        return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
                                        .getAvailability() > 0;
                } catch (ProfitMandiBusinessException e) {
                        return false;
                }
        }

        @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 = getNotifications(notificationCampaigns, messageType);

                model.addAttribute("notifications", notifications);

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

        public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
                        throws ProfitMandiBusinessException {
                List<Notification> notifications = new ArrayList<>();
                Document document = null;
                if (messageType != null) {
                        for (NotificationCampaign notificationCampaign : nc) {
                                if (notificationCampaign.getMessageType() == messageType) {
                                        Notification ns = new Notification();
                                        SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
                                                        SimpleCampaignParams.class);
                                        Campaign campaign = new SimpleCampaign(scp);
                                        LocalDateTime expire = campaign.getExpireTimestamp();
                                        ns.setCid(Integer.toString(notificationCampaign.getId()));
                                        ns.setType(campaign.getType());
                                        ns.setMessage(campaign.getMessage());
                                        ns.setTitle(campaign.getTitle());
                                        if (notificationCampaign.getDocumentId() != null) {
                                                document = documentRepository.selectById(notificationCampaign.getDocumentId());
                                                ns.setDocumentName(document.getDisplayName());
                                        }
                                        ns.setUrl(campaign.getUrl());
                                        ns.setShowImage(campaign.getShowImage());
                                        ns.setImageUrl(campaign.getImageUrl());
                                        ns.setDocumentId(notificationCampaign.getDocumentId());
                                        ns.setMessageType(notificationCampaign.getMessageType());
                                        ns.setCreated(
                                                        notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
                                                                        * 1000);
                                        if (LocalDateTime.now().isAfter(expire)) {
                                                ns.setExpired(true);
                                        } else {
                                                ns.setExpired(false);
                                        }
                                        notifications.add(ns);
                                }
                        }
                } else {
                        for (NotificationCampaign notificationCampaign : nc) {

                                Notification ns = new Notification();
                                SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
                                                SimpleCampaignParams.class);
                                Campaign campaign = new SimpleCampaign(scp);
                                LocalDateTime expire = campaign.getExpireTimestamp();
                                ns.setCid(Integer.toString(notificationCampaign.getId()));
                                ns.setType(campaign.getType());
                                ns.setMessage(campaign.getMessage());
                                ns.setTitle(campaign.getTitle());
                                if (notificationCampaign.getDocumentId() != null) {
                                        document = documentRepository.selectById(notificationCampaign.getDocumentId());
                                        ns.setDocumentName(document.getDisplayName());
                                }
                                ns.setUrl(campaign.getUrl());
                                ns.setShowImage(campaign.getShowImage());
                                ns.setImageUrl(campaign.getImageUrl());
                                ns.setDocumentId(notificationCampaign.getDocumentId());
                                ns.setMessageType(notificationCampaign.getMessageType());
                                ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
                                                * 1000);
                                if (LocalDateTime.now().isAfter(expire)) {
                                        ns.setExpired(true);
                                } else {
                                        ns.setExpired(false);
                                }
                                notifications.add(ns);
                        }

                }
                return notifications;

        }

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

        public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
                LOGGER.info("getL2AuthUserPartnerDetail Started");
                Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
                Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
                for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
                        List<Integer> authIds = l2l1.getValue();
                        authIds.add(l2l1.getKey());

                        List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
                        LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
                        AuthUser auth = authRepository.selectById(l2l1.getKey());
                        if (!leads.isEmpty()) {
                                authIdAndleadsCountMap.put(auth.getId(), leads.size());
                        } else {
                                authIdAndleadsCountMap.put(auth.getId(), 0);
                        }
                }

                Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
                List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
                                .collect(Collectors.toList());
                LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);

                Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();

                Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
                for (int authUserId : pp.keySet()) {
                        if (L2L1Mapping.keySet().contains(authUserId)) {
                                List<Integer> fofoIds = pp.get(authUserId);
                                unmappedPartners.removeAll(fofoIds);
                                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
                                                .collect(Collectors.toList());
                                LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
                                PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
                                authIdAndallValues.put(authUserId, partnerDetailModel);
                        }
                }
                List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
                                .collect(Collectors.toList());
                PartnerDetailModel partnerDetailModel = partnerStatsService
                                .getAggregateStats(new ArrayList<>(partnerStats.values()));
                authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
                authIdAndallValues.put(0, partnerDetailModel);
                return authIdAndallValues;
        }

        @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 = this.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";
        }

}