Subversion Repositories SmartDukaan

Rev

Rev 35583 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.google.gson.Gson;
import com.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.ContentType;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.*;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.StoreSalesTarget;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.Scheme;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
import com.spice.profitmandi.dao.entity.fofo.*;
import com.spice.profitmandi.dao.entity.transaction.LineItem;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
import com.spice.profitmandi.dao.enumuration.fofo.Milestone;
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
import com.spice.profitmandi.dao.model.SamsungUpgradeOfferModel;
import com.spice.profitmandi.dao.model.*;
import com.spice.profitmandi.dao.model.warehouse.LMSGraphRequest;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.catalog.*;
import com.spice.profitmandi.dao.repository.cs.*;
import com.spice.profitmandi.dao.repository.dtr.*;
import com.spice.profitmandi.dao.repository.fofo.*;
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
import com.spice.profitmandi.dao.service.SaleRewardService;
import com.spice.profitmandi.service.AdminUser;
import com.spice.profitmandi.service.FofoUser;
import com.spice.profitmandi.service.PartnerInvestmentService;
import com.spice.profitmandi.service.PartnerStatsService;
import com.spice.profitmandi.service.SshServer.SSHService;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.catalog.BrandsService;
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.offers.OfferService;
import com.spice.profitmandi.service.scheme.SchemeService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

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

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

    List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@smartdukaan.com", "ranu.rajput@smartdukaan.com", "vikas.jangra@smartdukaan.com", "aman.gupta@smartdukaan.com");

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

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

    @Autowired
    private CsService1 csService1;

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

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

    @Autowired
    private PriceDropRepository priceDropRepository;

    @Autowired
    private CookiesProcessor cookiesProcessor;

    @Autowired
    private PendingOrderRepository pendingOrderRepository;

    @Autowired
    private PartnerStatsService partnerStatsService;

    @Autowired
    private CsService csService;

    @Autowired
    private ResponseSender<?> responseSender;

    @Autowired
    RetailerService retailerService;

    @Autowired
    private AdminUser adminUser;

    @Autowired
    private RoleManager roleManager;

    @Autowired
    private FofoStoreRepository fofoStoreRepository;

    @Autowired
    private PartnerInvestmentService partnerInvestmentService;

    @Autowired
    DocumentRepository documentRepository;

    @Autowired
    InventoryItemRepository inventoryItemRepository;

    @Autowired
    InventoryService inventoryService;

    @Autowired
    private PendingOrderItemRepository pendingOrderItemRepository;

    @Autowired
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

    @Autowired
    private FofoOrderItemRepository fofoOrderItemRepository;

    @Autowired
    private PartnerTypeChangeService partnerTypeChangeService;

    @Autowired
    private HygieneDataRepository hygieneDataRepository;

    @Autowired
    private UserAccountRepository userAccountRepository;

    @Autowired
    private NotificationCampaignRepository notificationCampaignRepository;

    @Autowired
    private AuthRepository authRepository;

    @Autowired
    private FofoOrderRepository fofoOrderRepository;

    @Autowired
    private Gson gson;

    @Autowired
    TicketRepository ticketRepository;

    @Autowired
    private OfferService offerService;

    @Autowired
    private ItemRepository itemRepository;

    @Autowired
    private SaholicInventoryCISRepository saholicInventoryCISRepository;

    @Autowired
    private MVCResponseSender mvcResponseSender;

    @Autowired
    private ReporticoCacheTableRepository reporticoCacheTableRepository;

    @Autowired
    private TransactionService transactionService;

    @Autowired
    private TagListingRepository tagListingRepository;

    @Autowired
    private TicketAssignedRepository ticketAssignedRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private FofoUser fofoUser;

    @Autowired
    private ActivatedImeiRepository activatedImeiRepository;

    @Autowired
    private Mongo mongoClient;

    @Autowired
    private SchemeInOutRepository schemeInOutRepository;

    @Autowired
    private LineItemRepository lineItemRepository;

    @Autowired
    private FofoLineItemRepository fofoLineItemRepository;

    @Autowired
    private PositionRepository positionRepository;

    @Autowired
    private MonthlyTargetRepository monthlyTargetRepository;

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

    @Autowired
    private SSHService sshService;

    @Autowired
    BrandsService brandsService;

    @Autowired
    SaleRewardService saleRewardService;

    @Autowired
    SchemeService schemeService;
    @Autowired
    PrintResourceRegionRepository printResourceRegionRepository;
    @Autowired
    PartnerRegionRepository partnerRegionRepository;
    @Autowired
    PrintResourceRepository printResourceRepository;
    @Autowired
    CatalogRepository catalogRepository;
    @Autowired
    OfferRepository offerRepository;
    @Autowired
    OfferPayoutRepository offerPayoutRepository;
    @Value("${google.api.key}")
    private String googleApiKey;

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

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

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

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

            model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId, false));
            model.addAttribute("salesMap", fofoUser.getSales(fofoId));
            model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
            // this.setInvestments
            //
            Map<Integer, String> monthValueMap = new HashMap<>();
            for (int i = 0; i <= 5; i++) {
                LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
                monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
            }
            LOGGER.info("monthValueMap" + monthValueMap);
            Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
            brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
            brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.SMART_WATCH_CATEGORY_ID));
            brands.add("Live Demo");
            model.addAttribute("brands", brands);
            model.addAttribute("monthValueMap", monthValueMap);
            model.addAttribute("investments", fofoUser.getInvestments(fofoId));
            model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(fofoId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
        } catch (ProfitMandiBusinessException e) {
            LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);

        }

        return "12dashboard34";
    }

    @RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
    public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        int fofoId = loginDetails.getFofoId();
        Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
        int dayOfMonth = curDate.getDayOfMonth();
        YearMonth yearMonth = YearMonth.now();
        for (int i = 0; i <= 6; i++) {
            LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
            int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
            LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth, startOfMonth.plusMonths(1));
            double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
            LOGGER.info("Month sales - {}", monthSales);
            double mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false).get(fofoId);

            PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(fofoId, yearMonth.minusMonths(i));

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

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

    @RequestMapping(value = "/getBrandwisePartnerSale", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getBrandwisePartnerSale(
            HttpServletRequest request,
            @RequestParam(name = "month", required = true, defaultValue = "0") int month,
            Model model) throws Exception {

        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        int fofoId = loginDetails.getFofoId();

        List<BrandWisePartnerSaleModel> mobileList =
                fofoStoreRepository.selectBrandWiseMonthlyPartnerSale(Collections.singletonList(fofoId), month);

        List<BrandWisePartnerSaleModel> accList =
                fofoStoreRepository.selectBrandWiseMonthlyPartnerAccessoriesSale(Collections.singletonList(fofoId), month);

        List<Map<String, Object>> response = new ArrayList<>();

        for (BrandWisePartnerSaleModel m : mobileList) {
            Map<String, Object> row = new HashMap<>();
            row.put("brand", m.getBrand());
            row.put("lms", fofoUser.format(m.getLms()));
            row.put("lmsQty", m.getLmsQty());
            row.put("mtd", fofoUser.format(m.getMtd()));
            row.put("mtdQty", m.getMtdQty());
            response.add(row);
        }

        long accLms = 0;
        long accLmtd = 0;
        long accMtd = 0;
        long accMtdQty = 0;
        for (BrandWisePartnerSaleModel a : accList) {
            accLms += a.getLms();
            accLmtd += a.getLmtd();
            accMtd += a.getMtd();
            accMtdQty += a.getMtdQty();
        }
        if (!accList.isEmpty()) {
            Map<String, Object> accRow = new HashMap<>();
            accRow.put("brand", "Accessories");
            accRow.put("lms", fofoUser.format(accLms));
            accRow.put("lmtd", fofoUser.format(accLmtd));
            accRow.put("mtd", fofoUser.format(accMtd));
            accRow.put("mtdQty", accMtdQty);
            response.add(accRow);
        }

        return response;
    }


    @RequestMapping(value = "/getBrandItemwisePartnerSale", method = RequestMethod.GET)
    @ResponseBody
    public List<BrandItemWisePartnerSaleModel> getBrandItemwisePartnerSale(HttpServletRequest request, @RequestParam(name = "month", required = true, defaultValue = "0") int month, @RequestParam(name = "brand") String brand, @RequestParam(name = "fofoId") Integer fofoId, Model model) throws Exception {
        List<BrandItemWisePartnerSaleModel> brandItemWisePartnerSaleModels = fofoStoreRepository.selectPartnerBrandItemMonthlySale(Collections.singletonList(fofoId), month, brand);
        LOGGER.info("brandItemWisePartnerSaleModels {}", brandItemWisePartnerSaleModels);
        return brandItemWisePartnerSaleModels;
    }

    @RequestMapping(value = "/getBrandItemwisePartnerSecondarySale", method = RequestMethod.GET)
    @ResponseBody
    public List<BrandItemWisePartnerSaleModel> getBrandItemwisePartnerSecondarySale(HttpServletRequest request, @RequestParam(name = "month", required = true, defaultValue = "0") int month, @RequestParam(name = "brand") String brand, @RequestParam(name = "fofoId") Integer fofoId, Model model) throws Exception {
        List<BrandItemWisePartnerSaleModel> brandItemWisePartnerSaleModels = fofoStoreRepository.selectPartnerBrandItemMonthlySecondarySale(Collections.singletonList(fofoId), month, brand);
        LOGGER.info("brandItemWisePartnerSaleModels {}", brandItemWisePartnerSaleModels);
        return brandItemWisePartnerSaleModels;
    }

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

        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
        List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
        LocalDate selectedDate = LocalDate.parse(date);

        // DB data (can be any order)
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> dbBulletins =
                adminUser.getTodayBulletin(positions, selectedDate.atStartOfDay());

        // Final ordered map (STRICT enum order)
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> bulletins =
                new LinkedHashMap<>();

        for (ProfitMandiConstants.BULLETIN_TYPE_ENUM type :
                ProfitMandiConstants.BULLETIN_TYPE_ENUM.values()) {

            List<BulletinOfferModal> list = dbBulletins.get(type);

            if (list != null && !list.isEmpty()) {
                bulletins.put(type, list);   // only add if has data
            }
        }

        model.addAttribute("bulletins", bulletins);
        return "bulletin-list";
    }


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

        model.addAttribute("webApiHost", webApiHost);
        model.addAttribute("webApiPort", webApiPort);
        model.addAttribute("webApiScheme", webApiScheme);
        model.addAttribute("webApiRoot", webApiRoot);
        model.addAttribute("googleApiKey", googleApiKey);

        if (isAdmin) {
            return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
        } else {
            FofoStore fofoStore;
            List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(fofoId);
            LocalDateTime currentDate = LocalDateTime.now();
            List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
            LOGGER.info("printresourcesList {}", printResources);
            model.addAttribute("printResources", printResources);
            try {
                fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
                if (!fofoStore.isActive()) {
                    return "redirect:/login";
                }

                LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
                LocalDateTime endtDate = LocalDateTime.now();
                OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
                LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());

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

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

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

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

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

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

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

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

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

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

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

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

                Scheme staticScheme = schemeService.getStaticScheme(fofoId);
                double schemeAchievement = 0;
                String schemeCategory = null;
                if (staticScheme != null) {
                    Map<Integer, Double> schemeAchievementMap = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(staticScheme.getStartDateTime(), staticScheme.getEndDateTime());
                    if (schemeAchievementMap.get(fofoId) != null) {
                        schemeAchievement = schemeAchievementMap.get(fofoId);
                        if (staticScheme.getTarget() >= 1500000 && staticScheme.getTarget() < 2500000) {
                            schemeCategory = "Silver Club";
                        } else if (staticScheme.getTarget() < 3000000) {
                            schemeCategory = "Gold Club";
                        } else if (staticScheme.getTarget() < 6000000) {
                            schemeCategory = "Rising Star Club";
                        } else if (staticScheme.getTarget() < 8000000) {
                            schemeCategory = "Super Star Club";
                        } else if (staticScheme.getTarget() < 10000000) {
                            schemeCategory = "Diamond Club";
                        } else if (staticScheme.getTarget() < 20000000) {
                            schemeCategory = "Platinum Club";
                        } else {
                            schemeCategory = "Premium Club";
                        }
                    }
                }


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

                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
                model.addAttribute("partnerType", partnerType);
                model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
                model.addAttribute("fofoStore", fofoStore);
                model.addAttribute("partnerType", partnerType);
                model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
                model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
                model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode()).append("partnerId", fofoStore.getId()).toString());
                model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
                model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
                model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);

                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(), curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));

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

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

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

                List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(loginDetails.getFofoId(), YearMonth.from(LocalDateTime.now()));

                // Batch fetch all catalog IDs to avoid N+1 queries
                Set<Integer> allCatalogIds = createOffers.stream()
                        .flatMap(offer -> offer.getTargetSlabs().stream())
                        .flatMap(slab -> slab.getItemCriteriaPayouts().stream())
                        .map(ItemCriteriaPayout::getItemCriteria)
                        .flatMap(criteria -> criteria.getCatalogIds().stream())
                        .collect(Collectors.toSet());

                final Map<Integer, String> catalogBrandMap = new HashMap<>();
                if (!allCatalogIds.isEmpty()) {
                    try {
                        catalogBrandMap.putAll(catalogRepository.selectAllByIds(new ArrayList<>(allCatalogIds)).stream()
                                .collect(Collectors.toMap(c -> c.getId(), c -> c.getBrand())));
                    } catch (ProfitMandiBusinessException e) {
                        LOGGER.error("Error fetching catalogs by IDs", e);
                    }
                }

                List<CreateOfferRequest> publishedOffers = createOffers.stream()
                        .filter(createOffer -> createOffer.getTargetSlabs().stream()
                                .flatMap(slab -> slab.getItemCriteriaPayouts().stream())
                                .map(ItemCriteriaPayout::getItemCriteria)
                                .flatMap(criteria -> criteria.getCatalogIds().stream())
                                .noneMatch(catalogId -> "Live Demo".equals(catalogBrandMap.get(catalogId))))
                        .collect(Collectors.toList());

                model.addAttribute("publishedOffers", publishedOffers);
                model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
                model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(), ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));

                double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(currentMonthStart, currentMonthEnd)) / 2;
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(lastMonthStart, currentMonthStart)) / 2;
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.withEndDate(currentMonthEnd)) / 2;
                model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
                model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
                model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);

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

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

                MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
                model.addAttribute("monthlyTarget", monthlyTarget);
                Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());

                model.addAttribute("brands", brands);
                model.addAttribute("monthValueMap", monthValueMap);
                model.addAttribute("month", 0);
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
                model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
                model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
                Map<String, Object> rewardsMap = saleRewardService.findByFofoAndRegionId(fofoId, partnerRegion.get(0).getRegionId());
                StoreSalesTarget targetData = saleRewardService.findTargetsByFofoId(fofoId);
                model.addAttribute("rewardsMap", rewardsMap);
                model.addAttribute("targetData", targetData);
                model.addAttribute("regionId", partnerRegion.get(0).getRegionId());



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

            }
            return "dashboard1";
        }

    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        orderStatus.add(SHIPPED_FROM_WH);

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

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

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



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

        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        Map<String, Object> data = retailerService
                .computeIncomeMap(loginDetails.getFofoId(), yearMonth);
