Rev 26432 | Rev 26434 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.controller;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.ZoneOffset;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Optional;import java.util.Set;import java.util.stream.Collectors;import javax.servlet.http.HttpServletRequest;import javax.transaction.Transactional;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.cglib.core.Local;import org.springframework.core.io.InputStreamResource;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.google.gson.Gson;import com.mongodb.DBObject;import com.spice.profitmandi.common.enumuration.ContentType;import com.spice.profitmandi.common.enumuration.MessageType;import com.spice.profitmandi.common.enumuration.ReporticoProject;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.BrandStockPrice;import com.spice.profitmandi.common.model.ChartModel;import com.spice.profitmandi.common.model.CustomRetailer;import com.spice.profitmandi.common.model.DataModel;import com.spice.profitmandi.common.model.DatasetModel;import com.spice.profitmandi.common.model.LegendModel;import com.spice.profitmandi.common.model.Notification;import com.spice.profitmandi.common.model.OptionsModel;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.model.TitleModel;import com.spice.profitmandi.common.web.util.ResponseSender;import com.spice.profitmandi.dao.Interface.Campaign;import com.spice.profitmandi.dao.entity.auth.AuthUser;import com.spice.profitmandi.dao.entity.auth.Menu;import com.spice.profitmandi.dao.entity.cs.Position;import com.spice.profitmandi.dao.entity.dtr.Document;import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;import com.spice.profitmandi.dao.entity.fofo.FofoStore;import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;import com.spice.profitmandi.dao.entity.fofo.PartnerType;import com.spice.profitmandi.dao.entity.user.Lead;import com.spice.profitmandi.dao.enumuration.cs.EscalationType;import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;import com.spice.profitmandi.dao.model.PartnerDetailModel;import com.spice.profitmandi.dao.model.SimpleCampaign;import com.spice.profitmandi.dao.model.SimpleCampaignParams;import com.spice.profitmandi.dao.repository.auth.AuthRepository;import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;import com.spice.profitmandi.dao.repository.auth.MenuRepository;import com.spice.profitmandi.dao.repository.cs.CsService;import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;import com.spice.profitmandi.dao.repository.cs.PositionRepository;import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;import com.spice.profitmandi.dao.repository.cs.TicketRepository;import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.LeadRepository;import com.spice.profitmandi.dao.repository.dtr.Mongo;import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;import com.spice.profitmandi.service.PartnerInvestmentService;import com.spice.profitmandi.service.authentication.RoleManager;import com.spice.profitmandi.service.inventory.InventoryService;import com.spice.profitmandi.service.user.RetailerService;import com.spice.profitmandi.web.model.LoginDetails;import com.spice.profitmandi.web.util.CookiesProcessor;@Controller@Transactional(rollbackOn = Throwable.class)public class DashboardController {private static final double ONE_LAC = 1*1000*100;private static final double TWO_LAC = 2*1000*100;private static final double FOUR_LAC = 4*1000*100;@Value("${web.api.host}")private String webApiHost;@Value("${web.api.scheme}")private String webApiScheme;@Value("${web.api.root}")private String webApiRoot;@Value("${web.api.port}")private int webApiPort;@Autowiredprivate CookiesProcessor cookiesProcessor;@Autowiredprivate MenuRepository menuRepository;@Autowiredprivate MenuCategoryRepository menuCategoryRepository;@Autowiredprivate CsService csService;@Autowiredprivate PartnerTargetRepository partnerTargetRepository;@Autowiredprivate ResponseSender<?> responseSender;@AutowiredRetailerService retailerService;@Autowiredprivate RoleManager roleManager;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;@Autowiredprivate PartnerInvestmentService partnerInvestmentService;@AutowiredDocumentRepository documentRepository;@AutowiredInventoryItemRepository inventoryItemRepository;@AutowiredInventoryService inventoryService;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;@Autowiredprivate FofoOrderItemRepository fofoOrderItemRepository;@Autowiredprivate TicketCategoryRepository ticketCategoryRepository;@Autowiredprivate PartnerTypeChangeService partnerTypeChangeService;@Autowiredprivate HygieneDataRepository hygieneDataRepository;@Autowiredprivate UserCampaignRepository userCampaignRepository;@Autowiredprivate PositionRepository positionRepository;@Autowiredprivate PartnersPositionRepository partnerPositionRepository;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate NotificationCampaignRepository notificationCampaignRepository;@Autowiredprivate Mongo mongoClient;@Autowiredprivate AuthRepository authRepository;@Autowiredprivate FofoOrderRepository fofoOrderRepository;@Autowiredprivate Gson gson;@AutowiredTicketRepository ticketRepository;@Autowiredprivate LeadRepository leadRepository;private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {boolean isAdmin = false;model.addAttribute("isAdmin", isAdmin);model.addAttribute("webApiHost", webApiHost);model.addAttribute("webApiPort", webApiPort);model.addAttribute("webApiScheme", webApiScheme);model.addAttribute("webApiRoot", webApiRoot);if (isAdmin) {return "dashboard1";}FofoStore fofoStore = null;try {CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);if (!fofoStore.isActive()) {return "redirect:/login";}PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());model.addAttribute("partnerType", partnerType);model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));model.addAttribute("fofoStore", customRetailer);model.addAttribute("partnerType", partnerType);model.addAttribute("hasGift", hasGift(fofoId));model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));model.addAttribute("salesMap", this.getSales(fofoId));model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));// this.setInvestments//model.addAttribute("investments", this.getInvestments(fofoId));model.addAttribute("isInvestmentOk",partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));} catch (ProfitMandiBusinessException e) {LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);}LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)/ 2;double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);long hygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, true, currentMonthStart, currentMonthEnd);long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,currentMonthEnd);if (hygieneCount == 0 && invalidHygieneCount == 0) {invalidHygieneCount = 1;}model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());return "12dashboard34";}private Map<String, Object> getInvestments(int fofoId) throws Exception {Map<String, Object> investments = new LinkedHashMap<>();PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);LocalDate yesterDate = LocalDate.now().minusDays(1);PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);if (yesterdayInvestment == null) {yesterdayInvestment = new PartnerDailyInvestment();}List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10).collect(Collectors.counting());investments.put("today", investment.getTotalInvestment());investments.put("investment", investment);investments.put("inStock", investment.getInStockAmount());investments.put("minimum", investment.getMinInvestmentString());investments.put("short", investment.getShortPercentage());investments.put("activated_stock", investment.getActivatedStockAmount());investments.put("okDays", okInvestmentDays);return investments;}private Map<String, Object> getSales(int fofoId) {Map<String, Object> salesMap = new LinkedHashMap<>();LocalDateTime curDate = LocalDate.now().atStartOfDay();int monthLength = LocalDate.now().lengthOfMonth();Double todaySale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);Double mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);Double lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());if (partnerTargetDetails.isEmpty()) {partnerTargetDetails = partnerTargetRepository.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));}PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());int currentRate = (int) (mtdSale / curDate.getDayOfMonth());salesMap.put("requiredType", partnerType.next());float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));salesMap.put("requiredRate", requiredRate);salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));salesMap.put("todaySale", todaySale == null ? 0 : todaySale);salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(mtdSale.floatValue());salesMap.put("currentRate", currentRate);salesMap.put("currentType", currentType);salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));return salesMap;}private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);List<BrandStockPrice> brandStockPrices = new ArrayList<>();mobileBrands.stream().forEach(x -> {String brand = (String) x.get("name");if (brandStockPricesMap.containsKey(brand)) {BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);brandStockPrice.setBrandUrl((String) x.get("url"));brandStockPrice.setRank(((Double) x.get("rank")).intValue());brandStockPrices.add(brandStockPrice);}});return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank()).collect(Collectors.toList());}@RequestMapping(value = "/dashboard", method = RequestMethod.GET)public String dashboard(HttpServletRequest request, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);String email = loginDetails.getEmailId();boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());model.addAttribute("isAdmin", isAdmin);model.addAttribute("webApiHost", webApiHost);model.addAttribute("webApiPort", webApiPort);model.addAttribute("webApiScheme", webApiScheme);model.addAttribute("webApiRoot", webApiRoot);if (isAdmin) {return adminPanel(loginDetails.getFofoId(), email, model);} else {FofoStore fofoStore = null;try {fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());if (!fofoStore.isActive()) {return "redirect:/login";}PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());model.addAttribute("partnerType", partnerType);model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));model.addAttribute("fofoStore", fofoStore);model.addAttribute("partnerType", partnerType);model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode()).append("partnerId", fofoStore.getId()).toString());model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));LocalDateTime curDate = LocalDate.now().atStartOfDay();Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);Double accesoriesStock = currentInventorySnapshotRepository.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),Optional.of(false)).get(loginDetails.getFofoId());model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));ChartModel cm = this.getBrandChart(loginDetails.getFofoId());LOGGER.info("chartMap" + gson.toJson(cm));model.addAttribute("chartMap", gson.toJson(cm));// this.setInvestments//model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),10, ProfitMandiConstants.CUTOFF_INVESTMENT));//Hardcoded for valentine//Hardcoded for valentineif(LocalDate.now().isBefore(LocalDate.of(2020, 3, 11))) {double valentineSales = fofoOrderItemRepository.selectSumAmountGroupByRetailer(LocalDate.of(2020, 3, 6).atStartOfDay(),LocalDate.of(2020, 3, 10).atStartOfDay(), loginDetails.getFofoId(), false).get(loginDetails.getFofoId());if(valentineSales < ONE_LAC) {model.addAttribute("valentineSale", "ONE_LAC");model.addAttribute("valentineShort", ONE_LAC - valentineSales);} else if(valentineSales < TWO_LAC) {model.addAttribute("valentineSale", "TWO_LAC");model.addAttribute("valentineShort", TWO_LAC - valentineSales);} else if (valentineSales < FOUR_LAC) {model.addAttribute("valentineSale", "FOUR_LAC");model.addAttribute("valentineShort", FOUR_LAC - valentineSales);} else {model.addAttribute("valentineSale", "CONGO");}}} catch (ProfitMandiBusinessException e) {LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());}}LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,currentMonthEnd) / 2;double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,currentMonthStart) / 2;double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,currentMonthEnd) / 2;model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,currentMonthEnd);long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,currentMonthStart, currentMonthEnd);if (hygieneCount == 0 && invalidHygieneCount == 0) {invalidHygieneCount = 1;}model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());return "dashboard1";}private ChartModel getBrandChart(int fofoId) {LocalDateTime curDate = LocalDate.now().atStartOfDay();LOGGER.info("cur Date" + curDate.withDayOfMonth(1));LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));Map<String, Double> brandwisesale = fofoOrderItemRepository.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);LOGGER.info("brandwisesale" + brandwisesale);Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),Optional.of(false));LOGGER.info("accesorieslmtdsale" + accesorieslmtdsale);ChartModel cm = new ChartModel();List<String> labels = new ArrayList<>();labels.addAll(brandwisesale.keySet());labels.add("accessories");List<Double> values = new ArrayList<>();values.addAll(brandwisesale.values());values.addAll(accesoriesmtdsale.values());List<Double> lmtdValues = new ArrayList<>();lmtdValues.addAll(lmtdBrandWiseSale.values());lmtdValues.addAll(accesorieslmtdsale.values());DatasetModel dsm = new DatasetModel();dsm.setLabel("mtd sales");List<String> backgroundColor = new ArrayList<>();for (Entry<String, Double> bs : brandwisesale.entrySet()) {backgroundColor.add("#3e95cd");}backgroundColor.add("#3e95cd");dsm.setBackgroundColor(backgroundColor);dsm.setData(values);DatasetModel lmtddsm = new DatasetModel();lmtddsm.setLabel("lmtd sales");List<String> background = new ArrayList<>();for (Entry<String, Double> bs : lmtdBrandWiseSale.entrySet()) {background.add("#8e5ea2");}background.add("#8e5ea2");lmtddsm.setBackgroundColor(background);lmtddsm.setData(lmtdValues);List<DatasetModel> datasets = new ArrayList<>();datasets.add(dsm);datasets.add(lmtddsm);DataModel dm = new DataModel();dm.setDatasets(datasets);dm.setLabels(labels);LegendModel lm = new LegendModel();lm.setDisplay(true);TitleModel tm = new TitleModel();tm.setText("Brand Wise Sale Graph");tm.setDisplay(true);OptionsModel om = new OptionsModel();om.setLegend(lm);om.setTitle(tm);cm.setType("bar");cm.setData(dm);cm.setOptions(om);return cm;}private String adminPanel(int fofoId, String email, Model model) throws Exception {List<Menu> menus = null;try {AuthUser authUser = authRepository.selectByEmailOrMobile(email);List<Position> positions = positionRepository.selectAll(authUser.getId());Map<Integer, AuthUser> authIdAndAuthUserMap = null;Map<Integer, Object> authIdAndallValues = null;if (positions.size() > 0) {if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L3)).count() > 0) {authIdAndAuthUserMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));authIdAndallValues = this.getL2AuthUserPartnerDetail();LOGGER.info("authIdAndallValues" + authIdAndallValues);}}if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in").contains(email)) {menus = menuRepository.selectAll();} else if (positions.size() > 0) {if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L4)).count() > 0) {menus = menuRepository.selectAll();} else {List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream().map(x -> x.getMenuId()).collect(Collectors.toList());LOGGER.info("Menu Ids are {}", menuIds);if (menuIds.size() > 0) {menus = menuRepository.selectAllByIds(menuIds);}}List<Position> salesPositions = positions.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES).collect(Collectors.toList());if (salesPositions.size() > 0) {Set<CustomRetailer> positionRetailers = new HashSet<>();csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {positionRetailers.addAll(customRetailers);});model.addAttribute("retailers", gson.toJson(positionRetailers));model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);model.addAttribute("warehouses", getWarehouses(positionRetailers));}List<Position> warehousePositions = positions.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE).collect(Collectors.toList());if (warehousePositions.size() > 0) {Set<CustomRetailer> positionRetailers = new HashSet<>();csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {positionRetailers.addAll(customRetailers);});model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);model.addAttribute("retailers", gson.toJson(positionRetailers));model.addAttribute("warehouses", getWarehouses(positionRetailers));}model.addAttribute("authId", authUser.getId());}model.addAttribute("authIdAndallValues", authIdAndallValues);model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);LOGGER.info("authIdAndallValues1" + authIdAndallValues);} catch (ProfitMandiBusinessException e) {}List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();LOGGER.info("menu" + menuList);model.addAttribute("menu", menuList);return "admin";}@RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET)public String L1AuthUsersDetail(HttpServletRequest request, Model model, @RequestParam int authId)throws Exception {Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();LocalDateTime curDate = LocalDate.now().atStartOfDay();Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);Map<Integer, Double> mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),curDate.with(LocalTime.MAX), 0, false);Map<Integer, List<Integer>> L2L1Mapping = csService.getL1L2Mapping();LOGGER.info("L2L1Mapping" + L2L1Mapping);List<Integer> l1authIds = L2L1Mapping.get(authId);Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>();Map<Integer, Object> authIdAndAuthUserMap = new LinkedHashMap<>();Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();for (Integer auth : l1authIds) {double totallmtdAmount = 0;double totalmtdAmount = 0;int totalTicketCount = 0;float totalTodayInvestment = 0;float totalStockInInvestment = 0;double currentMonthRatingAllPartners = 0;Map<Integer, Long> leadCount = leadRepository.selectByAssignAuthIdAndStatus(auth, LeadStatus.followUp).stream().collect(Collectors.groupingBy(Lead::getAssignTo, Collectors.counting()));AuthUser authUser = authRepository.selectById(auth);authIdAndAuthUserMap.put(auth, authUser);List<Integer> fofoIds = pp.get(auth);for (Integer fId : fofoIds) {Map<String, Object> investmentMap = this.getInvestments(fId);double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));currentMonthRatingAllPartners += currentMonthRating;fofoIds.size();Double lmtdAmount = lmtdSale.get(fId);Double mtdAmount = mtdSale.get(fId);Long ticketCount = ticketMap.get(fId);if (!investmentMap.isEmpty()) {totalTodayInvestment += (float) investmentMap.get("today");totalStockInInvestment += (float) investmentMap.get("inStock");}LOGGER.info("totalTodayInvestment" + totalTodayInvestment);LOGGER.info("totalStockInInvestment" + totalStockInInvestment);if (ticketCount != null) {totalTicketCount += ticketCount;}if (lmtdAmount != null) {totallmtdAmount += lmtdAmount;}if (mtdAmount != null) {totalmtdAmount += mtdAmount;}}LOGGER.info("currentMonthRatingAllPartners" + currentMonthRatingAllPartners);LOGGER.info("size" + fofoIds.size());double totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();LOGGER.info("totalHygieneRating" + totalHygieneRating);PartnerDetailModel pm = new PartnerDetailModel();pm.setLmtd(totallmtdAmount);pm.setMtd(totalmtdAmount);if (leadCount.get(auth) != null) {pm.setLeads(leadCount.get(auth).intValue());} else {pm.setLeads(0);}pm.setInvestment(totalTodayInvestment);pm.setStockInInvestment(totalStockInInvestment);pm.setTicket(totalTicketCount);pm.setHygiene((double) Math.round(totalHygieneRating));authIdAndallValues.put(auth, pm);}model.addAttribute("authIdAndallValues", authIdAndallValues);model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);LOGGER.info("authIdAndallValues" + authIdAndallValues);return "auth_user_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();List<Integer> fofoIds = pp.get(authId);Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();Map<Integer, Object> fofoIdAndallValues = new LinkedHashMap<>();Map<Integer, Object> fofoIdAndPartnerMap = new LinkedHashMap<>();for (Integer fofoId : fofoIds) {CustomRetailer cr = retailerService.getFofoRetailer(fofoId);fofoIdAndPartnerMap.put(fofoId, cr);LocalDateTime curDate = LocalDate.now().atStartOfDay();Double lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);Double mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);Map<String, Object> investmentMap = this.getInvestments(fofoId);double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId,curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));Long ticketCount = ticketMap.get(fofoId);float totalTodayInvestment = (float) investmentMap.get("today");float totalStockInInvestment = (float) investmentMap.get("inStock");PartnerDetailModel pm = new PartnerDetailModel();pm.setLmtd(lmtdSale);pm.setMtd(mtdSale);pm.setInvestment(totalTodayInvestment);pm.setStockInInvestment(totalStockInInvestment);if (ticketCount != null) {pm.setTicket(ticketCount.intValue());} else {pm.setTicket(0);}pm.setHygiene((double) Math.round(currentMonthRating));fofoIdAndallValues.put(fofoId, pm);}model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);return "auth_user_partner_detail";}private String getWarehouses(Set<CustomRetailer> positionRetailers) {Map<Integer, String> warehouses = new HashMap<>();positionRetailers.stream().forEach(x -> {if (x.getWarehouseId() != 0) {warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));}});return gson.toJson(warehouses);}private List<Menu> prepareMenu(List<Menu> menus) {List<Menu> returnMenu = new ArrayList<>();Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();for (Menu menu : menus) {if (menu.get_parent() == null) {if (!subMenuMap.containsKey(menu)) {subMenuMap.put(menu, new ArrayList<>());}} else {Menu parentMenu = menu.get_parent();if (!subMenuMap.containsKey(parentMenu)) {subMenuMap.put(parentMenu, new ArrayList<>());}subMenuMap.get(parentMenu).add(menu);}}subMenuMap.entrySet().stream().forEach(entry -> {entry.getKey().setSubMenus(entry.getValue());returnMenu.add(entry.getKey());});return returnMenu;}// This method is currently hardcoded to faciliate watches sold as gift.private boolean hasGift(int fofoId) {try {return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId).getAvailability() > 0;} catch (ProfitMandiBusinessException e) {return false;}}@RequestMapping(value = "/contactUs", method = RequestMethod.GET)public String contactUs(HttpServletRequest request, Model model) throws Throwable {model.addAttribute("appContextPath", request.getContextPath());return "contact-us";}@RequestMapping(value = "/notifications", method = RequestMethod.GET)public String getNotificationsWithType(HttpServletRequest request,@RequestParam(required = false) MessageType messageType,@RequestParam(name = "offset", defaultValue = "0") int offset,@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);int userId = 0;boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());if (isAdmin) {userId = loginDetails.getFofoId();} else {userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());}List<Notification> notifications = null;List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,userId, offset, limit);LOGGER.info("messageType" + messageType);notifications = getNotifications(notificationCampaigns, messageType);model.addAttribute("notifications", notifications);LOGGER.info("notifications" + notifications);return "notification-template";}public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)throws ProfitMandiBusinessException {List<Notification> notifications = new ArrayList<>();Document document = null;if (messageType != null) {for (NotificationCampaign notificationCampaign : nc) {if (notificationCampaign.getMessageType() == messageType) {Notification ns = new Notification();SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),SimpleCampaignParams.class);Campaign campaign = new SimpleCampaign(scp);LocalDateTime expire = campaign.getExpireTimestamp();ns.setCid(Integer.toString(notificationCampaign.getId()));ns.setType(campaign.getType());ns.setMessage(campaign.getMessage());ns.setTitle(campaign.getTitle());if (notificationCampaign.getDocumentId() != null) {document = documentRepository.selectById(notificationCampaign.getDocumentId());ns.setDocumentName(document.getDisplayName());}ns.setUrl(campaign.getUrl());ns.setShowImage(campaign.getShowImage());ns.setImageUrl(campaign.getImageUrl());ns.setDocumentId(notificationCampaign.getDocumentId());ns.setMessageType(notificationCampaign.getMessageType());ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))* 1000);if (LocalDateTime.now().isAfter(expire)) {ns.setExpired(true);} else {ns.setExpired(false);}notifications.add(ns);}}} else {for (NotificationCampaign notificationCampaign : nc) {Notification ns = new Notification();SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),SimpleCampaignParams.class);Campaign campaign = new SimpleCampaign(scp);LocalDateTime expire = campaign.getExpireTimestamp();ns.setCid(Integer.toString(notificationCampaign.getId()));ns.setType(campaign.getType());ns.setMessage(campaign.getMessage());ns.setTitle(campaign.getTitle());if (notificationCampaign.getDocumentId() != null) {document = documentRepository.selectById(notificationCampaign.getDocumentId());ns.setDocumentName(document.getDisplayName());}ns.setUrl(campaign.getUrl());ns.setShowImage(campaign.getShowImage());ns.setImageUrl(campaign.getImageUrl());ns.setDocumentId(notificationCampaign.getDocumentId());ns.setMessageType(notificationCampaign.getMessageType());ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))* 1000);if (LocalDateTime.now().isAfter(expire)) {ns.setExpired(true);} else {ns.setExpired(false);}notifications.add(ns);}}return notifications;}@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)throws ProfitMandiBusinessException {Document document = documentRepository.selectById(documentId);NotificationCampaign nc = notificationCampaignRepository.selectById(cid);if (nc.getDocumentId() == null) {throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");}if (nc.getDocumentId() != documentId) {throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");}return responseSender.ok(document);}@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)throws ProfitMandiBusinessException {NotificationCampaign nc = notificationCampaignRepository.selectById(cid);if (nc.getDocumentId() == null) {throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");}Document document = documentRepository.selectById(nc.getDocumentId());FileInputStream file = null;try {file = new FileInputStream(document.getPath() + File.separator + document.getName());} catch (FileNotFoundException e) {LOGGER.error("Retailer Document file not found : ", e);throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");}// ByteArrayOutputStream byteArrayOutputStream = new// ByteArrayOutputStream();// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);final HttpHeaders headers = new HttpHeaders();String contentType = "";if (document.getContentType() == ContentType.JPEG) {contentType = "image/jpeg";} else if (document.getContentType() == ContentType.PNG) {contentType = "image/png";} else if (document.getContentType() == ContentType.PDF) {contentType = "application/pdf";}headers.set("Content-Type", contentType);headers.set("Content-disposition", "inline; filename=" + document.getName());headers.setContentLength(document.getSize());final InputStreamResource inputStreamResource = new InputStreamResource(file);return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);}public Map<Integer, Object> getL2AuthUserPartnerDetail() throws Exception {List<Position> pos = positionRepository.selectPositionbyCategoryIdAndEscalationType(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);LocalDateTime curDate = LocalDate.now().atStartOfDay();Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);Map<Integer, Double> mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),curDate.with(LocalTime.MAX), 0, false);Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();Map<Integer, List<Integer>> L2L1Mapping = csService.getL1L2Mapping();LOGGER.info("L2L1Mapping" + L2L1Mapping);for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {List<Integer> authIds = l2l1.getValue();authIds.add(l2l1.getKey());List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);AuthUser auth = authRepository.selectById(l2l1.getKey());if (!leads.isEmpty()) {authIdAndleadsCountMap.put(auth.getId(), leads.size());} else {authIdAndleadsCountMap.put(auth.getId(), 0);}}LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>();for (Position po : pos) {double totallmtdAmount = 0;double totalmtdAmount = 0;int totalTicketCount = 0;float totalTodayInvestment = 0;float totalStockInInvestment = 0;double currentMonthRatingAllPartners = 0;AuthUser auth = authRepository.selectById(po.getAuthUserId());List<Integer> fofoIds = pp.get(po.getAuthUserId());for (Integer fId : fofoIds) {Map<String, Object> investmentMap = this.getInvestments(fId);double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));currentMonthRatingAllPartners += currentMonthRating;fofoIds.size();Double lmtdAmount = lmtdSale.get(fId);Double mtdAmount = mtdSale.get(fId);Long ticketCount = ticketMap.get(fId);if (!investmentMap.isEmpty()) {totalTodayInvestment += (float) investmentMap.get("today");totalStockInInvestment += (float) investmentMap.get("inStock");}LOGGER.info("totalTodayInvestment" + totalTodayInvestment);LOGGER.info("totalStockInInvestment" + totalStockInInvestment);if (ticketCount != null) {totalTicketCount += ticketCount;}if (lmtdAmount != null) {totallmtdAmount += lmtdAmount;}if (mtdAmount != null) {totalmtdAmount += mtdAmount;}}LOGGER.info("currentMonthRatingAllPartners" + currentMonthRatingAllPartners);LOGGER.info("size" + fofoIds.size());double totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap.get(po.getAuthUserId()));PartnerDetailModel pm = new PartnerDetailModel();pm.setLmtd(totallmtdAmount);pm.setMtd(totalmtdAmount);if(authIdAndleadsCountMap == null) {pm.setLeads(0);}else {pm.setLeads(authIdAndleadsCountMap.get(po.getAuthUserId()));}pm.setInvestment(totalTodayInvestment);pm.setStockInInvestment(totalStockInInvestment);pm.setTicket(totalTicketCount);pm.setHygiene((double) Math.round(totalHygieneRating));authIdAndallValues.put(auth.getId(), pm);}return authIdAndallValues;}}