Subversion Repositories SmartDukaan

Rev

Rev 24312 | Rev 24321 | 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.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.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.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.dao.entity.dtr.NotificationData;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.NotificationPanelRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
import com.spice.profitmandi.dao.repository.fofo.PurchaseReturnItemRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.slab.TargetSlabService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.wallet.WalletService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

import be.ceau.chart.BarChart;
import be.ceau.chart.color.Color;
import be.ceau.chart.data.BarData;
import be.ceau.chart.dataset.BarDataset;
import be.ceau.chart.options.BarOptions;
import be.ceau.chart.options.Title;
import be.ceau.chart.options.scales.BarScale;
import be.ceau.chart.options.scales.XAxis;
import be.ceau.chart.options.scales.YAxis;
import be.ceau.chart.options.ticks.LinearTicks;

@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 RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private WalletService walletService;

        @Autowired
        private InventoryService inventoryService;

        @Autowired
        private TargetSlabService targetSlabService;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private PurchaseReturnItemRepository purchaseReturnItemRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        /*
         * @Autowired private ScanRepository scanRepository;
         */

        @Autowired
        private TransactionService transactionService;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private NotificationPanelRepository notificationPanelRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        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 walletAmount = 0;
                float inStockAmount = 0;
                float unbilledStockAmount = 0;
                float grnPendingStockAmount = 0;
                float shortPercentage = 100;
                float totalInvestedAmount = 0;
                float minimumInvestment = 0;
                float returnedStockInTransit = 0;
                float sale = 0;
                if (roleManager.isAdmin(loginDetails.getRoleIds())) {
                        model.addAttribute("showAlert", false);
                        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);

                        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())) {
                        walletAmount = walletService.getUserWallet(loginDetails.getFofoId()).getAmount();
                        inStockAmount = inventoryService.getTotalAmountInStock(loginDetails.getFofoId());

                        List<Order> unbilledOrders = transactionService.getInTransitOrders(loginDetails.getFofoId());
                        for (Order unBilledOrder : unbilledOrders) {
                                unbilledStockAmount += unBilledOrder.getTotalAmount();
                        }

                        List<Order> grnPendingOrders = orderRepository.selectPendingGrnOrders(loginDetails.getFofoId());
                        for (Order grnPendingOrder : grnPendingOrders) {
                                grnPendingStockAmount += grnPendingOrder.getTotalAmount();
                        }
                        totalInvestedAmount = walletAmount + inStockAmount + unbilledStockAmount + grnPendingStockAmount + sale;
                        shortPercentage = ((fofoStore.getMinimumInvestment() - totalInvestedAmount)
                                        / fofoStore.getMinimumInvestment()) * 100;
                        model.addAttribute("showAlert", shortPercentage > 10);
                        minimumInvestment = fofoStore.getMinimumInvestment();

                        // debitNoteRepository.se
                        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);

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

                        }
                }
                LocalDate endDate = LocalDate.now().minusDays(1);
                LocalDate weekStartDate = endDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                LocalDate startDate = weekStartDate.minusWeeks(5);
                List<PartnerDailyInvestment> partnerInvestments = partnerDailyInvestmentRepository
                                .selectAll(loginDetails.getFofoId(), startDate, endDate);

                model.addAttribute("investmentChart", this.getInvestmentChartData(partnerInvestments));
                model.addAttribute("sale", sale);
                model.addAttribute("walletAmount", walletAmount);
                model.addAttribute("inStockAmount", inStockAmount);
                model.addAttribute("unbilledStockAmount", unbilledStockAmount);
                model.addAttribute("grnPendingStockAmount", grnPendingStockAmount);
                model.addAttribute("shortPercentage", shortPercentage);
                model.addAttribute("totalInvestedAmount", totalInvestedAmount);
                model.addAttribute("minimumInvestmentAmount", minimumInvestment);
                model.addAttribute("returnedStockInTransit", returnedStockInTransit);

                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) {

                List<List<Integer>> walletStackList = new ArrayList<>();
                List<List<Integer>> inStockStackList = new ArrayList<>();
                List<List<Integer>> salesStackList = new ArrayList<>();
                List<List<Integer>> grnPendingStackList = new ArrayList<>();
                List<List<Integer>> billingPendingStackList = new ArrayList<>();
                List<List<Integer>> inTransitStackList = new ArrayList<>();
                List<List<LocalDate>> datesList = new ArrayList<>();

                int currentWeekOfYear = 0;
                List<Integer> walletStack = null;
                List<Integer> inStockStack = null;
                List<Integer> salesStack = null;
                List<Integer> grnPendingStack = null;
                List<Integer> billingPendingStack = null;
                List<Integer> inTransitStack = null;
                List<LocalDate> dates = null;
                for (PartnerDailyInvestment pdi : partnerInvestments) {
                        int weekOfYear = pdi.getDate().get(WeekFields.ISO.weekOfYear());
                        if (weekOfYear != currentWeekOfYear) {
                                walletStack = new ArrayList<>();
                                inStockStack = new ArrayList<>();
                                salesStack = new ArrayList<>();
                                grnPendingStack = new ArrayList<>();
                                billingPendingStack = new ArrayList<>();
                                inTransitStack = new ArrayList<>();
                                dates = new ArrayList<>();
                                currentWeekOfYear = weekOfYear;
                                walletStackList.add(walletStack);
                                inStockStackList.add(inStockStack);
                                salesStackList.add(salesStack);
                                grnPendingStackList.add(grnPendingStack);
                                billingPendingStackList.add(billingPendingStack);
                                inTransitStackList.add(inTransitStack);
                        }
                        walletStack.add((int)pdi.getWalletAmount());
                        inStockStack.add((int)pdi.getInStockAmount());
                        salesStack.add((int)pdi.getSalesAmount());
                        grnPendingStack.add((int)pdi.getGrnPendingAmount());
                        billingPendingStack.add((int)pdi.getUnbilledAmount());
                        inTransitStack.add((int)pdi.getReturnInTransitAmount());
                        datesList.add(dates);
                        
                }
                
                int counter = 0;
                BarData barData = new BarData();
                while(counter < walletStackList.size()) {
                        barData
                        .addDataset(new BarDataset().setData(walletStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("Wallet").addBackgroundColor(Color.BLUE))
                        .addDataset(new BarDataset().setData(inStockStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("In Stock").addBackgroundColor(Color.LIGHT_BLUE))
                        .addDataset(new BarDataset().setData(salesStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("Sales").addBackgroundColor(Color.YELLOW))
                        .addDataset(new BarDataset().setData(grnPendingStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("Grn Pending").addBackgroundColor(Color.LIGHT_YELLOW))
                        .addDataset(new BarDataset().setData(billingPendingStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("Billing Pending").addBackgroundColor(Color.GREEN))
                        .addDataset(new BarDataset().setData(inTransitStackList.get(counter).stream().mapToInt(i -> i).toArray()).setLabel("In Transit").addBackgroundColor(Color.GREEN_YELLOW));
                        counter++;
                }
                BarOptions barOptions = new BarOptions()
                                .setTitle(new Title().setDisplay(true).setText("Daily Investment Summary"))
                                .setResponsive(true)
                                
                                .setScales(new BarScale().addxAxes(new XAxis<LinearTicks>().setStacked(true))
                                                                                 .addyAxes(new YAxis<LinearTicks>().setStacked(true))
                                                                                 );
                                                
                BarChart barChart = new BarChart(barData, barOptions);
                return barChart.toJson();
        }

        // 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);

                FofoStore fofoStore = null;
                try {
                        fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
                }
                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";
        }

}