//        long pendingIncome = 0;
//        long partnerPurchaseIn = 0;
//        long partnerCreditedSale = 0;
//        long partnerFrontIncome = 0;
//
//        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
//        LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();
//
//        AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository.selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
//        AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository.selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
//        AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository.selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
//
//        AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository.selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
//
//        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
//
//        long additionalIncome = offerPayoutImeiIncomeModels.stream().collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
//        // AllPurchaseInventoryModel partnerAdditionalIncome =
//        // offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth,
//        // endOfMonth);
//
//        LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);
//
//        LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
//        LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
//        LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);
//
//        if (partnerlPendingSaleAmount != null) {
//
//            pendingIncome = partnerlPendingSaleAmount.getAmount();
//
//            LOGGER.info("pendingIncome" + pendingIncome);
//
//        }
//
//        if (partnerCreditedSaleAmount != null) {
//
//            partnerCreditedSale = partnerCreditedSaleAmount.getAmount();
//
//            LOGGER.info("partnerCreditedSale" + partnerCreditedSale);
//
//        }
//        if (partnerFrontIncomes != null) {
//
//            partnerFrontIncome = partnerFrontIncomes.getAmount();
//            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
//
//        }
//        if (partnerPurchaseInAmount != null) {
//
//            partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
//            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
//
//        }
//
//        LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
//        LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
//        LOGGER.info("pendingIncomeTT" + pendingIncome);
//
//        long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome + additionalIncome;
//
//        long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;
//
//        long pendingTotalIncome = pendingIncome;
//        LOGGER.info("totalIncome" + totalIncome);
//        LOGGER.info("creditedIncome" + creditedIncome);
//        LOGGER.info("pendingTotalIncome" + pendingTotalIncome);
//
        model.addAttribute("totalIncome", data.get("totalIncome"));
        model.addAttribute("creditedIncome", data.get("creditedIncome"));
        model.addAttribute("pendingTotalIncome", data.get("pendingIncome"));
