Subversion Repositories SmartDukaan

Rev

Rev 30479 | Rev 31884 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service;

import com.google.gson.Gson;
import com.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.*;
import com.spice.profitmandi.dao.Interface.Campaign;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
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.model.BrandWiseModel;
import com.spice.profitmandi.dao.model.SimpleCampaign;
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.fofo.*;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.inventory.InventoryService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Component
public class FofoUser {

        @Autowired
        private Gson gson;

        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        ChartService chartService;

        @Autowired
        FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        FofoOrderRepository fofoOrderRepository;

        @Autowired
        PartnerTypeChangeService partnerTypeChangeService;

        @Autowired
        PartnerTargetRepository partnerTargetRepository;

        @Autowired
        InventoryService inventoryService;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        DocumentRepository documentRepository;

        @Autowired
        CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        private static final Logger LOGGER = LogManager.getLogger(FofoUser.class);

        List<String> colorList = Arrays.asList("papayawhip", "mediumseagreen", "dodgerblue", "darkblue", "gold", "#eb0029", "coral",
                        "steelblue", "red", "deeppink", "midnightblue", "cornsilk");

        List<String> borderList = Arrays.asList("pink", "lawngreen", "lightblue", "#0000cd", "#f7e98e", "#eb0029", "lightcoral",
                        "#0000cd", "lightsalmon", "pink", "#0000cd", "cornsilk");

