Subversion Repositories SmartDukaan

Rev

Rev 26028 | Rev 26056 | 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.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.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.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BrandStockPrice;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.Notification;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
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.cs.TicketCategory;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
import com.spice.profitmandi.dao.entity.dtr.UserCampaign;
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.enumuration.cs.EscalationType;
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.PositionRepository;
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
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.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.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 {

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

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

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

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

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private MenuRepository menuRepository;

        @Autowired
        private MenuCategoryRepository menuCategoryRepository;

        @Autowired
        private PartnerTargetRepository partnerTargetRepository;

        @Autowired
        private ResponseSender<?> responseSender;

        @Autowired
        RetailerService retailerService;

        @Autowired
        private RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

        @Autowired
        DocumentRepository documentRepository;

        @Autowired
        InventoryService inventoryService;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        private TicketCategoryRepository ticketCategoryRepository;

        @Autowired
        private PartnerTypeChangeService partnerTypeChangeService;

        @Autowired
        private HygieneDataRepository hygieneDataRepository;

        @Autowired
        private UserCampaignRepository userCampaignRepository;

        @Autowired
        private PositionRepository positionRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private NotificationCampaignRepository notificationCampaignRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private Gson gson;

        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";
                } else {
                        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));
                                // 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, 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();
                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(currentRate * monthLength);
                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.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, 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("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);
                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 String adminPanel(int fofoId, String email, Model model) throws ProfitMandiBusinessException {
                List<Menu> menus = null;
                try {
                        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                        List<Position> positions = positionRepository.selectAll(authUser.getId());
                        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);
                                        }
                                }

                        }
                } catch (ProfitMandiBusinessException e) {
                }
                List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();

                model.addAttribute("menu", menuList);
                return "admin";
        }

        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 = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
                List<UserCampaign> userCampaigns = userCampaignRepository.selectByUserId(userId);

                List<Notification> notifications = null;
                if (!userCampaigns.isEmpty()) {
                        List<Integer> campaignIds = new ArrayList<>();
                        for (UserCampaign userCampaign : userCampaigns) {
                                campaignIds.add(userCampaign.getCampaignId());
                        }
                        List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.selectbyCids(campaignIds,
                                        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);
        }

}