Rev 25642 | Rev 25653 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.controller;import java.text.DecimalFormat;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.ZoneOffset;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;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.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.MediaType;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.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.BrandStockPrice;import com.spice.profitmandi.common.model.Notification;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.model.SendNotificationModel;import com.spice.profitmandi.dao.Interface.Campaign;import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;import com.spice.profitmandi.dao.entity.dtr.UserCampaign;import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;import com.spice.profitmandi.dao.entity.fofo.FofoStore;import com.spice.profitmandi.dao.entity.fofo.HygieneData;import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;import com.spice.profitmandi.dao.entity.fofo.PartnerTarget;import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;import com.spice.profitmandi.dao.entity.fofo.PartnerType;import com.spice.profitmandi.dao.model.SimpleCampaign;import com.spice.profitmandi.dao.model.SimpleCampaignParams;import com.spice.profitmandi.dao.repository.catalog.ItemRepository;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;import com.spice.profitmandi.dao.repository.dtr.Mongo;import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;import com.spice.profitmandi.dao.repository.dtr.NotificationPanelRepository;import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;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.HygieneDataRepository;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.dao.repository.fofo.TargetSlabRepository;import com.spice.profitmandi.dao.repository.user.UserRepository;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.slab.TargetSlabService;import com.spice.profitmandi.service.transaction.TransactionService;import com.spice.profitmandi.web.model.LoginDetails;import com.spice.profitmandi.web.util.CookiesProcessor;import com.spice.profitmandi.web.util.MVCResponseSender;@Controller@Transactional(rollbackOn = Throwable.class)public class DashboardController {@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 ItemRepository itemRepository;@Autowiredprivate TargetSlabService targetSlabService;@Autowiredprivate PartnerTargetRepository partnerTargetRepository;@Autowiredprivate TargetSlabRepository targetSlabRepository;@Autowiredprivate RoleManager roleManager;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;@Autowiredprivate PartnerInvestmentService partnerInvestmentService;@Autowiredprivate InsurancePolicyRepository insurancePolicyRepository;/** @Autowired private ScanRepository scanRepository;*/@Autowiredprivate RechargeTransactionRepository rechargeTransactionRepository;@Autowiredprivate TransactionService transactionService;@Autowiredprivate InventoryService inventoryService;@Autowiredprivate MVCResponseSender mvcResponseSender;@Autowiredprivate NotificationPanelRepository notificationPanelRepository;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;@Autowiredprivate FofoOrderItemRepository fofoOrderItemRepository;@Autowiredprivate InsuranceProviderRepository insuranceProviderRepository;@Autowiredprivate PartnerTypeChangeService partnerTypeChangeService;@Autowiredprivate HygieneDataRepository hygieneDataRepository;@Autowiredprivate UserCampaignRepository userCampaignRepository;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate NotificationCampaignRepository notificationCampaignRepository;@Autowiredprivate Mongo mongoClient;@Autowiredprivate Gson gson;private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)public String dashboard1(HttpServletRequest request, Model model) throws Exception {LOGGER.info("In Dashboard1");LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());model.addAttribute("isAdmin", isAdmin);if (!isAdmin) {// model.addAttribute("brandStockPrices",// this.getBrandStockPrices(loginDetails.getFofoId()));model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));return "dashboard1";}return "dashboard1";}private Map<String, Object> getInvestments(int fofoId) throws Exception {Map<String, Object> investments = new LinkedHashMap<>();PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 1);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("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();List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectBetweenCreatedTime(fofoId, curDate,curDate.with(LocalTime.MAX));List<FofoOrderItem> mtdFofoOrderItems = fofoOrderItemRepository.selectBetweenCreatedTime(fofoId,curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));double todaySale = fofoOrderItems.stream().collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));double mtdSale = mtdFofoOrderItems.stream().collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());if (partnerTargetDetails.isEmpty()) {partnerTargetDetails = partnerTargetRepository.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(2));}List<Integer> targetIds = partnerTargetRepository.selectAllPartnerTargetForPartner(fofoId,partnerTargetDetails.stream().map(x -> x.getId()).collect(Collectors.toList())).stream().map(x -> x.getTargetId()).collect(Collectors.toList());if (targetIds.size() > 0) {PartnerTarget target = partnerTargetRepository.selectAllPartnerTargetForPartner(fofoId, targetIds).get(0);double targetValue = (double) target.getTargetValue();int remainingDays = monthLength - curDate.getDayOfMonth() + 1;// Should not consider today's sale while evaluating today's target.double todayTargetValue = Math.round((targetValue - (mtdSale - todaySale)) / remainingDays);DecimalFormat df = new DecimalFormat("#.##");String targetValueString = df.format(targetValue / 100000) + "Lac";salesMap.put("todayTarget", todayTargetValue);salesMap.put("monthTarget", targetValueString);} else {salesMap.put("todayTarget", 0d);salesMap.put("monthTarget", 0d);}salesMap.put("todaySale", todaySale);salesMap.put("mtdSale", mtdSale);return salesMap;}/** private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws* Exception { Map<String, BrandStockPrice> brandStockPricesMap =* inventoryService.getBrandWiseStockValue(fofoId);** List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 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, @RequestParam(name = "offset", defaultValue = "0") int offset,@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());model.addAttribute("isAdmin", isAdmin);FofoStore fofoStore = null;model.addAttribute("webApiHost", webApiHost);model.addAttribute("webApiPort", webApiPort);model.addAttribute("webApiScheme", webApiScheme);model.addAttribute("webApiRoot", webApiRoot);if (isAdmin) {return "dashboard1";} else {try {fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());if (!fofoStore.isActive()) {return "redirect:/login";}LOGGER.info("partnerType {}", partnerType);model.addAttribute("partnerType", partnerType);model.addAttribute("fofoStore", fofoStore);model.addAttribute("partnerType", partnerType);model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);// model.addAttribute("brandStockPrices",// this.getBrandStockPrices(loginDetails.getFofoId()));model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));// this.setInvestments//model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),10, ProfitMandiConstants.CUTOFF_INVESTMENT));} catch (ProfitMandiBusinessException e) {LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());}}LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);List<HygieneData> hygieneData = hygieneDataRepository.selectAll(loginDetails.getFofoId(), currentMonthStart,LocalDateTime.now().plusMonths(1).withDayOfMonth(1)).stream().filter(x -> x.getDisposedTimestamp() != null).collect(Collectors.toList());LOGGER.info("hygieneData" + hygieneData);int successHygieneData = hygieneData.stream().filter(x -> x.getHygieneRating() == true).collect(Collectors.toList()).size();int unsuccessfullHygieneData = hygieneData.stream().filter(x -> x.getHygieneRating() == false).collect(Collectors.toList()).size();model.addAttribute("successHygieneData", successHygieneData);model.addAttribute("fullHygieneData", successHygieneData + unsuccessfullHygieneData);model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());return "dashboard1";}// 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(value = "") String notifyType,@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 = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());List<UserCampaign> userCampaigns = userCampaignRepository.selectByUserId(userId);List<Notification> notifications = new ArrayList<>();if (!userCampaigns.isEmpty()) {List<Integer> campaignIds = new ArrayList<>();for (UserCampaign userCampaign : userCampaigns) {campaignIds.add(userCampaign.getCampaignId());}List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.selectbyCids(campaignIds);if (notifyType.equals("annoucement")) {for (NotificationCampaign notificationCampaign : notificationCampaigns) {if (notificationCampaign.isAnnoucement() == true) {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());ns.setUrl(campaign.getUrl());ns.setShowImage(campaign.getShowImage());ns.setImageUrl(campaign.getImageUrl());ns.setAnnoucement(notificationCampaign.isAnnoucement());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 if (notifyType.equals("notification")) {for (NotificationCampaign notificationCampaign : notificationCampaigns) {if (notificationCampaign.isAnnoucement() == false) {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());ns.setUrl(campaign.getUrl());ns.setShowImage(campaign.getShowImage());ns.setImageUrl(campaign.getImageUrl());ns.setAnnoucement(notificationCampaign.isAnnoucement());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 : notificationCampaigns) {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());ns.setUrl(campaign.getUrl());ns.setShowImage(campaign.getShowImage());ns.setImageUrl(campaign.getImageUrl());ns.setAnnoucement(notificationCampaign.isAnnoucement());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);}}}model.addAttribute("notifications", notifications);LOGGER.info("notifications"+notifications);return "notification-template" ;}}