Subversion Repositories SmartDukaan

Rev

Rev 25002 | Rev 25136 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.IOException;
import java.net.URISyntaxException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.RechargeStatus;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BrandStockPrice;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
import com.spice.profitmandi.dao.entity.dtr.NotificationData;
import com.spice.profitmandi.dao.entity.dtr.RechargeTransaction;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.enumuration.dtr.RechargeType;
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.NotificationPanelRepository;
import com.spice.profitmandi.dao.repository.dtr.RechargeTransactionRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
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.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(rollbackFor = 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 ItemRepository itemRepository;

        @Autowired
        private RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

        @Autowired
        private InsurancePolicyRepository insurancePolicyRepository;
        /*
         * @Autowired private ScanRepository scanRepository;
         */
        @Autowired
        private RechargeTransactionRepository rechargeTransactionRepository;

        @Autowired
        private TransactionService transactionService;
        
        @Autowired
        private InventoryService inventoryService;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private NotificationPanelRepository notificationPanelRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        private InsuranceProviderRepository insuranceProviderRepository;
        
        @Autowired
        private Mongo mongoClient;

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

        @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
        public String dashboard(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
                        throws ProfitMandiBusinessException, URISyntaxException, IOException {
                // LOGGER.info("scanRepository.selectScansByInventoryItemId(1)",
                // scanRepository.selectScansByInventoryItemId(1));
                LOGGER.info("In Dashboard");
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                FofoStore fofoStore = null;
                try {
                        fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
                }

                float sale = 0;
                if (roleManager.isAdmin(loginDetails.getRoleIds())) {
                        model.addAttribute("sale", sale);
                        List<NotificationData> notificationData = null;
                        long size = 0;

                        notificationData = notificationPanelRepository.selectAllNotificationData(offset, limit);
                        size = notificationPanelRepository.selectAllCount();
                        LOGGER.info("notification_data {}", notificationData);

                        LOGGER.info("notification_data {}", size);
                        // Map<String, Object> saleSummary=this.getAllSaleDetails(loginDetails);
                        // model.addAllAttributes(saleSummary);
                        if (!notificationData.isEmpty()) {

                                model.addAttribute("notificationData", notificationData);
                                LOGGER.info("notificationdata", notificationData);
                                model.addAttribute("start", offset + 1);
                                model.addAttribute("size", size);
                                model.addAttribute("url", "/getPaginatedNotificationData");

                                LOGGER.info("start {}", offset + 1);
                                LOGGER.info("SIZE {}", size);

                                if (notificationData.size() < limit) {
                                        model.addAttribute("end", offset + notificationData.size());
                                        LOGGER.info("SIZE2 {}", offset + notificationData.size());
                                } else {
                                        model.addAttribute("end", offset + limit);

                                        LOGGER.info("end {}", size);

                                }

                        } else {

                                model.addAttribute("notificationData", notificationData);
                                model.addAttribute("size", size);
                                LOGGER.info("sizeOriginal {}", size);

                        }
                } else if (roleManager.isPartner(loginDetails.getRoleIds())) {

                        List<NotificationData> notificationData = null;
                        long size = 0;

                        notificationData = notificationPanelRepository.selectAllNotificationDataByActiveFlag(offset, limit, true);
                        size = notificationPanelRepository.selectCountByActiveFlag(true);
                        LOGGER.info("notification_data {}", notificationData);

                        LOGGER.info("notification_data {}", size);

                        ///// DashBoard ......................///////
                        model.addAllAttributes(this.getAllInsuranceDetails(loginDetails.getFofoId()));
                        model.addAllAttributes(this.getAllRechargeDetails(loginDetails.getFofoId()));
                        model.addAllAttributes(this.getAllSaleDetails(loginDetails.getFofoId()));
                        model.addAttribute("fofoId", loginDetails.getFofoId());
                        ///////////////////////////////
                        if (!notificationData.isEmpty()) {

                                model.addAttribute("notificationData", notificationData);
                                LOGGER.info("notificationdata", notificationData);
                                model.addAttribute("start", offset + 1);
                                model.addAttribute("size", size);
                                model.addAttribute("url", "/getPaginatedNotificationData");

                                LOGGER.info("start {}", offset + 1);
                                LOGGER.info("SIZE {}", size);

                                if (notificationData.size() < limit) {
                                        model.addAttribute("end", offset + notificationData.size());
                                        LOGGER.info("SIZE2 {}", offset + notificationData.size());
                                } else {
                                        model.addAttribute("end", offset + limit);

                                        LOGGER.info("end {}", size);

                                }

                        } else {

                                model.addAttribute("notificationData", notificationData);
                                model.addAttribute("size", size);
                                LOGGER.info("sizeOriginal {}", size);

                        }
                }

                boolean isInvestmentOk = partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(), 10, 30);
                LocalDate endDate = LocalDate.now().minusDays(1);
                LocalDate weekStartDate = endDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                LocalDate startDate = weekStartDate.minusWeeks(2);
                List<PartnerDailyInvestment> partnerInvestments = new ArrayList<>();
                try {
                        partnerInvestments.add(partnerInvestmentService.getInvestment(loginDetails.getFofoId(), 1));
                        partnerInvestments
                                        .addAll(partnerDailyInvestmentRepository.selectAll(loginDetails.getFofoId(), startDate, endDate));

                } catch (Exception e) {
                        LOGGER.error("partner Investment can't exists");
                }
                Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(loginDetails.getFofoId());
                List<DBObject> mobileBrands = mongoClient.getMongoBrands(loginDetails.getFofoId(), loginDetails.getEmailId(), 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);
                        } else {
                        }
                });
                model.addAttribute("brandStockPrices", brandStockPrices.stream().sorted((x,y)-> y.getRank() - x.getRank()).collect(Collectors.toList()));
                model.addAttribute("isInvestmentOk", isInvestmentOk || roleManager.isAdmin(loginDetails.getRoleIds()));
                model.addAttribute("partnerInvestment", partnerInvestments.get(0));
                //model.addAttribute("investmentChart", this.getInvestmentChartData(partnerInvestments));
                model.addAttribute("fofoStore", fofoStore);
                model.addAttribute("walletAmount");
                model.addAttribute("appContextPath", request.getContextPath());
                model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
                model.addAttribute("webApiHost", webApiHost);
                model.addAttribute("webApiPort", webApiPort);
                model.addAttribute("webApiScheme", webApiScheme);
                model.addAttribute("webApiRoot", webApiRoot);
                model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
                model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
                model.addAttribute("sale", sale);

                // LOGGER.info("loginDetails.getFofoId()"+loginDetails.getFofoId());
                // inventoryService.prebookingAvailabilitySendMessage(loginDetails.getFofoId());
                return "dashboard";
        }

        private String getInvestmentChartData(List<PartnerDailyInvestment> partnerInvestments) {

                JSONObject scale = new JSONObject().put("scaleLabel", new JSONObject().put("scaleLabel", "Amount in Rs"));
                JSONObject titleObject = new JSONObject().put("display", true).put("text", "Investment Overview").put("display",
                                true);

                JSONObject barData = new JSONObject();

                JSONObject walletStack = new JSONObject().put("backgroundColor", "rgba(255, 99, 132, 0.2)")
                                .put("label", "Wallet").put("stack", "Stack1").put("data", new JSONArray());
                JSONObject inStockStack = new JSONObject().put("label", "In Stock")
                                .put("backgroundColor", "rgba(54, 162, 235, 0.2)").put("stack", "Stack1").put("data", new JSONArray());
                JSONObject salesStack = new JSONObject().put("backgroundColor", "rgba(255, 206, 86, 0.2)").put("label", "Sales")
                                .put("stack", "Stack1").put("data", new JSONArray());
                JSONObject grnPendingStack = new JSONObject().put("backgroundColor", "rgba(75, 192, 192, 0.2)")
                                .put("label", "Grn Pending").put("stack", "Stack1").put("data", new JSONArray());
                JSONObject billingPendingStack = new JSONObject().put("backgroundColor", "rgba(153, 102, 255, 0.2)")
                                .put("label", "Billing Pending").put("stack", "Stack1").put("data", new JSONArray());
                JSONObject inTransitStack = new JSONObject().put("backgroundColor", "rgba(255, 159, 64, 0.2)")
                                .put("label", "Returned").put("stack", "Stack1").put("data", new JSONArray());

                JSONObject minInvestmentDataSet = new JSONObject().put("label", "Min. Ivestment").put("data", new JSONArray())
                                .put("type", "line");
                JSONArray dateLabels = new JSONArray();

                for (PartnerDailyInvestment pdi : partnerInvestments) {
                        dateLabels = dateLabels.put(pdi.getDate().toString());
                        walletStack.getJSONArray("data").put((int) pdi.getWalletAmount());
                        inStockStack.getJSONArray("data").put((int) pdi.getInStockAmount());
                        salesStack.getJSONArray("data").put((int) pdi.getSalesAmount());
                        grnPendingStack.getJSONArray("data").put((int) pdi.getUnbilledAmount());
                        billingPendingStack.getJSONArray("data").put((int) pdi.getGrnPendingAmount());
                        inTransitStack.getJSONArray("data").put((int) pdi.getReturnInTransitAmount());
                        minInvestmentDataSet.getJSONArray("data").put((int) pdi.getMinInvestment());
                }

                JSONArray barDataSetsArray = new JSONArray().put(walletStack).put(inStockStack).put(salesStack)
                                .put(grnPendingStack).put(billingPendingStack).put(inTransitStack);
                barData.put("labels", dateLabels).put("datasets", barDataSetsArray);
                scale.put("yAxes", new JSONArray().put(new JSONObject().put("stacked", true))).put("xAxes",
                                new JSONArray().put(new JSONObject().put("stacked", true)));

                JSONObject barOptions = new JSONObject().put("title", titleObject).put("responsive", true).put("scales", scale)
                                .put("tooltips", new JSONObject().put("mode", "index").put("intersect", false));

                JSONObject chartJSOn = new JSONObject().put("type", "bar").put("data", barData).put("options", barOptions);
                return chartJSOn.toString();
        }

        // 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 = "/getPaginatedNotificationData", method = RequestMethod.GET)
        public String getPaginatedNotificationData(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                if (roleManager.isAdmin(loginDetails.getRoleIds())) {
                        List<NotificationData> notificationData = null;

                        notificationData = notificationPanelRepository.selectAllNotificationData(offset, limit);

                        LOGGER.info("notification_data {}", notificationData);

                        if (!notificationData.isEmpty()) {

                                model.addAttribute("notificationData", notificationData);
                                model.addAttribute("url", "/getPaginatedNotificationData");

                        } else {
                                model.addAttribute("notificationData", notificationData);

                        }
                } else if (roleManager.isPartner(loginDetails.getRoleIds())) {

                        List<NotificationData> notificationData = null;

                        notificationData = notificationPanelRepository.selectAllNotificationDataByActiveFlag(offset, limit, true);
                        LOGGER.info("notification_data {}", notificationData);

                        if (!notificationData.isEmpty()) {

                                model.addAttribute("notificationData", notificationData);
                                model.addAttribute("url", "/getPaginatedNotificationData");

                        } else {
                                model.addAttribute("notificationData", notificationData);

                        }
                }

                return "dashboard-paginated";
        }

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

        /*
         * private List<PaymentOption> getPaymentOptions(int fofoId){ List<Integer>
         * paymentOptionIds =
         * fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId) ;
         * if(paymentOptionIds.isEmpty()){ return new ArrayList<>(); } return
         * paymentOptionRepository.selectByIds(new HashSet<>(paymentOptionIds)); }
         */

        @RequestMapping(value = "/inactiveNotificationData", method = RequestMethod.POST)
        public String inactiveNotificationData(HttpServletRequest request,
                        @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {

                NotificationData notificationData = notificationPanelRepository.selectById(id);
                if (notificationData != null) {

                        notificationData.setActive(false);
                        LOGGER.info("notification" + notificationData);
                        notificationPanelRepository.persist(notificationData);

                        model.addAttribute("response", mvcResponseSender.createResponseString(true));
                } else {
                        model.addAttribute("response", mvcResponseSender.createResponseString(false));

                }
                return "response";
        }

        @RequestMapping(value = "/activeNotificationData", method = RequestMethod.POST)
        public String activeNotificationData(HttpServletRequest request,
                        @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {

                NotificationData notificationData = notificationPanelRepository.selectById(id);
                if (notificationData != null) {

                        notificationData.setActive(true);
                        notificationData.setCreated_timestamp(LocalDateTime.now());
                        LOGGER.info("notification" + notificationData);
                        notificationPanelRepository.persist(notificationData);

                        model.addAttribute("response", mvcResponseSender.createResponseString(true));
                } else {
                        model.addAttribute("response", mvcResponseSender.createResponseString(false));

                }
                return "response";
        }

        private Map<String, Object> getAllInsuranceDetails(int fofoId) {

                LocalDateTime currentDayStart = LocalDateTime.of(LocalDate.now(), LocalTime.of(00, 00));
                LocalDateTime previousDayStart = currentDayStart.minusDays(1);
                LocalDateTime currentDayEnd = LocalDateTime.now();
                LocalDateTime currentMonthDayStart = LocalDateTime
                                .of(LocalDate.of(currentDayStart.getYear(), currentDayStart.getMonth(), 01), LocalTime.of(00, 00));
                LocalDateTime previousDayEnd = currentDayStart.minusMinutes(1);
                LocalDateTime previousMonthFirstDay = currentMonthDayStart.minusMonths(1);
                LocalDateTime previousMonthLastDay = currentMonthDayStart.minusMinutes(1);

                List<String> insuranceProviders = insuranceProviderRepository.selectAll().stream().map(x -> x.getName())
                                .collect(Collectors.toList());

                Map<String, Object> map = new HashMap<>();
                List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
                                .selectByRetailerIdAndBetweenCreatedTimeStamp(fofoId, previousMonthFirstDay, LocalDateTime.now());

                Map<Integer, Double> currentMonthTotalInsurance = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(InsurancePolicy::getRetailerId,
                                                Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<Integer, Double> previousMonthTotalInsurance = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay))
                                .collect(Collectors.groupingBy(InsurancePolicy::getRetailerId,
                                                Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<Integer, Double> currentDayTotalInsurance = insurancePolicies.stream().filter(
                                x -> x.getCreateTimestamp().isAfter(currentDayStart) && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(InsurancePolicy::getRetailerId,
                                                Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<Integer, Double> previousDayTotalInsurance = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd))
                                .collect(Collectors.groupingBy(InsurancePolicy::getRetailerId,
                                                Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                IntFunction<String> intFunction = (providerId) -> {
                        try {
                                return insuranceProviderRepository.selectById(providerId).getName();
                        } catch (ProfitMandiBusinessException e1) {
                                // TODO Auto-generated catch block
                                return "";
                        }
                };
                Map<String, Double> currentMonthTotalInsuranceByPolicyName = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return intFunction.apply(x.getProviderId());
                                }, Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<String, Double> previousMonthTotalInsuranceByPolicyName = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay))
                                .collect(Collectors.groupingBy(x -> {
                                        return intFunction.apply(x.getProviderId());
                                }, Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<String, Double> previousDayTotalInsuranceByPolicyName = insurancePolicies.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return intFunction.apply(x.getProviderId());
                                }, Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                Map<String, Double> currentDayTotalInsuranceByPolicyName = insurancePolicies.stream().filter(
                                x -> x.getCreateTimestamp().isAfter(currentDayStart) && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return intFunction.apply(x.getProviderId());
                                }, Collectors.summingDouble(InsurancePolicy::getSellingPrice)));

                map.put("currentMonthTotalInsurance", currentMonthTotalInsurance);
                map.put("previousMonthTotalInsurance", previousMonthTotalInsurance);
                map.put("currentDayTotalInsurance", currentDayTotalInsurance);
                map.put("previousDayTotalInsurance", previousDayTotalInsurance);
                map.put("currentMonthTotalInsuranceByPolicyName", currentMonthTotalInsuranceByPolicyName);
                map.put("previousMonthTotalInsuranceByPolicyName", previousMonthTotalInsuranceByPolicyName);
                map.put("previousDayTotalInsuranceByPolicyName", previousDayTotalInsuranceByPolicyName);
                map.put("currentDayTotalInsuranceByPolicyName", currentDayTotalInsuranceByPolicyName);
                map.put("insuranceProviders", insuranceProviders);
                return map;
        }

        private Map<String, Object> getAllRechargeDetails(int fofoId) {

                LocalDateTime currentDayStart = LocalDateTime.of(LocalDate.now(), LocalTime.of(00, 00));
                LocalDateTime previousDayStart = currentDayStart.minusDays(1);
                LocalDateTime currentDayEnd = LocalDateTime.now();
                LocalDateTime currentMonthDayStart = LocalDateTime
                                .of(LocalDate.of(currentDayStart.getYear(), currentDayStart.getMonth(), 01), LocalTime.of(00, 00));
                LocalDateTime previousDayEnd = currentDayStart.minusMinutes(1);
                LocalDateTime previousMonthFirstDay = currentMonthDayStart.minusMonths(1);
                LocalDateTime previousMonthLastDay = currentMonthDayStart.minusMinutes(1);

                List<RechargeTransaction> rechargeTransactions = rechargeTransactionRepository
                                .getAllRechargeTransactionByCreatedTimeStamp(fofoId, previousMonthFirstDay, currentDayEnd).stream()
                                .filter(x -> x.getStatus().equals(RechargeStatus.SUCCESS)).collect(Collectors.toList());

                LOGGER.info(rechargeTransactions);
                Map<Integer, Double> currentMonthTotalRecharge = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(RechargeTransaction::getRetailerId,
                                                Collectors.summingDouble(RechargeTransaction::getAmount)));
                LOGGER.info(currentMonthTotalRecharge);
                Map<Integer, Double> previousMonthTotalRecharge = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay))
                                .collect(Collectors.groupingBy(RechargeTransaction::getRetailerId,
                                                Collectors.summingDouble(RechargeTransaction::getAmount)));

                LOGGER.info(previousMonthTotalRecharge);
                Map<Integer, Double> currentDayTotalRecharge = rechargeTransactions.stream().filter(
                                x -> x.getCreateTimestamp().isAfter(currentDayStart) && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(RechargeTransaction::getRetailerId,
                                                Collectors.summingDouble(RechargeTransaction::getAmount)));

                Map<Integer, Double> previousDayTotalRecharge = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd))
                                .collect(Collectors.groupingBy(RechargeTransaction::getRetailerId,
                                                Collectors.summingDouble(RechargeTransaction::getAmount)));

                Map<Object, Double> currentMonthTotalRechargeByRechargeType = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return x.getType();
                                }, Collectors.summingDouble(RechargeTransaction::getAmount)));

                Map<Object, Double> previosMonthTotalRechargeByRechargeType = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay))
                                .collect(Collectors.groupingBy(x -> {
                                        return x.getType();
                                }, Collectors.summingDouble(RechargeTransaction::getAmount)));

                Map<Object, Double> currentDayTotalRechargeByRechargeType = rechargeTransactions.stream().filter(
                                x -> x.getCreateTimestamp().isAfter(currentDayStart) && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return x.getType();
                                }, Collectors.summingDouble(RechargeTransaction::getAmount)));

                Map<Object, Double> previousDayTotalRechargeByRechargeType = rechargeTransactions.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd))
                                .collect(Collectors.groupingBy(x -> {
                                        return x.getType();
                                }, Collectors.summingDouble(RechargeTransaction::getAmount)));

                LOGGER.info("previosMonthTotalRechargeByRechargeType" + previosMonthTotalRechargeByRechargeType);
                Map<String, Object> map = new HashMap<>();
                map.put("currentMonthTotalRecharge", currentMonthTotalRecharge);
                map.put("previousMonthTotalRecharge", previousMonthTotalRecharge);
                map.put("currentDayTotalRecharge", currentDayTotalRecharge);
                map.put("previousDayTotalRecharge", previousDayTotalRecharge);
                map.put("currentMonthTotalRechargeByRechargeType", currentMonthTotalRechargeByRechargeType);
                map.put("previosMonthTotalRechargeByRechargeType", previosMonthTotalRechargeByRechargeType);
                map.put("currentDayTotalRechargeByRechargeType", currentDayTotalRechargeByRechargeType);
                map.put("previousDayTotalRechargeByRechargeType", previousDayTotalRechargeByRechargeType);
                map.put("rechargeTypes", RechargeType.values());

                return map;

        }

        private Map<String, Object> getAllSaleDetails(int fofoId) {

                LocalDateTime currentDayStart = LocalDateTime.of(LocalDate.now(), LocalTime.of(00, 00));
                LocalDateTime previousDayStart = currentDayStart.minusDays(1);
                LocalDateTime currentDayEnd = LocalDateTime.now();
                LocalDateTime currentMonthDayStart = LocalDateTime
                                .of(LocalDate.of(currentDayStart.getYear(), currentDayStart.getMonth(), 01), LocalTime.of(00, 00));
                LocalDateTime previousDayEnd = currentDayStart.minusMinutes(1);
                LocalDateTime previousMonthFirstDay = currentMonthDayStart.minusMonths(1);
                LocalDateTime previousMonthLastDay = currentMonthDayStart.minusMinutes(1);

                Map<String, Object> map = new HashMap<>();

                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectBetweenCreatedTime(fofoId,
                                previousMonthFirstDay, currentDayEnd);
                
                Double currentMonthTotalSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                LOGGER.info("currentMonthTotalSale" + currentMonthTotalSale);
                Double previousMonthTotalSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double currentDayTotalSale = fofoOrderItems.stream().filter(
                                x -> x.getCreateTimestamp().isAfter(currentDayStart) && x.getCreateTimestamp().isBefore(currentDayEnd))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                LOGGER.info(currentDayTotalSale);

                Double previousDayTotalSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));
                LOGGER.info(previousDayTotalSale);
                IntPredicate checkHandset = (itemId) -> {
                        try {
                                Item item = itemRepository.selectById(itemId);
                                return item.getCategoryId() == 10006;
                        } catch (ProfitMandiBusinessException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                return false;
                        }
                };

                Set<String> brands = fofoOrderItemRepository
                                .selectBetweenDates(previousMonthFirstDay.minusMonths(1), currentDayEnd).stream()
                                .filter(x -> checkHandset.test(x.getItemId())).map(x -> x.getBrand()).collect(Collectors.toSet());
                Set<String> accessories = fofoOrderItemRepository
                                .selectBetweenDates(previousMonthFirstDay.minusMonths(1), currentDayEnd).stream()
                                .filter(x -> !checkHandset.test(x.getItemId())).map(x -> x.getBrand()).collect(Collectors.toSet());

                Double currentMonthTotalMobileSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double previousMonthTotalMobileSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double previousDayTotalMobileSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double currentDayTotalMobileSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double currentMonthTotalAccessoriesSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double previousMonthTotalAccessoriesSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double previousDayTotalAccessoriesSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Double currentDayTotalAccessoriesSale = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity()));

                Map<String, Double> currentMonthMobileSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> currentMonthAccesoriesSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentMonthDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> previousMonthAccesoriesSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> currentDayAccesoriesSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> previousDayAccesoriesSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd) && !checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> currentDayMobileSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(currentDayStart)
                                                && x.getCreateTimestamp().isBefore(currentDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));

                Map<String, Double> previousDayMobileSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousDayStart)
                                                && x.getCreateTimestamp().isBefore(previousDayEnd) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));
                Map<String, Double> previousMonthMobileSalegroupByBrand = fofoOrderItems.stream()
                                .filter(x -> x.getCreateTimestamp().isAfter(previousMonthFirstDay)
                                                && x.getCreateTimestamp().isBefore(previousMonthLastDay) && checkHandset.test(x.getItemId()))
                                .collect(Collectors.groupingBy(x -> x.getBrand(),
                                                Collectors.summingDouble(x -> x.getSellingPrice() * x.getQuantity())));
                
                map.put("brands", brands);
                map.put("accessories", accessories);
                map.put("currentMonthTotalSale", currentMonthTotalSale);
                map.put("previousMonthTotalSale", previousMonthTotalSale);
                map.put("currentDayTotalSale", currentDayTotalSale);
                map.put("previousDayTotalSale", previousDayTotalSale);
                map.put("currentMonthMobileSalegroupByBrand", currentMonthMobileSalegroupByBrand);
                map.put("currentMonthAccesoriesSalegroupByBrand", currentMonthAccesoriesSalegroupByBrand);
                map.put("previousMonthAccesoriesSalegroupByBrand", previousMonthAccesoriesSalegroupByBrand);
                map.put("previousDayAccesoriesSalegroupByBrand", previousDayAccesoriesSalegroupByBrand);
                map.put("currentDayMobileSalegroupByBrand", currentDayMobileSalegroupByBrand);
                map.put("previousDayMobileSalegroupByBrand", previousDayMobileSalegroupByBrand);
                map.put("currentDayAccesoriesSalegroupByBrand", currentDayAccesoriesSalegroupByBrand);
                map.put("previousMonthMobileSalegroupByBrand", previousMonthMobileSalegroupByBrand);

                map.put("currentMonthTotalMobileSale", currentMonthTotalMobileSale);
                map.put("previousMonthTotalMobileSale", previousMonthTotalMobileSale);
                map.put("previousDayTotalMobileSale", previousDayTotalMobileSale);
                map.put("currentDayTotalMobileSale", currentDayTotalMobileSale);
                map.put("currentMonthTotalAccessoriesSale", currentMonthTotalAccessoriesSale);
                map.put("previousMonthTotalAccessoriesSale", previousMonthTotalAccessoriesSale);
                map.put("previousDayTotalAccessoriesSale", previousDayTotalAccessoriesSale);
                map.put("currentDayTotalAccessoriesSale", currentDayTotalAccessoriesSale);

                return map;
        }
}