Subversion Repositories SmartDukaan

Rev

Rev 24271 | Rev 24312 | 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.LocalDateTime;
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.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.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;

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

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

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

}