        List<String> brands = Arrays.asList("Accessories", "Oppo", "Vivo", "Samsung", "Realme", "Xiaomi", "OnePlus", "Tecno", "Itel",
                        "Lava", "Nokia");

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

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

        }

        public 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(Comparator.comparingInt(BrandStockPrice::getRank))
                                .collect(Collectors.toList());
        }

        public 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;
        }

        public Map<String, Object> getInvestmentsMonths(int fofoId, int month) throws Exception {
                Map<String, Object> investments = new LinkedHashMap<>();
                PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
                LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1).minusMonths(month);

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

        public ChartModel getLmsLineChart(int fofoId) throws ProfitMandiBusinessException {

                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
                Map<YearMonth, Map<String, Double>> monthValueMap = new HashMap<>();

                Map<String, Double> lmsBrandWiseSale = null;

                for (int i = 0; i <= 6; i++) {

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

                        LOGGER.info("startOfMonth" + startOfMonth);

                        lmsBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
                                        curDate.withDayOfMonth(1).minusMonths(i), curDate.withDayOfMonth(1).minusMonths(i - 1), fofoId);

                        Map<Integer, Double> accesorieslmsSale = fofoOrderRepository
                                        .selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(i),
                                                        curDate.withDayOfMonth(1).minusMonths(i - 1), Optional.of(false));
                        LOGGER.info("lmsBrandWiseSale" + lmsBrandWiseSale);

                        lmsBrandWiseSale.put("Accessories", accesorieslmsSale.get(fofoId));

                        monthValueMap.put(YearMonth.from(startOfMonth), lmsBrandWiseSale);
                        for (Entry<String, Double> lbw : lmsBrandWiseSale.entrySet()) {
                                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
                                if (brandMonthValue.containsKey(lbw.getKey())) {
                                        yearMonthValue = brandMonthValue.get(lbw.getKey());
                                        yearMonthValue.put(YearMonth.from(startOfMonth), lbw.getValue());
                                } else {

                                        yearMonthValue.put(YearMonth.from(startOfMonth), lbw.getValue());

                                }
                                brandMonthValue.put(lbw.getKey(), yearMonthValue);

                        }

                }

                LOGGER.info("brandMonthValue" + brandMonthValue);

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

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

                                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
                                LOGGER.info("startMonth" + startMonth);

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

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

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

                        brandMonthValue.put(brand, sortedMonthBrandValue);

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

                }

                LOGGER.info("brandMonthValue" + brandMonthValue);

                LOGGER.info("sortedBrandValue" + sortedBrandValue);

                ChartModel cm = chartService.createChart(6, sortedBrandValue, colorList, borderList, "Brand Wise LMS");

                return cm;

        }

        public ChartModel getPurchaseOrderChart(int fofoId) throws ProfitMandiBusinessException {

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

                LOGGER.info("startMonth" + curDate.withDayOfMonth(1).minusMonths(6));

                LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(1);
                List<BrandWiseModel> soblms = orderRepository.selectAllBilledOrderGroupByBrandFofoId(fofoId,
                                curDate.withDayOfMonth(1).minusMonths(6));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
                Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
                for (BrandWiseModel bwl : soblms) {
                        Map<YearMonth, Double> yearMonthValue = new HashMap<>();
                        if (brandMonthValue.containsKey(bwl.getBrand())) {
                                yearMonthValue = brandMonthValue.get(bwl.getBrand());
                                yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
                        } else {

                                yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());

                        }
                        brandMonthValue.put(bwl.getBrand(), yearMonthValue);

                }
                LOGGER.info("soblms" + brandMonthValue);

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

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

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

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

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

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

                        brandMonthValue.put(brand, sortedMonthBrandValue);

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

                }

                LOGGER.info("brandMonthValue" + brandMonthValue);

                ChartModel cm = chartService.createChart(6, sortedBrandValue, colorList, borderList,
                                "Brand Wise Monthly Purchase");

                return cm;

        }

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

                Map<String, Object> salesMap = new LinkedHashMap<>();
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
                int monthLength = LocalDate.now().lengthOfMonth();
                int daysGone = now.getDayOfMonth() - 1;
                int daysRemaining = monthLength - daysGone;
                Double todaySale = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday, now, fofoId, false)
                                .get(fofoId);
                Double mtdSaleTillYesterDay = fofoOrderItemRepository
                                .selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), startOfToday, fofoId, false).get(fofoId);
                Double mtdSale = mtdSaleTillYesterDay + todaySale;
                Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
                                startOfToday.withDayOfMonth(1).minusMonths(1), now.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 = 0;
                if (mtdSaleTillYesterDay > 0) {
                        currentRate = (int) (mtdSaleTillYesterDay / daysGone);
                }

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

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

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

        public ChartModel getBrandChart(int fofoId) {

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

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

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

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

                LOGGER.info("brandwisesale" + brandwisesale);

                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
                                fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
                brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));

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

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

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

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

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

                ChartModel cm = new ChartModel();

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

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

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

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

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

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

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

                LOGGER.info("mtdValuesMoney" + mtdValues);

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

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

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

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

                DatasetModel linemtdChart = new DatasetModel();
                linemtdChart.setLabel("MTD");
                linemtdChart.setBackgroundColor("#006400");
                linemtdChart.setBorderColor("#006400");
                linemtdChart.setData(mtdValues);
                linemtdChart.setType("line");
                linemtdChart.setOrder(2);
                linemtdChart.setFill("false");

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

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

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

                Tooltips tooltips = new Tooltips();
                tooltips.setBodyFontSize(10);
                tooltips.setTitleFontSize(10);
                tooltips.setMode("index");
                tooltips.setIntersect(false);
                tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
                HoverModel hover = new HoverModel();
                hover.setIntersect(false);
                hover.setMode("index");

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

                TitleModel tm = new TitleModel();
                tm.setText("Brand Wise Sales");
                tm.setDisplay(true);
                tm.setFontSize(20);
                tm.setFontColor("#111");

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

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

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

                OptionsModel om = new OptionsModel();
                om.setLegend(lm);
                om.setTitle(tm);
                om.setScales(sm);
                om.setHover(hover);
                om.setTooltips(tooltips);

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

                LOGGER.info("cm" + cm);

                return cm;

        }

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

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

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

                ChartInvestmentModel cm = new ChartInvestmentModel();

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

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

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

                }

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

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

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

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

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

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

                return cm;
        }

        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;

        }

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

}