Subversion Repositories SmartDukaan

Rev

Rev 24387 | Rev 24996 | 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.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.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.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.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.transaction.OrderRepository;
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.service.wallet.WalletService;
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 RoleManager roleManager;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private WalletService walletService;

        @Autowired
        private InventoryService inventoryService;


        @Autowired
        private OrderRepository orderRepository;


        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
        
        @Autowired
        private PartnerInvestmentService partnerInvestmentService;

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

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

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

}