Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
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.enumuration.CounterSize;
import com.spice.profitmandi.common.enumuration.IndentStatus;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BrandPerformance;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.ItemIdAvailability;
import com.spice.profitmandi.common.model.ItemIdQuantity;
import com.spice.profitmandi.common.model.ItemIdQuantityAvailability;
import com.spice.profitmandi.common.model.StockAllocationModel;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.IndentItem;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.IndentItemRepository;
import com.spice.profitmandi.dao.repository.dtr.IndentRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.service.inventory.StockAllocationService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import com.spice.profitmandi.web.util.RoleManager;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class IndentController {

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

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private IndentRepository indentRepository;

        @Autowired
        private StockAllocationService stockAllocationService;

        @Autowired
        private IndentItemRepository indentItemRepository;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private TagListingRepository tagListingRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        RoleManager roleManager;

        @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
        public String saveOpenIndent(HttpServletRequest request, Model model,
                        @RequestBody List<StockAllocationModel> stockAllocationModelList, @RequestParam int fofoId,
                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                boolean response = false;
                if (fofoId > 0) {
                        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
                        stockAllocationModelList.forEach(x -> {
                                x.setFofoId(fofoId);
                                x.setCounterSize(fs.getCounterSize());
                        });
                } else {
                        stockAllocationModelList.forEach(x -> {
                                x.setFofoId(fofoId);
                                x.setCounterSize(counterSize);
                        });
                }
                if (roleManager.isAdmin(loginDetails.getRoleIds())) {
                        response = stockAllocationService.addToAllocation(stockAllocationModelList);
                        model.addAttribute("response", mvcResponseSender.createResponseString(response));
                }
                return "response";
        }

        @RequestMapping(value = "/migrate", method = RequestMethod.PUT)
        public String migrate(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                List<TagListing> tagListings = tagListingRepository.selectAll();
                for (TagListing tagListing : tagListings) {
                        int itemId = tagListing.getItemId();
                }
                return "";
        }

        @RequestMapping(value = "/indent/inProcess")
        public String loadInProcessIndents(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();

                List<Integer> pendingIndentIds = indentRepository.selectIndentByStatus(fofoId, IndentStatus.PENDING).stream()
                                .map(x -> x.getId()).collect(Collectors.toList());
                List<Integer> allocatedIndentIds = indentRepository.selectIndentByStatus(fofoId, IndentStatus.ALLOCATED)
                                .stream().map(x -> x.getId()).collect(Collectors.toList());
                pendingIndentIds.addAll(allocatedIndentIds);

                if (pendingIndentIds.size() > 0) {
                        Map<Integer, IndentItem> pendingIndentItemIdMap = indentItemRepository.selectIndentItems(pendingIndentIds)
                                        .stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                        List<TagListing> tagListings = tagListingRepository
                                        .selectByItemIdsAndTagIds(pendingIndentItemIdMap.keySet(), new HashSet<>(Arrays.asList(4)));

                        List<FofoOrderItem> fofoOrderItems = fofoOrderRepository.selectByFofoItemIds(fofoId, pendingIndentIds,
                                        LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(30), LocalDateTime.now());
                        Map<Integer, Integer> itemQuantity = fofoOrderItems.stream().collect(
                                        Collectors.groupingBy(FofoOrderItem::getItemId, Collectors.summingInt(FofoOrderItem::getQuantity)));

                        List<CurrentInventorySnapshot> cis = currentInventorySnapshotRepository.selectByFofoId(fofoId);
                        Map<Integer, CurrentInventorySnapshot> itemIdSnapshotMap = cis.stream()
                                        .collect(Collectors.toMap(x -> x.getItemId(), x -> x));

                        for (TagListing tagListing : tagListings) {
                                Integer itemId = tagListing.getItemId();
                                tagListing.setItemDescription(itemRepository.selectById(itemId).getItemDescription());
                                if (itemQuantity.containsKey(itemId)) {
                                        tagListing.setLast30DaysSale(itemQuantity.get(itemId));
                                }
                                if (itemIdSnapshotMap.containsKey(itemId)) {
                                        tagListing.setStockInHand(itemIdSnapshotMap.get(itemId).getAvailability());
                                }
                        }

                        model.addAttribute("pendingIndentItemIdMap", pendingIndentItemIdMap);
                        model.addAttribute("tagListings", tagListings);
                }
                return "pending-indent";
        }

        @RequestMapping(value = "/indent/loadIndent")
        public String loadOpenIndent(HttpServletRequest request, Model model,
                        @RequestParam(required = false, defaultValue = "0") int fofoId,
                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws ProfitMandiBusinessException {
                Set<Integer> roleIds = cookiesProcessor.getCookiesObject(request).getRoleIds();
                LOGGER.info("Counter size is {}", counterSize);
                LOGGER.info("Fofo Id is {}", fofoId);

                Map<Integer, ItemIdAvailability> itemCisMap = null;
                if (!roleManager.isAdmin(roleIds)) {
                        fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
                        List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository.selectItemsStock(fofoId);
                        itemCisMap = currentInventorySnapshots.stream().filter(x->x.getAvailability()>0).collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                } else {
                        if (fofoId == 0) {
                                List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository.selectItemsStock();
                                itemCisMap = currentInventorySnapshots.stream().filter(x->x.getAvailability()>0).collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                        } else {
                                List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository.selectItemsStock(fofoId);
                                itemCisMap = currentInventorySnapshots.stream().filter(x->x.getAvailability()>0).collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                        }
                }
                List<BrandPerformance> brandPerformanceList = new ArrayList<>();
                List<BrandPerformance> accsBrandPerformanceList = new ArrayList<>();
                List<StockAllocationModel> stockAllocationList;
                if (fofoId > 0) {
                        stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
                } else {
                        stockAllocationList = stockAllocationService.getStockAllocation(counterSize, true);
                }
                LOGGER.info("Stock Allocation list  is {}", stockAllocationList);

                Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));

                LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
                List<TagListing> tagListings = tagListingRepository.selectAll();
                if(!roleManager.isAdmin(roleIds)) {
                        tagListings = new ArrayList<>(tagListings);
                }
                Iterator<TagListing> iterator = tagListings.iterator();
                while (iterator.hasNext()) {
                        TagListing tagListing = iterator.next();
                        LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
                        Item item = itemRepository.selectById(tagListing.getItemId());
                        if (roleManager.isAdmin(roleIds)) {
                                if (item.getBrand() == null || item.getCategoryId() == 0) {
                                        iterator.remove();
                                        continue;
                                }
                        } else {
                                if(!itemCisMap.containsKey(tagListing.getItemId()) && itemStockAllocationMap.containsKey(tagListing.getItemId())) {
                                        iterator.remove();
                                        continue;
                                }
                        }
                        StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
                        LOGGER.info(" stockAllocationModel {}", stockAllocationModel);
                        LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
                        if (stockAllocationModel != null) {
                                tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
                        } else {
                                tagListing.setAllocatedQuantity(0);
                        }
                        tagListing.setBrand(item.getBrand());
                        tagListing.setItemDescription(item.getItemDescription());
                        if (item.getCategoryId() == 10006) {
                                tagListing.setCategoryId(item.getCategoryId());
                        }
                        LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
                }

                Map<Integer, List<TagListing>> performanceMap = tagListings.stream()
                                .collect(Collectors.groupingBy(x -> x.getCategoryId()));
                List<TagListing> accsListing = performanceMap.get(0);
                List<TagListing> mobileListing = performanceMap.get(10006);

                Map<String, DoubleSummaryStatistics> accsStats = accsListing.stream().collect(Collectors.groupingBy(
                                x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));
                Map<String, DoubleSummaryStatistics> mobStats = mobileListing.stream().collect(Collectors.groupingBy(
                                x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));

                for (Map.Entry<String, DoubleSummaryStatistics> entry : mobStats.entrySet()) {
                        DoubleSummaryStatistics dss = entry.getValue();
                        BrandPerformance bp = new BrandPerformance();
                        bp.setTarget((float) dss.getSum());
                        bp.setBrandName(entry.getKey());
                        brandPerformanceList.add(bp);
                }
                for (Map.Entry<String, DoubleSummaryStatistics> entry : accsStats.entrySet()) {
                        DoubleSummaryStatistics dss = entry.getValue();
                        BrandPerformance bp = new BrandPerformance();
                        bp.setTarget((float) dss.getSum());
                        bp.setBrandName(entry.getKey());
                        accsBrandPerformanceList.add(bp);
                }
                brandPerformanceList = brandPerformanceList.stream().filter(x -> x.getTarget() > 0)
                                .sorted((BrandPerformance o1, BrandPerformance o2) -> (int) (o1.getTarget() - o2.getTarget()))
                                .collect(Collectors.toList());
                accsBrandPerformanceList = accsBrandPerformanceList.stream().filter(x -> x.getTarget() > 0)
                                .sorted((BrandPerformance o1, BrandPerformance o2) -> (int) (o1.getTarget() - o2.getTarget()))
                                .collect(Collectors.toList());

                List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
                                .collect(Collectors.toList());
                model.addAttribute("tagListings", tagListings);
                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
                if (fofoId > 0) {
                        CustomRetailer customRetailer = customRetailersMap.get(fofoId);
                        model.addAttribute("retailerName",
                                        customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
                        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
                        model.addAttribute("retailerId", customRetailer.getPartnerId());
                        model.addAttribute("counterSize", fs.getCounterSize().toString());
                } else {
                        model.addAttribute("counterSize", counterSize.toString());
                }
                String customRetailers = JSONObject.valueToString(customRetailersMap.values());
                LOGGER.info("Custom retailers {}", customRetailers);
                model.addAttribute("customRetailers", customRetailers);
                model.addAttribute("brandPerformanceList", brandPerformanceList);
                model.addAttribute("accsBrandPerformanceList", accsBrandPerformanceList);
                model.addAttribute("counterSizes", CounterSize.values());
                model.addAttribute("itemCisMap", itemCisMap);
                return "open-indent";
        }
}