//
//        Map<Integer, String> monthValueMap = new HashMap<>();
//        for (int i = 0; i <= 5; i++) {
//            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
//            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
//        }
//
        model.addAttribute("month", data.get("monthIndex"));
        model.addAttribute("monthValueMap", data.get("monthValueMap"));
        LOGGER.info("income data", data);
        model.addAttribute("data", data);
        return "partner-total-income";
    }

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

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

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

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

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

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

    @RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
    public String getlmsLineChart(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
        if (fofoId == 0) {
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
            fofoId = loginDetails.getFofoId();
        }

        ChartModel cm = fofoUser.getLmsLineChart(fofoId);

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

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

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

        return "purchase_chart";
    }

    @RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
    public String getBarChart(HttpServletRequest request, @RequestParam(required = false) LocalDate from, @RequestParam(required = false) LocalDate to,@RequestParam(required = false) Boolean isQuantity ,Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        int fofoId = loginDetails.getFofoId();
        LocalDateTime curDate = from == null ? LocalDate.now().atStartOfDay().withDayOfMonth(1) : from.atStartOfDay();
        LocalDateTime lastDate = to == null ? LocalDate.now().atStartOfDay().with(LocalTime.MAX) : to.atStartOfDay();
        isQuantity = isQuantity==null?false:isQuantity;
        ChartModel cm = fofoUser.getBrandChart(fofoId, from, to,isQuantity);
        LOGGER.info("from" + curDate);
        LOGGER.info("to" + lastDate);
        LOGGER.info("chartMap" + gson.toJson(cm));
        model.addAttribute("chartMap", gson.toJson(cm));
        model.addAttribute("from", curDate.toLocalDate());
        model.addAttribute("to", lastDate.toLocalDate());
        model.addAttribute("fofoId", fofoId);
        model.addAttribute("isQuantity",isQuantity);
        return "bar_chart";
    }

    @GetMapping(value = "/brandWiseFofoSaleData")
    public String getBarChartModelWise(HttpServletRequest request,
                                       @RequestParam LocalDate from,
                                       @RequestParam LocalDate to,
                                       @RequestParam String brand,
                                       @RequestParam boolean isQuantity,
                                       @RequestParam int fofoId, Model model) throws Exception {
        ChartModel cm = fofoUser.getModelBrandChart(fofoId, brand, from, to,isQuantity);

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

        model.addAttribute("chartMap", gson.toJson(cm));
        return "bar_chart_model_wise";
    }

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

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

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

        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);

        model.addAttribute("priceDropdetailsList", priceDropdetailsList);

        return "price-drop-details";
    }

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

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

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

        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);

        model.addAttribute("priceDropdetailsList", priceDropdetailsList);

        return "price-drop-details";
    }

    @RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
    public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (fofoId == 0) {
            fofoId = loginDetails.getFofoId();
        }

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

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

        LOGGER.info("startfMonthTotal" + startfMonthTotal);

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

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

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

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

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

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

        LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);

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

        model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);
        LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);

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

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

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

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

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

        model.addAttribute("brands", brands);

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

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

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

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

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

            brandMonthValue.put(brand, sortedMonthBrandValue);

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

        }

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

        model.addAttribute("sortedBrandValue", sortedBrandValue);

        return "price-drop-tabular";
    }

    @RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
    public String getMonthlyActivation(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (fofoId == 0) {
            fofoId = loginDetails.getFofoId();
        }

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

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

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

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

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

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

        model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);

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

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

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

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

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

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

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

        model.addAttribute("brands", brands);

        for (String brand : brands) {
            Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
            for (int i = 5; i >= 0; i--) {
                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
                if (yearMonthValue != null) {
                    if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
                    }

                } else {
                    yearMonthValue = new HashMap<>();
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
                }
            }
            Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
            activationBrandMonthMap.put(brand, sortedMonthBrandValue);
            sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
        }

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

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

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

        List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository.selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);

        if (!activationItemDetails.isEmpty()) {
            // Batch fetch to avoid N+1 queries
            List<Integer> inventoryItemIds = activationItemDetails.stream()
                    .map(ActivationItemDetailModel::getInventoryItemId)
                    .collect(Collectors.toList());

            Map<Integer, List<FofoLineItem>> lineItemsByInventoryId;
            try {
                lineItemsByInventoryId = fofoLineItemRepository
                        .selectByInventoryItemIds(inventoryItemIds).stream()
                        .collect(Collectors.groupingBy(FofoLineItem::getInventoryItemId));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoLineItems by inventory IDs", e);
                lineItemsByInventoryId = new HashMap<>();
            }

            // Get max FofoOrderItemId for each inventory item
            Set<Integer> fofoOrderItemIds = lineItemsByInventoryId.values().stream()
                    .map(list -> list.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1))
                    .filter(id -> id > 0)
                    .collect(Collectors.toSet());

            Map<Integer, FofoOrderItem> fofoOrderItemMap;
            try {
                fofoOrderItemMap = fofoOrderItemRepository
                        .selectByIds(new ArrayList<>(fofoOrderItemIds)).stream()
                        .collect(Collectors.toMap(FofoOrderItem::getId, foi -> foi));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoOrderItems by IDs", e);
                fofoOrderItemMap = new HashMap<>();
            }

            Set<Integer> orderIds = fofoOrderItemMap.values().stream()
                    .map(FofoOrderItem::getOrderId)
                    .collect(Collectors.toSet());

            Map<Integer, FofoOrder> fofoOrderMap = new HashMap<>();
            try {
                fofoOrderMap = fofoOrderRepository
                        .selectAllByOrderIds(new ArrayList<>(orderIds)).stream()
                        .collect(Collectors.toMap(FofoOrder::getId, fo -> fo));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoOrders by order IDs", e);
            }

            for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
                List<FofoLineItem> flis = lineItemsByInventoryId.get(activationItemDetail.getInventoryItemId());
                if (flis != null && !flis.isEmpty()) {
                    int maxFofoOrderItemId = flis.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1);
                    FofoOrderItem foi = fofoOrderItemMap.get(maxFofoOrderItemId);
                    if (foi != null) {
                        FofoOrder fo = fofoOrderMap.get(foi.getOrderId());
                        if (fo != null) {
                            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
                        }
                    }
                }
            }
        }
        LOGGER.info("activationItemDetails" + activationItemDetails);

        model.addAttribute("activationItemDetails", activationItemDetails);

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

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

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

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

        if (!activationItemDetails.isEmpty()) {
            // Batch fetch to avoid N+1 queries
            List<Integer> inventoryItemIds = activationItemDetails.stream()
                    .map(ActivationItemDetailModel::getInventoryItemId)
                    .collect(Collectors.toList());

            Map<Integer, List<FofoLineItem>> lineItemsByInventoryId;
            try {
                lineItemsByInventoryId = fofoLineItemRepository
                        .selectByInventoryItemIds(inventoryItemIds).stream()
                        .collect(Collectors.groupingBy(FofoLineItem::getInventoryItemId));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoLineItems by inventory IDs", e);
                lineItemsByInventoryId = new HashMap<>();
            }

            Set<Integer> fofoOrderItemIds = lineItemsByInventoryId.values().stream()
                    .map(list -> list.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1))
                    .filter(id -> id > 0)
                    .collect(Collectors.toSet());

            Map<Integer, FofoOrderItem> fofoOrderItemMap;
            try {
                fofoOrderItemMap = fofoOrderItemRepository
                        .selectByIds(new ArrayList<>(fofoOrderItemIds)).stream()
                        .collect(Collectors.toMap(FofoOrderItem::getId, foi -> foi));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoOrderItems by IDs", e);
                fofoOrderItemMap = new HashMap<>();
            }

            Set<Integer> orderIds = fofoOrderItemMap.values().stream()
                    .map(FofoOrderItem::getOrderId)
                    .collect(Collectors.toSet());

            Map<Integer, FofoOrder> fofoOrderMap = new HashMap<>();
            try {
                fofoOrderMap = fofoOrderRepository
                        .selectAllByOrderIds(new ArrayList<>(orderIds)).stream()
                        .collect(Collectors.toMap(FofoOrder::getId, fo -> fo));
            } catch (ProfitMandiBusinessException e) {
                LOGGER.error("Error fetching FofoOrders by order IDs", e);
            }

            for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
                List<FofoLineItem> flis = lineItemsByInventoryId.get(activationItemDetail.getInventoryItemId());
                if (flis != null && !flis.isEmpty()) {
                    int maxFofoOrderItemId = flis.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1);
                    FofoOrderItem foi = fofoOrderItemMap.get(maxFofoOrderItemId);
                    if (foi != null) {
                        FofoOrder fo = fofoOrderMap.get(foi.getOrderId());
                        if (fo != null) {
                            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
                        }
                    }
                }
            }
        }
        LOGGER.info("activationItemDetails" + activationItemDetails);

        model.addAttribute("activationItemDetails", activationItemDetails);

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

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

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

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

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

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

        LOGGER.info("suos" + suos);

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

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

        model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);

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

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

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

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

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

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

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

        Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
        for (int i = 5; i >= 0; i--) {
            LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
            if (yearMonthValue != null) {
                if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
                }

            } else {
                yearMonthValue = new HashMap<>();
                yearMonthValue.put(YearMonth.from(startMonth), 0.0);
            }
        }
        Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
        upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
        sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
        LOGGER.info("sortedBrandValue" + sortedBrandValue);

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

    }

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

        LOGGER.info("params" + fofoId + brand + yearMonth);
        List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository.selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);

        model.addAttribute("offerItems", offerItems);

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

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

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

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

        model.addAttribute("offerItems", offerItems);

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

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

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

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

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

        return "auth_user_partner_detail";
    }

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

        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
        if (authfofoIds == null) {
            authfofoIds = new HashSet<>();
        }
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));

        if (!warehouseIdFofoIdMap.containsKey(7573)) {
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
        }

        Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
        Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
        if (fofoIdAndallValues == null) {
            fofoIdAndallValues = new HashMap<>();
        }
        if (warehouseId != 0) {
            List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
            if (fofoIds != null) {
                fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
            }
        }
        // warehouseId=0 means show all partner stats - no filtering needed
        ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
        model.addAttribute("chartPieMap", gson.toJson(cm));

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

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

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

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

        model.addAttribute("partnerTypes", partnerTypes);

        return "auth_user_partner_detail";
    }


    @RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
    public String getWarehouseWiseBrandStock(HttpServletRequest request, Model
            model, @RequestParam List<Integer> warehouseId) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));

        if (!warehouseIdFofoIdMap.containsKey(7573)) {
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
        }
        List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
        if (!warehouseId.contains(0)) {
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
        } else {
            LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));

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

        return "warehouse_brand_stock";
    }

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

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

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

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

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

        return "warehouse_brand_item_stock";
    }

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

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

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

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

        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            model.addAttribute("notifications", notifications);

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

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

    @Autowired
    PsiSmartService psiSmartService;

    @RequestMapping(value = "/psi/auth-endpoint", method = RequestMethod.GET)
    public ResponseEntity<?> getPartnerPSIUrl(HttpServletRequest request) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(loginDetails.getFofoId());
        return responseSender.ok(psiSmartService.getRegistrationEndPoint(customRetailer.getMobileNumber()));
    }

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

        NotificationCampaign nc = notificationCampaignRepository.selectById(cid);

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

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

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

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

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

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

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

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

        return "item-wise-indent";
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);

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

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

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

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

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

        if (!ticketAssigns.isEmpty()) {
            // Batch fetch AuthUsers to avoid N+1 queries
            Set<Integer> assigneeIds = ticketAssigns.stream()
                    .map(TicketAssigned::getAssineeId)
                    .collect(Collectors.toSet());

            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(assigneeIds)).stream()
                    .collect(Collectors.toMap(AuthUser::getId, au -> au));

            for (TicketAssigned ticketAssign : ticketAssigns) {
                AuthUser authUser = authUserMap.get(ticketAssign.getAssineeId());
                if (authUser != null) {
                    ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
                }
            }
        }
        model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
        model.addAttribute("ticketAssigns", ticketAssigns);
        model.addAttribute("customRetailer", customRetailer);
        return "open-ticket";
    }

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

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

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

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

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

        }

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

        return "partner-secondary-order";
    }

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

        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);

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

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

        model.addAttribute("brandSalesMap", partnersBrandSaleMap);

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

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

        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);

        List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;

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

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

    @PostMapping("/getMobileLMSGraph")
    public String getMobileLMSGraph(@RequestBody LMSGraphRequest lmsGraphRequest, Model model) throws Exception {
        LocalDate startDate = lmsGraphRequest.getDate().toLocalDate();
        LocalDate endLocalDate = lmsGraphRequest.getEndDate().toLocalDate();

        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(lmsGraphRequest.getFofoIds())
                .stream()
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));

        ChartModel cm;
        if (lmsGraphRequest.getWarehouseId() != 0) {
            cm = adminUser.getBrandWiseLms(
                    Arrays.asList(lmsGraphRequest.getWarehouseId()),
                    lmsGraphRequest.getFofoIds(),
                    startDate,
                    endLocalDate,
                    lmsGraphRequest.getFilterType()
            );
        } else {
            cm = adminUser.getBrandWiseLms(
                    new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                    lmsGraphRequest.getFofoIds(),
                    startDate,
                    endLocalDate,
                    lmsGraphRequest.getFilterType()
            );
        }

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

        return "brand-wise-mobile-lms-chart";
    }


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

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

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

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

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

            endDate = curDate;

        }

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

        return "chart-filter-lms";
    }

    @PostMapping("/getMobileLMPGraph")
    public String getMobileLMPGraph(@RequestBody LMSGraphRequest lmpGraphRequest, Model model) throws Exception {
        LocalDate startDate = lmpGraphRequest.getDate().toLocalDate();
        LocalDate endLocalDate = lmpGraphRequest.getEndDate().toLocalDate();

        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(lmpGraphRequest.getFofoIds())
                .stream()
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));

        ChartModel cm;
        if (lmpGraphRequest.getWarehouseId() != 0) {
            cm = adminUser.getBrandWiseLmp(
                    Arrays.asList(lmpGraphRequest.getWarehouseId()),
                    lmpGraphRequest.getFofoIds(),
                    startDate,
                    endLocalDate,
                    lmpGraphRequest.getFilterType()
            );
        } else {
            cm = adminUser.getBrandWiseLmp(
                    new ArrayList<>(warehouseIdFofoIdMap.keySet()),
                    lmpGraphRequest.getFofoIds(),
                    startDate,
                    endLocalDate,
                    lmpGraphRequest.getFilterType()
            );
        }

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

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

        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        String email = loginDetails.getEmailId();
        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);

        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
        Set<Integer> fofoIds = null;
        if (authFofoIds != null) {
            fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
        }


        Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);

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

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

                            List<Integer> values = null;

                            if (avg3Monthlms.containsKey(milestone)) {

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

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

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

                            }
                        }

                    }

                }

                if (partnerDetails != null) {

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

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

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

            }
        }

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

        return "sale-milestone";

    }

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

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

        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);

        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
        Set<Integer> fofoIds = null;
        if (authFofoIds != null) {
            fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
        }

        Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());

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

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

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

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

                                values = new ArrayList<>();

                                values.add(last3MonthSEntry.getKey());

                                avg3MonthS.put(milestone, values);

                            }
                        }

                    }

                }

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

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

                }

            }
        }

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

        return "purchase-milestone";

    }

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

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

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

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

    @RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
    public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        Set<Integer> fofoIds = csService1.getAuthFofoIds(loginDetails.getEmailId(), true);

        List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository.selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
        model.addAttribute("activatedModels", activatedModels);
        return "activation-brandwise-report";
    }

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

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

    }

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

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

        List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository.selectActivatedUpdationDate();

        // Create a map for quick lookup of existing results
        Map<String, ActivationImeiUpdationModel> resultMap = activationImeiUpdations.stream()
                .collect(Collectors.toMap(
                        m -> m.getWarehouseId() + "_" + m.getBrand(),
                        m -> m
                ));

        // Merge with master data - add missing combinations with null timestamp
        List<ActivationImeiUpdationModel> completeList = new ArrayList<>();
        for (Integer warehouseId : warehouseMap.keySet()) {
            for (String brand : brands) {
                String key = warehouseId + "_" + brand;
                ActivationImeiUpdationModel existing = resultMap.get(key);
                if (existing != null) {
                    completeList.add(existing);
                } else {
                    completeList.add(new ActivationImeiUpdationModel(warehouseId, brand, null));
                }
            }
        }

        model.addAttribute("warehouseMap", warehouseMap);
        model.addAttribute("activationImeiUpdations", completeList);
        return "activation-updation-timestamp";

    }

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

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

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

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

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

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

        model.addAttribute("yearMonth", list);

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

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

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

        model.addAttribute("customRetailerMap", customRetailerMap);

        model.addAttribute("customRetailerMap", customRetailerMap);

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

    }

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

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

        model.addAttribute("yearMonth", list);

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

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

    }

    @GetMapping("/restartServer")
    public String RestartServer(HttpServletRequest request, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (Arrays.asList("amit.gupta@smartdukaan.com", "shivam.gupta@smartdukaan.com", "vinay.p@smartdukaan.com").contains(loginDetails.getEmailId())) {
            String ipAddress = "45.79.106.95";
            int port = 22;
            String username = "root";
            String password = "spic@2015shop2020";
            String restartServices = "./restart-services.sh";
            sshService.executeCommand(ipAddress, port, username, password, restartServices);
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } else {
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
        }
        return "response";
    }

    @GetMapping("/rebootServer")
    public String rebootServer(HttpServletRequest request, Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (Arrays.asList("amit.gupta@smartdukaan.com", "shivam.gupta@smartdukaan.com", "vinay.p@smartdukaan.com").contains(loginDetails.getEmailId())) {
            String ipAddress = "45.79.106.95";
            int port = 22;
            String username = "root";
            String password = "spic@2015shop2020";
            String rebootCommand = "reboot";

            sshService.executeCommand(ipAddress, port, username, password, rebootCommand);
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } else {
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
        }
        return "response";
    }

    @GetMapping("/getRestartServer")
    public String getRestartServer(HttpServletRequest request, Model model) {
        return "restart-server-page";
    }
}