Subversion Repositories SmartDukaan

Rev

Rev 31663 | Rev 32170 | 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 com.mongodb.DBObject;
import com.spice.profitmandi.common.enumuration.ActivationType;
import com.spice.profitmandi.common.enumuration.CounterSize;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.*;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.common.util.Utils.Attachment;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.catalog.Category;
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.cs.Region;
import com.spice.profitmandi.dao.entity.fofo.*;
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
import com.spice.profitmandi.dao.entity.user.User;
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.model.FofoReportingModel;
import com.spice.profitmandi.dao.model.InStockAccessoriesTvFofoIdModel;
import com.spice.profitmandi.dao.model.InStockBrandFofoIdModel;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.cs.*;
import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.fofo.*;
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
import com.spice.profitmandi.dao.repository.user.UserRepository;
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
import com.spice.profitmandi.service.NotificationService;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
import com.spice.profitmandi.service.inventory.StockAllocationService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.wallet.WalletService;
import com.spice.profitmandi.thrift.clients.PaymentClient;
import com.spice.profitmandi.thrift.clients.TransactionClient;
import com.spice.profitmandi.thrift.clients.UserClient;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import in.shop2020.logistics.PickUpType;
import in.shop2020.model.v1.order.*;
import in.shop2020.model.v1.user.ItemPriceQuantity;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.model.v1.user.UserContextService.Client;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.thrift.TException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
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 javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

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

        private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
        private static final int WALLET_GATEWAY_ID = 8;
        private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));

        private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
                        OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
                        OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
                        OrderStatus.REACHED_DESTINATION_CITY);

        private static final int PLANNING_OPEN_DAY = 20;
        private static final int PLANNING_CLOSE_DAY = 1;

        private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";

        @Autowired
        WalletService walletService;

        @Autowired
        BrandRegionMappingRepository brandRegionMappingRepository;

        @Autowired
        private JavaMailSender googleMailSender;

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private UserWalletRepository userWalletRepository;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private StockAllocationService stockAllocationService;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private TagListingRepository tagListingRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private PurchaseRepository purchaseRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private FocusedModelRepository focusedModelRepository;

        @Autowired
        private MonthlyPlannedRepository monthlyPlannedRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;

        @Autowired
        private PlannedDetailRepository plannedDetailRepository;

        @Autowired
        RoleManager roleManager;

        @Autowired
        PartnerTypeChangeRepository partnerTypeChangeRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private InventoryService inventoryService;

        @Autowired
        private CsService1 csService1;

        @Autowired
        private CsService csService;

        @Autowired
        private AuthRepository authRepository;
        @Autowired
        WarehouseRepository warehouseRepository;
        @Autowired
        private SuggestedPoRepository suggestedPoRepository;

        @Autowired
        private NotificationService notificationService;

        @Autowired
        private RegionRepository regionRepository;

        @Autowired
        private PartnerRegionRepository partnerRegionRepository;

        @Autowired
        private SaholicInventoryCISRepository saholicInventoryCISRepository;

        @Autowired
        private SaholicInventoryService saholicInventoryService;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
        @Autowired
        private SuggestedPoDetailRepository suggestedPoDetailRepository;

        @Autowired
        SaholicCISTableRepository saholicCISTableRepository;

        @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
        public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
                        @RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
                if (fofoId == 0) {

                        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                        fofoId = loginDetails.getFofoId();

                }

                LocalDate currentMonthDate = LocalDate.now();
                MonthlyPlanned monthlyPlanned = null;

                if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
                        currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
                        LOGGER.info("monthlyPlanned" + monthlyPlanned);
                        saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
                }
                model.addAttribute("response1", mvcResponseSender.createResponseString(false));
                return "response";
        }

        private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
                        int catalogId, int itemQty) {
                if (monthlyPlanned == null) {
                        monthlyPlanned = new MonthlyPlanned();
                        monthlyPlanned.setFofoId(fofoId);
                        monthlyPlanned.setYearMonth(currentMonthDate);
                        monthlyPlannedRepository.persist(monthlyPlanned);
                        PlannedDetail pd = new PlannedDetail();
                        pd.setCatalogId(catalogId);
                        pd.setPlannedId(monthlyPlanned.getId());
                        pd.setQuantity(itemQty);
                        pd.setUpdatedTimestamp(LocalDateTime.now());
                        plannedDetailRepository.persist(pd);

                } else {
                        PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
                                        catalogId);
                        if (plannedDetail == null) {
                                plannedDetail = new PlannedDetail();
                                plannedDetail.setCatalogId(catalogId);
                                plannedDetail.setPlannedId(monthlyPlanned.getId());
                                plannedDetail.setQuantity(itemQty);
                                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
                                plannedDetailRepository.persist(plannedDetail);
                        } else if (itemQty == 0) {
                                plannedDetailRepository.delete(plannedDetail);

                        } else {
                                plannedDetail.setCatalogId(catalogId);
                                plannedDetail.setQuantity(itemQty);
                                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
                        }

                }

        }

        @RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
        public String confirmOpenIndent(HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {

                if (fofoId == 0) {
                        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                        fofoId = loginDetails.getFofoId();
                }
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);

                LocalDate currentDate = LocalDate.now();
                LocalDate planningMonthDate = null;
                MonthlyPlanned monthlyPlanned = null;
                if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
                        planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);

                        confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
                }
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));

                return "response";
        }

        private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
                        throws Exception {
                List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());

                List<PlannedModel> plannedModel = new ArrayList<>();
                for (PlannedDetail plannedDetail : plannedDetails) {

                        List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
                        String itemDesription = items.get(0).getItemDescriptionNoColor();
                        PlannedModel pm = new PlannedModel();
                        pm.setItemDescription(itemDesription);
                        pm.setStoreName(customRetailer.getBusinessName());
                        pm.setQty(plannedDetail.getQuantity());
                        pm.setFofoId(fofoId);
                        plannedModel.add(pm);
                        LOGGER.info("plannedModel" + plannedModel);

                }
                List<String> ccemails = new ArrayList<>();
                LOGGER.info("ccemails" + ccemails);
                Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
                LOGGER.info("emailEsclationType" + emailEsclationType);
                if (emailEsclationType.get(EscalationType.L1) != null) {
                        ccemails.add(emailEsclationType.get(EscalationType.L1));
                }

                if (emailEsclationType.get(EscalationType.L2) != null) {

                        ccemails.add(emailEsclationType.get(EscalationType.L2));
                }
                LOGGER.info("ccemails" + ccemails);
                List<String> bccemails = new ArrayList<>();
                bccemails.add(emailEsclationType.get(EscalationType.L3));
                LOGGER.info("bccemails" + bccemails);
                ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
                                Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
                                plannedModel.stream()
                                                .map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
                                                .collect(Collectors.toList()));
                LOGGER.info("baos" + baos);
                Utils.sendMailWithAttachments(googleMailSender, new String[] { customRetailer.getEmail() },
                                ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
                                "Planned Indent", "PFA",
                                new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });

        }

        @RequestMapping(value = "/indent/download", method = RequestMethod.GET)
        public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
                        @RequestParam(required = false, defaultValue = "0") int fofoId,
                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Set<Integer> roleIds = loginDetails.getRoleIds();
                LOGGER.info("Counter size is {}", counterSize);
                LOGGER.info("Fofo Id is {}", fofoId);

                if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
                        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
                                        .collect(Collectors.toList());
                        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                        Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x))
                                        .filter(x -> x != null).collect(Collectors.toList()).stream()
                                        .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                        List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
                                        true);
                        Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
                                        .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));

                        Map<String, Integer> catalogUserQtyMap = new HashMap<>();
                        currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
                                int retailerId = x.getFofoId();
                                int catalogId;
                                try {
                                        catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
                                        String key = catalogId + "-" + retailerId;
                                        if (!catalogUserQtyMap.containsKey(key)) {
                                                catalogUserQtyMap.put(key, 0);
                                        }
                                        catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
                                } catch (ProfitMandiBusinessException e) {
                                        // TODO Auto-generated catch block
                                        throw new RuntimeException(e);
                                }
                        });

                        List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
                        Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
                                try {
                                        return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
                                                        + x.getRetailerId();
                                } catch (ProfitMandiBusinessException e) {
                                        // TODO Auto-generated catch block
                                        return "";
                                }
                        }, Collectors.summingInt(x -> x.getLineItem().getQuantity())));

                        Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();

                        List<TagListing> tagListings = tagListingRepository.selectAll(true);
                        Iterator<TagListing> iterator = tagListings.iterator();
                        while (iterator.hasNext()) {
                                TagListing tagListing = iterator.next();
                                Item item = itemRepository.selectById(tagListing.getItemId());
                                int catalogId = item.getCatalogItemId();
                                if (item.getCategoryId() != 10006) {
                                        continue;
                                }

                                int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
                                                ? modelStockAllocationMap.get(catalogId)
                                                : 0;
                                for (int retailerId : fofoIds) {
                                        String key = catalogId + "-" + retailerId;
                                        if (catalogListingMap.containsKey(key)) {
                                                continue;
                                        }
                                        int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
                                        int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
                                        if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
                                                continue;
                                        }
                                        CatalogListingModel catalogListingModel = new CatalogListingModel();
                                        catalogListingModel.setFofoId(retailerId);
                                        catalogListingModel.setModelName(item.getModelName());
                                        catalogListingModel.setModelNumber(item.getModelNumber());
                                        catalogListingModel.setCatalogId(catalogId);
                                        catalogListingModel.setDp(tagListing.getSellingPrice());
                                        catalogListingModel.setMop(tagListing.getMop());
                                        catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
                                        catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
                                        catalogListingModel.setInTransitQuantity(catalogInTransit);
                                        catalogListingModel
                                                        .setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
                                        catalogListingModel.setStockInHand(catalogInStock);
                                        catalogListingModel.setBrand(item.getBrand());
                                        catalogListingModel.setModelName(item.getModelName());
                                        catalogListingModel.setModelNumber(item.getModelNumber());
                                        catalogListingModel.setCategoryId(item.getCategoryId());
                                        catalogListingMap.put(key, catalogListingModel);
                                }
                        }
                        List<List<?>> listOfRows = new ArrayList<>();
                        for (CatalogListingModel clm : catalogListingMap.values()) {
                                CustomRetailer cr = crm.get(clm.getFofoId());
                                listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
                                                clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
                                                clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
                                                clm.getToBeOrdered()));
                        }
                        ByteArrayOutputStream baos = FileUtil
                                        .getCSVByteStream(
                                                        Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
                                                                        "DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
                                                        listOfRows);
                        HttpHeaders headers = new HttpHeaders();
                        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
                        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
                                        HttpStatus.OK);
                }
                return null;

        }

        @RequestMapping(value = "/itemsByCatalogId")
        public String getItemsByCatalogId(HttpServletRequest request, Model model,
                        @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
                        throws ProfitMandiBusinessException {
                if (catalogId == 0) {
                        catalogId = itemRepository.selectById(itemId).getCatalogItemId();
                }
                List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
                LOGGER.info("Items {}", items);
                Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
                                .collect(Collectors.toMap(Item::getId, Item::getColor));
                Map<Integer, TagListing> tagsMap = tagListingRepository
                                .selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
                                .stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
                LOGGER.info("Items color map {}", itemsColorMap);
                JSONArray response = new JSONArray();
                itemsColorMap.keySet().stream().forEach(x -> {
                        response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
                                        tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
                });
                model.addAttribute("response1", response.toString());
                return "response";

        }

        @RequestMapping(value = "/hotdealsitemsByCatalogId")
        public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,
                        @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
                        throws ProfitMandiBusinessException {
                if (catalogId == 0) {
                        catalogId = itemRepository.selectById(itemId).getCatalogItemId();
                }
                List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
                LOGGER.info("Items {}", items);
                Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
                                .collect(Collectors.toMap(Item::getId, Item::getColor));
                Map<Integer, TagListing> tagsMap = tagListingRepository
                                .selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
                                .stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
                LOGGER.info("Items color map {}", itemsColorMap);
                JSONArray response = new JSONArray();
                itemsColorMap.keySet().stream().forEach(x -> {
                        response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",
                                        tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));
                });
                model.addAttribute("response1", response.toString());
                return "response";

        }

        private List<Order> filterValidOrders(List<Order> lastOrdersList) {
                int orderRemovedCount = 0;
                Iterator<Order> orderIterator = lastOrdersList.iterator();
                while (orderIterator.hasNext()) {
                        Order o = orderIterator.next();
                        if (o.getInvoiceNumber() != null) {
                                try {
                                        purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
                                        orderIterator.remove();
                                        orderRemovedCount++;
                                } catch (Exception e) {

                                }
                        }
                }
                LOGGER.info("Order removed count is {}", orderRemovedCount);
                return lastOrdersList;
        }

        // Clean up the saholic cis table
        @RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
        public String updateTagListing(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
                        throws Exception {
                JSONArray jsonArray = new JSONArray(jsonArrayString);
                for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject obj = jsonArray.getJSONObject(i);

                        TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
                        if (tl == null) {
                                continue;
                        } else {
                                tl.setActive(obj.getBoolean("active"));
                                if (!tl.isActive()) {
                                        saholicCISTableRepository.selectAllByItemId(tl.getItemId()).stream()
                                                        .forEach(x -> saholicCISTableRepository.delete(x));
                                }
                        }
                }
                model.addAttribute("response1", true);
                return "response";
        }

        @RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)
        public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
                        throws Exception {
                JSONArray jsonArray = new JSONArray(jsonArrayString);
                for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject obj = jsonArray.getJSONObject(i);

                        TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
                        if (tl == null) {
                                continue;
                        } else {
                                tl.setHotDeals(obj.getBoolean("hotDeals"));
                                tagListingRepository.persist(tl);
                        }
                }
                model.addAttribute("response1", true);
                return "response";
        }

        @RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
        public String raisePO(HttpServletRequest request, Model model) throws Exception {
                boolean success = false;
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                Client userClient = new UserClient().getClient();
                double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();

                if (totalAmount > 0) {
                        userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
                        User user = userRepository.selectById(loginDetails.getFofoId());
                        userClient = new UserClient().getClient();
                        LOGGER.info("Setting wallet amount in cart");
                        long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
                                        7890, OrderSource.WEBSITE.getValue(), true);
                        LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
                        createPayment(user, totalAmount, transactionId);
                        TransactionService.Client transactionClient = new TransactionClient().getClient();
                        transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
                                        "Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
                        transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
                                        "Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
                        LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
                        transactionClient = new TransactionClient().getClient();
                        transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
                        try {
                                transactionClient.enqueueTransactionInfoEmail(transactionId);
                        } catch (Exception e1) {
                                e1.printStackTrace();
                                LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
                        }
                        resetCart(transactionClient.getTransaction(transactionId));
                }
                model.addAttribute("response1", mvcResponseSender.createResponseString(success));
                return "response";
        }

        private void createPayment(User user, double totalAmount, long transactionId)
                        throws NumberFormatException, PaymentException, TException {
                List<Attribute> paymentAttributes = new ArrayList<Attribute>();
                in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
                paymentAttributes.add(new Attribute("payMethod", "7890"));
                long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
                                false);
                paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
                                PaymentStatus.SUCCESS, null, paymentAttributes);
        }

        @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 Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Set<Integer> roleIds = loginDetails.getRoleIds();
                LOGGER.info("Counter size is {}", counterSize);
                LOGGER.info("Fofo Id is {}", fofoId);
                boolean isAdmin = roleManager.isAdmin(roleIds);

                List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
                                .collect(Collectors.toList());

                Map<String, Object> equalsMap = new HashMap<>();
                equalsMap.put("categoryId", 10006);
                equalsMap.put("brand", brands);
                Map<String, List<?>> notEqualsMap = new HashMap<>();

                Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
                Map<Integer, Integer> currentStockMap;

                if (!isAdmin && fofoId == 0) {
                        fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
                        Map<String, Object> equalsStockJoinMap = new HashMap<>();
                        equalsStockJoinMap.put("fofoId", fofoId);
                        currentStockMap = itemRepository
                                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                        equalsStockJoinMap, notEqualsJoinMap, "availability")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                        LOGGER.info("currentStock");
                } else {
                        if (fofoId == 0) {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        } else {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        }
                }

                LOGGER.info("currentStock" + currentStockMap);

                Map<Integer, Integer> itemsInTransit = null;
                List<TagListing> tagListings = tagListingRepository.selectAll(true);
                if (!isAdmin) {
                        tagListings = new ArrayList<>(tagListings);
                        List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
                                        OrderRepository.validOrderStatusList);
                        inTransitOrders = this.filterValidOrders(inTransitOrders);
                        itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                } else {
                        itemsInTransit = new HashMap<>();
                }

                int totalPcs = 0;

                float totalAmount = 0;
                Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                LOGGER.info("regionIds" + regionIds);
                Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
                                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
                LOGGER.info("focusedModelMap" + focusedModelMap);
                LocalDate planningMonthDate = null;
                MonthlyPlanned monthlyPlanned = null;
                List<Integer> fofoOrderIds = null;
                LOGGER.info("localDate" + LocalDate.now());
                if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
                        planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
                        LOGGER.info("monthlyPlanned2" + monthlyPlanned);
                        fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
                                        LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
                                        .collect(Collectors.toList());

                        model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
                } else {
                        planningMonthDate = LocalDate.now().withDayOfMonth(1);
                        LocalDateTime curDate = LocalDate.now().atStartOfDay();
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
                        model.addAttribute("planningMonth", planningMonthDate.getMonth());
                        model.addAttribute("mtd", true);
                        model.addAttribute("freezed", true);
                        fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
                                        curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
                                        .collect(Collectors.toList());
                        LOGGER.info("monthlyPlanned1" + monthlyPlanned);
                }

                Map<Integer, Integer> plannedDetailMap = null;
                if (monthlyPlanned != null) {
                        plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
                                        .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));

                }
                LOGGER.info("plannedDetailMap" + plannedDetailMap);

                LOGGER.info("fofoOrderIds" + fofoOrderIds);
                Map<String, Object> equalsJoinMap = new HashMap<>();

                equalsJoinMap.put("orderId", fofoOrderIds);
                Map<Integer, Integer> last15daysMap = null;
                if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {

                        last15daysMap = itemRepository
                                        .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
                                                        notEqualsJoinMap, "quantity")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                }
                LOGGER.info("last15daysMap" + last15daysMap);

                Map<Integer, TagListing> taglistingMap = tagListings.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
                Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
                                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
                LOGGER.info("catalogIdItemMap");

                Map<String, Object> equalsItemJoinMap = new HashMap<>();
                equalsItemJoinMap.put("active", 1);
                List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                LOGGER.info("tagListingCatalogIds");
                for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
                        int catalogId = catalogIdAggregateValue.getCatalogId();
                        Item item = catalogIdItemMap.get(catalogId).get(0);
                        TagListing tagListing = taglistingMap.get(item.getId());
                        CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
                        if (!catalogListingMap.containsKey(catalogId)) {
                                catalogListingModel = new CatalogListingModel();
                                catalogListingModel.setCatalogId(catalogId);
                                catalogListingModel.setDp(tagListing.getSellingPrice());
                                catalogListingModel.setMop(tagListing.getMop());
                                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
                                if (plannedDetailMap != null) {

                                        Integer quantity = plannedDetailMap.get(catalogId);
                                        if (quantity != null) {
                                                catalogListingModel.setAllocatedQuantity(quantity);
                                        }
                                }

                                if (last15daysMap != null) {
                                        Integer last15DaysSale = last15daysMap.get(catalogId);

                                        if (last15DaysSale != null) {
                                                catalogListingModel.setLast15DaysSale(last15DaysSale);
                                        } else {
                                                catalogListingModel.setLast15DaysSale(0);
                                        }
                                } else {
                                        catalogListingModel.setLast15DaysSale(0);
                                }

                                catalogListingModel.setBrand(item.getBrand());
                                if (item.getCategoryId() == 10006) {
                                        catalogListingModel.setCategoryId(item.getCategoryId());
                                }

                                FocusedModel fm = focusedModelMap.get(catalogId);
                                if (fm != null) {
                                        catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
                                        catalogListingModel.setMinimumQty(fm.getMinimumQty());

                                } else {
                                        catalogListingModel.setRecommendedQty(0);
                                        catalogListingModel.setMinimumQty(0);
                                }

                                catalogListingMap.put(catalogId, catalogListingModel);

                        }
                        int itemAvailability = 0;
                        if (currentStockMap != null) {
                                Integer qty = currentStockMap.get(catalogId);
                                itemAvailability = qty == null ? 0 : qty;
                                catalogListingModel.setStockInHand(itemAvailability);
                        } else {
                                catalogListingModel.setStockInHand(0);
                        }
                        Integer inTransitQuantity = itemsInTransit.get(item.getId());
                        int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
                        catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
                        if (plannedDetailMap != null) {
                                if (plannedDetailMap.get(catalogId) != null) {

                                        int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
                                                        + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
                                        LOGGER.info("remaning" + remaining);

                                        if (remaining != 0) {
                                                catalogListingModel.setRemaining(remaining);
                                        } else {
                                                catalogListingModel.setRemaining(0);
                                        }
                                }
                        }
                }

                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
                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());

                List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());

                Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
                                Comparator.reverseOrder());
                LOGGER.info("monthlyPlanned" + monthlyPlanned);
                model.addAttribute("catalogTagListings",
                                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
                model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
                model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
                model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
                model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());

                model.addAttribute("customRetailers", customRetailers);
                model.addAttribute("totalAmount", totalAmount);
                model.addAttribute("monthlyPlanned", monthlyPlanned);
                model.addAttribute("totalPcs", totalPcs);
                return "open-indent";

        }

        private long resetCart(Transaction transaction) {
                long sum = 0;
                Map<Long, Double> items = new HashMap<Long, Double>();
                for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
                        sum += order.getGvAmount();
                        for (LineItem lineitem : order.getLineitems()) {
                                Long itemId = lineitem.getItem_id();
                                Double quantity = items.get(itemId);
                                if (quantity == null) {
                                        quantity = lineitem.getQuantity();
                                } else {
                                        quantity = quantity + lineitem.getQuantity();
                                }
                                items.put(itemId, quantity);
                        }
                }

                LOGGER.debug("Items to reset in cart are: " + items);

                try {
                        Client userClient = new UserClient().getClient();
                        userClient.resetCart(transaction.getShoppingCartid(), items);
                } catch (TException e) {
                        LOGGER.error("Error while updating information in payment database.", e);
                } catch (ShoppingCartException e) {
                        LOGGER.error("Error while reseting the cart in cart database.", e);
                } catch (Exception e) {
                        LOGGER.error("Unexpected exception", e);
                }
                return sum;
        }

        private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
                List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
                /*
                 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
                 * currentInventorySnapshots = currentInventorySnapshotRepository
                 * .selectItemsStock(fofoId); itemCisMap =
                 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
                 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                 * List<StockAllocationModel> stockAllocationList =
                 * stockAllocationService.getStockAllocation(fofoId, true);
                 *
                 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
                 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
                 * -> x)); Map<Integer, Integer> itemsInTransit = null;
                 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
                 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
                 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
                 * validOrderStatusList); inTransitOrders =
                 * this.filterValidOrders(inTransitOrders); itemsInTransit =
                 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
                 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
                 * x.getLineItem().getQuantity())));
                 *
                 * Iterator<TagListing> iterator = tagListings.iterator();
                 *
                 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
                 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
                 * tagListing.getAllocatedQuantity()); if
                 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
                 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
                 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
                 * itemCisMap.get(tagListing.getItemId());
                 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
                 * itemIdAvailability.getAvailability()); StockAllocationModel
                 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
                 *
                 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
                 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
                 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
                 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
                 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
                 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
                 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
                 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
                 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
                 */
                return itemQuantities;

        }

        @RequestMapping(value = "/indent/loadIndentPreviousMonth")
        public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
                        @RequestParam(required = false, defaultValue = "0") int fofoId,
                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
                LocalDate planMonthStart = null;
                if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
                        planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
                } else {
                        planMonthStart = LocalDate.now().withDayOfMonth(1);
                }
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Set<Integer> roleIds = loginDetails.getRoleIds();
                LOGGER.info("Counter size is {}", counterSize);
                LOGGER.info("Fofo Id is {}", fofoId);
                boolean isAdmin = roleManager.isAdmin(roleIds);

                List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
                                .collect(Collectors.toList());

                Map<String, Object> equalsMap = new HashMap<>();
                equalsMap.put("categoryId", 10006);
                equalsMap.put("brand", brands);
                Map<String, List<?>> notEqualsMap = new HashMap<>();

                Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
                Map<Integer, Integer> currentStockMap;

                if (!isAdmin && fofoId == 0) {
                        fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
                        Map<String, Object> equalsStockJoinMap = new HashMap<>();
                        equalsStockJoinMap.put("fofoId", fofoId);
                        currentStockMap = itemRepository
                                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                        equalsStockJoinMap, notEqualsJoinMap, "availability")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                        LOGGER.info("currentStock");
                } else {
                        if (fofoId == 0) {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        } else {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        }
                }

                LOGGER.info("currentStock" + currentStockMap);

                Map<Integer, Integer> itemsInTransit = null;
                List<TagListing> tagListings = tagListingRepository.selectAll(true);
                if (!isAdmin) {
                        tagListings = new ArrayList<>(tagListings);
                        List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
                                        OrderRepository.validOrderStatusList);
                        inTransitOrders = this.filterValidOrders(inTransitOrders);
                        itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                } else {
                        itemsInTransit = new HashMap<>();
                }

                int totalPcs = 0;

                float totalAmount = 0;
                Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();

                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
                                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));

                MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
                                planMonthStart.minusMonths(1));
                model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
                model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
                model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());

                Map<Integer, Integer> plannedDetailMap = null;
                if (monthlyPlanned != null) {
                        plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
                                        .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));

                }

                LOGGER.info("plannedDetailMap" + plannedDetailMap);
                List<Integer> fofoOrderIds = fofoOrderRepository
                                .selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
                                                planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
                                .stream().map(x -> x.getId()).collect(Collectors.toList());

                LOGGER.info("fofoOrderIds" + fofoOrderIds);
                Map<String, Object> equalsJoinMap = new HashMap<>();
                equalsJoinMap.put("orderId", fofoOrderIds);
                Map<Integer, Integer> lastMonthSaleMap = null;
                if (!fofoOrderIds.isEmpty()) {
                        lastMonthSaleMap = itemRepository
                                        .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
                                                        notEqualsJoinMap, "quantity")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                }
                LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);

                Map<Integer, TagListing> taglistingMap = tagListings.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
                Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
                                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
                LOGGER.info("catalogIdItemMap");

                Map<String, Object> equalsItemJoinMap = new HashMap<>();
                equalsItemJoinMap.put("active", 1);
                List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                LOGGER.info("tagListingCatalogIds");
                for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
                        int catalogId = catalogIdAggregateValue.getCatalogId();
                        Item item = catalogIdItemMap.get(catalogId).get(0);
                        TagListing tagListing = taglistingMap.get(item.getId());
                        CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
                        if (!catalogListingMap.containsKey(catalogId)) {
                                catalogListingModel = new CatalogListingModel();
                                catalogListingModel.setCatalogId(catalogId);
                                catalogListingModel.setDp(tagListing.getSellingPrice());
                                catalogListingModel.setMop(tagListing.getMop());
                                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
                                if (plannedDetailMap != null) {

                                        Integer quantity = plannedDetailMap.get(catalogId);
                                        if (quantity != null) {
                                                catalogListingModel.setAllocatedQuantity(quantity);
                                        }
                                }

                                if (lastMonthSaleMap != null) {
                                        Integer lastMonthSale = lastMonthSaleMap.get(catalogId);

                                        if (lastMonthSale != null) {
                                                catalogListingModel.setLastMonthSaleMap(lastMonthSale);
                                        } else {
                                                catalogListingModel.setLastMonthSaleMap(0);
                                        }
                                } else {
                                        catalogListingModel.setLast15DaysSale(0);
                                }

                                catalogListingModel.setBrand(item.getBrand());
                                if (item.getCategoryId() == 10006) {
                                        catalogListingModel.setCategoryId(item.getCategoryId());
                                }

                                FocusedModel fm = focusedModelMap.get(catalogId);
                                if (fm != null) {
                                        catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
                                        catalogListingModel.setMinimumQty(fm.getMinimumQty());

                                } else {
                                        catalogListingModel.setRecommendedQty(0);
                                        catalogListingModel.setMinimumQty(0);
                                }

                                catalogListingMap.put(catalogId, catalogListingModel);

                        }
                        int itemAvailability = 0;
                        if (currentStockMap != null) {
                                Integer qty = currentStockMap.get(catalogId);
                                itemAvailability = qty == null ? 0 : qty;
                                catalogListingModel.setStockInHand(itemAvailability);
                        } else {
                                catalogListingModel.setStockInHand(0);
                        }
                        Integer inTransitQuantity = itemsInTransit.get(item.getId());
                        int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
                        catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);

                }

                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
                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());

                List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());

                Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
                                Comparator.reverseOrder());
                LOGGER.info("monthlyPlanned" + monthlyPlanned);
                model.addAttribute("catalogTagListings",
                                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
                model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
                model.addAttribute("previousMonth", true);
                model.addAttribute("freezed", true);
                model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
                model.addAttribute("customRetailers", customRetailers);
                model.addAttribute("totalAmount", totalAmount);
                model.addAttribute("monthlyPlanned", monthlyPlanned);
                model.addAttribute("totalPcs", totalPcs);
                return "open-indent";

        }

        private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
                Map<Integer, Item> itemMap = new HashMap<>();
                for (FocusedModel focusedModel : focusedModels) {
                        List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
                        itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
                }

                return itemMap;
        }

        private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
                Map<Integer, Region> regionMap = new HashMap<>();
                for (FocusedModel focusedModel : focusedModels) {
                        Region region = regionRepository.selectById(focusedModel.getRegionId());
                        regionMap.put(region.getId(), region);
                }

                return regionMap;
        }

        @RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
        public String getFocusedModel(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
                        throws ProfitMandiBusinessException {

                long size = 0;
                List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);

                size = focusedModelRepository.selectAllCount();
                if (!focusedModels.isEmpty()) {
                        Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
                        Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);

                        LOGGER.info("regionMap" + regionMap);
                        model.addAttribute("focusedModels", focusedModels);
                        model.addAttribute("itemMap", itemMap);
                        model.addAttribute("regionMap", regionMap);
                        model.addAttribute("start", offset + 1);
                        model.addAttribute("size", size);
                        model.addAttribute("url", "/getPaginatedFocusedModel");

                        if (focusedModels.size() < limit) {
                                model.addAttribute("end", offset + focusedModels.size());
                        } else {
                                model.addAttribute("end", offset + limit);
                        }
                } else {

                        model.addAttribute("walletRequest", focusedModels);
                        model.addAttribute("size", size);

                }

                List<Region> regions = regionRepository.selectAll();

                model.addAttribute("regions", regions);

                return "focused_model";
        }

        @RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
        public String getPaginatedFocusedModel(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
                        throws ProfitMandiBusinessException {
                LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
                List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);

                if (!focusedModels.isEmpty()) {
                        Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
                        Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
                        model.addAttribute("focusedModels", focusedModels);
                        model.addAttribute("itemMap", itemMap);
                        model.addAttribute("regionMap", regionMap);
                        model.addAttribute("url", "/getPaginatedFocusedModel");
                } else {
                        model.addAttribute("focusedModels", focusedModels);

                }

                List<Region> regions = regionRepository.selectAll();

                model.addAttribute("regions", regions);
                return "focused-model-paginated";
        }

        private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
                Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);

                List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 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);
                        }
                });

                return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
                                .collect(Collectors.toList());
        }

        @RequestMapping(value = "/getPartnerAllocation")
        public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());

                Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();

                List<Integer> fofoIds = pp.get(authUser.getId());

                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
                                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                model.addAttribute("customRetailersMap", crm);
                model.addAttribute("fofoStoreMap", fofoStoreMap);
                return "partners_allocation";

        }

        @RequestMapping(value = "/partnerPendingOrder")
        public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());

                Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();

                List<Integer> fofoIds = pp.get(authUser.getId());
                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
                                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));

                model.addAttribute("customRetailersMap", crm);

                return "partner-po";

        }

        @RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
        public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,
                        @RequestParam(name = "recommended", defaultValue = "0") int recommended,
                        @RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,
                        @RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,
                        @RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,
                        Model model) throws ProfitMandiBusinessException {

                FocusedModel fm = new FocusedModel();
                fm.setCatalogId(catalogId);
                fm.setMinimumQty(minimumQty);
                fm.setRecommendedQty(recommended);
                fm.setRegionId(regionId);
                fm.setObsRecommendedQty(obvrecommend);
                fm.setObsMinimumQty(obvminimum);
                fm.setCreatedTimestamp(LocalDateTime.now());
                focusedModelRepository.persist(fm);
                return "focused_model";
        }

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

                focusedModelRepository.deleteById(id);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "response";
        }

        @RequestMapping(value = "/getPartnerloadContent")
        public String getPartnerloadContent(HttpServletRequest request, Model model,
                        @RequestParam(required = false, defaultValue = "0") int fofoId,
                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Set<Integer> roleIds = loginDetails.getRoleIds();
                LOGGER.info("Counter size is {}", counterSize);
                LOGGER.info("Fofo Id is {}", fofoId);
                boolean isAdmin = roleManager.isAdmin(roleIds);

                List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
                                .collect(Collectors.toList());

                Map<String, Object> equalsMap = new HashMap<>();
                equalsMap.put("categoryId", 10006);
                equalsMap.put("brand", brands);
                Map<String, List<?>> notEqualsMap = new HashMap<>();

                Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
                Map<Integer, Integer> currentStockMap;

                if (!isAdmin && fofoId == 0) {
                        fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
                        Map<String, Object> equalsStockJoinMap = new HashMap<>();
                        equalsStockJoinMap.put("fofoId", fofoId);
                        currentStockMap = itemRepository
                                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                        equalsStockJoinMap, notEqualsJoinMap, "availability")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                        LOGGER.info("currentStock");
                } else {
                        if (fofoId == 0) {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        } else {

                                Map<String, Object> equalsStockJoinMap = new HashMap<>();
                                equalsStockJoinMap.put("fofoId", fofoId);

                                currentStockMap = itemRepository
                                                .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
                                                                equalsStockJoinMap, notEqualsJoinMap, "availability")
                                                .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));

                        }
                }

                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
                LOGGER.info("currentStock" + currentStockMap);

                Map<Integer, Integer> itemsInTransit = null;
                List<TagListing> tagListings = tagListingRepository.selectAll(true);
                if (!isAdmin) {
                        tagListings = new ArrayList<>(tagListings);
                        List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
                                        OrderRepository.validOrderStatusList);
                        inTransitOrders = this.filterValidOrders(inTransitOrders);
                        itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                } else {
                        itemsInTransit = new HashMap<>();
                }

                int totalPcs = 0;

                float totalAmount = 0;
                Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();

                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());

                Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
                                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));

                LocalDate currentMonthDate = LocalDate.now();
                MonthlyPlanned monthlyPlanned = null;
                List<Integer> fofoOrderIds = null;
                LOGGER.info("localDate" + LocalDate.now());
                if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
                        currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
                        LOGGER.info("monthlyPlanned2" + monthlyPlanned);
                        fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
                                        LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
                                        .collect(Collectors.toList());

                        model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
                } else {
                        currentMonthDate = LocalDate.now().withDayOfMonth(1);
                        LocalDateTime curDate = LocalDate.now().atStartOfDay();
                        monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
                        model.addAttribute("planningMonth", currentMonthDate.getMonth());
                        model.addAttribute("mtd", true);
                        model.addAttribute("freezed", true);
                        fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
                                        curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
                                        .collect(Collectors.toList());
                        LOGGER.info("monthlyPlanned1" + monthlyPlanned);
                }

                Map<Integer, Integer> plannedDetailMap = null;
                if (monthlyPlanned != null) {
                        plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
                                        .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));

                }
                LOGGER.info("plannedDetailMap" + plannedDetailMap);

                LOGGER.info("fofoOrderIds" + fofoOrderIds);
                Map<String, Object> equalsJoinMap = new HashMap<>();

                equalsJoinMap.put("orderId", fofoOrderIds);
                Map<Integer, Integer> last15daysMap = null;
                if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {

                        last15daysMap = itemRepository
                                        .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
                                                        notEqualsJoinMap, "quantity")
                                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
                }
                LOGGER.info("last15daysMap" + last15daysMap);

                Map<Integer, TagListing> taglistingMap = tagListings.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
                Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
                                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
                LOGGER.info("catalogIdItemMap");

                Map<String, Object> equalsItemJoinMap = new HashMap<>();
                equalsItemJoinMap.put("active", 1);
                List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                Map<Integer, Integer> ourStockAvailability = new HashMap<>();

                Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
                                .selectAllByCatalogIds(new HashSet<>(
                                                tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
                                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                Collectors.mapping(y -> y.getId(), Collectors.toList())));
                for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
                        List<Integer> itemIds = catalogItem.getValue();
                        int availability = 0;
                        for (Integer itemId : itemIds) {
                                List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId,
                                                fofoStore.getWarehouseId());
                                if (saholicCISTableList != null) {
                                        availability += saholicCISTableList.stream()
                                                        .collect(Collectors.summingInt(x -> x.getAvailability()));
                                }
                        }
                        Integer catalogItemId = catalogItem.getKey();
                        ourStockAvailability.put(catalogItemId, availability);
                }
                LOGGER.info("ourStockAvailability" + ourStockAvailability);

                for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
                        int catalogId = catalogIdAggregateValue.getCatalogId();
                        Item item = catalogIdItemMap.get(catalogId).get(0);
                        TagListing tagListing = taglistingMap.get(item.getId());
                        CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
                        if (!catalogListingMap.containsKey(catalogId)) {
                                catalogListingModel = new CatalogListingModel();
                                catalogListingModel.setCatalogId(catalogId);
                                catalogListingModel.setDp(tagListing.getSellingPrice());
                                catalogListingModel.setMop(tagListing.getMop());
                                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
                                if (plannedDetailMap != null) {

                                        Integer quantity = plannedDetailMap.get(catalogId);
                                        if (quantity != null) {
                                                catalogListingModel.setAllocatedQuantity(quantity);
                                        }
                                }

                                if (last15daysMap != null) {
                                        Integer last15DaysSale = last15daysMap.get(catalogId);

                                        if (last15DaysSale != null) {
                                                catalogListingModel.setLast15DaysSale(last15DaysSale);
                                        } else {
                                                catalogListingModel.setLast15DaysSale(0);
                                        }
                                } else {
                                        catalogListingModel.setLast15DaysSale(0);
                                }

                                catalogListingModel.setBrand(item.getBrand());
                                if (item.getCategoryId() == 10006) {
                                        catalogListingModel.setCategoryId(item.getCategoryId());
                                }

                                Integer ourStock = ourStockAvailability.get(catalogId);
                                LOGGER.info("catalogId" + catalogId);

                                LOGGER.info("ourStock" + ourStock);
                                if (ourStock != null) {
                                        catalogListingModel.setOurStockQty(ourStock);
                                }

                                FocusedModel fm = focusedModelMap.get(catalogId);
                                if (fm != null) {
                                        catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
                                        catalogListingModel.setMinimumQty(fm.getMinimumQty());
                                        catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());
                                        catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());

                                } else {
                                        catalogListingModel.setRecommendedQty(0);
                                        catalogListingModel.setMinimumQty(0);

                                        catalogListingModel.setObsRecommendedQty(0);
                                        catalogListingModel.setObsMinimumQty(0);

                                }

                                catalogListingMap.put(catalogId, catalogListingModel);

                        }
                        int itemAvailability = 0;
                        if (currentStockMap != null) {
                                Integer qty = currentStockMap.get(catalogId);
                                itemAvailability = qty == null ? 0 : qty;
                                catalogListingModel.setStockInHand(itemAvailability);
                        } else {
                                catalogListingModel.setStockInHand(0);
                        }
                        Integer inTransitQuantity = itemsInTransit.get(item.getId());
                        int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
                        catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
                        if (plannedDetailMap != null) {
                                if (plannedDetailMap.get(catalogId) != null) {

                                        int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
                                                        + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
                                        LOGGER.info("remaning" + remaining);

                                        if (remaining != 0) {
                                                catalogListingModel.setRemaining(remaining);
                                        } else {
                                                catalogListingModel.setRemaining(0);
                                        }
                                }
                        }
                }

                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
                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());

                List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());

                Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
                                Comparator.reverseOrder());
                LOGGER.info("monthlyPlanned" + monthlyPlanned);
                model.addAttribute("catalogTagListings",
                                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
                model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
                model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
                model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
                model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());

                model.addAttribute("customRetailers", customRetailers);
                model.addAttribute("totalAmount", totalAmount);
                model.addAttribute("monthlyPlanned", monthlyPlanned);
                model.addAttribute("totalPcs", totalPcs);

                UserWallet userWallet = walletService.getUserWallet(fofoId);

                model.addAttribute("userWallet", userWallet);

                return "create-partner-po";

        }

        @RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
        public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
                        throws Exception {

                List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);

                List<Item> items = new ArrayList<>();
                for (Item item : selecteditems) {

                        TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);

                        if (tagListing != null) {
                                items.add(item);
                        }

                }
                model.addAttribute("items", items);
                LOGGER.info("itemIdAndColorMap" + items);
                return "select-item-color";
        }

        List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
                        "niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com");

        @Autowired
        private PositionRepository positionRepository;

        @Autowired
        private PartnerTypeChangeService partnerTypeChangeService;

        @Autowired
        private com.spice.profitmandi.service.transaction.TransactionService transactionService;

        @Autowired
        private CategoryRepository categoryRepository;

        @Autowired
        private BrandLimitRepository brandLimitRepository;

        @Autowired
        //This is alternate proxy to auth to enable Spring Caching
        private CsService1 authService1;

        private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,
                        OrderStatus.ACCEPTED);

        public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();

        static {

                Brand_Amount_Limit.put("accessories", 10000.00);
                Brand_Amount_Limit.put("TV", 27000.00);
        }

        @RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)
        public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();

                List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Tecno", "Itel", "OnePlus", "Lava", "Realme",
                                "Xiaomi", "Nokia");

                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);

                Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();

                Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();

                Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();
                Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();
                Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();
                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
                Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();

                if (fofoIds != null && fofoIds.size() > 0) {
                        List<Integer> fofoIdList = new ArrayList<>(fofoIds);

                        Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
                                        .stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));

                        model.addAttribute("partnerActivationType", partnerActivationType);
                        model.addAttribute("activationTypes", ActivationType.values());

                        Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();

                        model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);

                        Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
                                        .stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
                                                        Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));

                        model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
                        customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
                                        .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                        Map<Integer, Map<String, Double>> inStockBrandModel = new HashMap<>();
                        Map<Integer, Map<String, Double>> pendingIndent = new HashMap<>();
                        Map<Integer, Map<String, Double>> grnPendingOrders = new HashMap<>();

                        // mobile
                        inStockBrandModel = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList)
                                        .stream()
                                        .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
                                                        Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
                                                                        Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));

                        pendingIndent = transactionService.getInTransitOrders(fofoIdList).stream()
                                        .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
                                        .collect(Collectors.groupingBy(x -> x.getRetailerId(),
                                                        Collectors.groupingBy(y -> y.getLineItem().getBrand(),
                                                                        Collectors.summingDouble(y -> (double) y.getTotalAmount()))));

                        grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoIdList).stream()
                                        .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
                                        .collect(Collectors.groupingBy(x -> x.getRetailerId(),
                                                        Collectors.groupingBy(y -> y.getLineItem().getBrand(),
                                                                        Collectors.summingDouble(y -> (double) y.getTotalAmount()))));

                        // accessories
                        inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
                                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

                        pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
                                        .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

                        grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
                                        .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));

                        for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
                                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
                                                LocalDate.now());
                                fofoIdPartnerTypeMap.put(customRetailer.getKey(), partnerType);

                                Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
                                Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
                                Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
                                double totalAmount = 0;

                                Map<String, Double> brandAmountMap = new HashMap<>();
                                for (String brand : brands) {

                                        double stockValue = 0;
                                        double pendingValue = 0;
                                        double grnValue = 0;
                                        if (stockBrand != null) {

                                                if (stockBrand.get(brand) != null) {
                                                        stockValue = stockBrand.get(brand);
                                                }
                                        }

                                        if (pendingIndentBrand != null) {
                                                if (pendingIndentBrand.get(brand) != null) {
                                                        pendingValue = pendingIndentBrand.get(brand);
                                                }
                                        }

                                        if (grnBrand != null) {
                                                if (grnBrand.get(brand) != null) {
                                                        grnValue = grnBrand.get(brand);
                                                }
                                        }

                                        totalAmount = stockValue + pendingValue + grnValue;

                                        brandAmountMap.put(brand, totalAmount);

                                }

                                fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);

                        }

                        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
                                        .selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
                        if (!partnerDailyInvestments.isEmpty()) {
                                partnerDailyInvestmentMap = partnerDailyInvestments.stream()
                                                .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
                        }

                }

                model.addAttribute("customRetailers", customRetailers);

                LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);

                model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);

                model.addAttribute("brands", brands);

                model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
                model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);

                model.addAttribute("inStockAccessTv", inStockAccessTv);
                model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
                model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
                model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
                return "partner-brandwise-detail";
        }

        @RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
        public String changeActivationType(HttpServletRequest request, @RequestParam String code,
                        @RequestParam ActivationType activationType, Model model) throws Exception {

                FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);

                fofoStore.setActivationType(activationType);

                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "response";

        }

        @RequestMapping(value = "/createPo", method = RequestMethod.POST)
        public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
                        throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                SuggestedPo mp = new SuggestedPo();
                mp.setFofoId(monthlyPoModel.getFofoId());
                mp.setCreateTimestamp(LocalDateTime.now());
                mp.setStatus("open");
                mp.setAuthId(loginDetails.getEmailId());
                suggestedPoRepository.persist(mp);

                for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
                        SuggestedPoDetail mpd = new SuggestedPoDetail();
                        mpd.setItemId(poId.getItemId());
                        mpd.setQuantity(poId.getQty());
                        mpd.setUpdatedTimestamp(LocalDateTime.now());
                        mpd.setPoId(mp.getId());
                        suggestedPoDetailRepository.persist(mpd);
                }

                SendNotificationModel sendNotificationModel = new SendNotificationModel();
                sendNotificationModel.setCampaignName("Alert");
                sendNotificationModel.setMessage("Suggested Po");
                sendNotificationModel.setType("url");
                sendNotificationModel.setTitle("Alert");
                sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
                sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
                sendNotificationModel.setMessageType(MessageType.notification);
                int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());

                sendNotificationModel.setUserIds(Arrays.asList(userId));
                notificationService.sendNotification(sendNotificationModel);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));

                return "response";
        }

        @RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
        public String getPartnerShortageStock(HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
                        throws Exception {

                Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
                                .getSaholicPOItems();

                List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
                CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
                Map<Integer, Integer> processingOrderMap = null;
                Map<Integer, Integer> catalogIdAndQtyMap = null;
                Map<Integer, Integer> grnPendingOrdersMap = null;

                List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();

                List<PartnerStockDescriptionModel> grnPendings = new ArrayList<>();

                List<PartnerStockDescriptionModel> pendingIndents = new ArrayList<>();

                Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
                                .stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));

                if (!currentInventorySnapshot.isEmpty()) {
                        if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
                                catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
                                                .filter(x -> x.getBrand().equals(brand))
                                                .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                                Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));

                        } else {
                                catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
                                                .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                                Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
                        }
                        inStocks.addAll(getBrandItemwiseDescription(brand, catalogIdAndQtyMap));
                }

                Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
                                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                                Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                if (!grnPendingOrders.isEmpty()) {

                        if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
                                grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
                                                .filter(x -> x.getBrand().equals(brand))
                                                .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                                Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));

                        } else {
                                grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
                                                .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                                Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
                        }
                        grnPendings.addAll(getBrandItemwiseDescription(brand, grnPendingOrdersMap));

                }

                Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
                                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                                Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                if (!processingOrder.isEmpty()) {
                        if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
                                processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
                                                .filter(x -> x.getBrand().equals(brand)).collect(Collectors.groupingBy(
                                                                x -> x.getCatalogItemId(), Collectors.summingInt(x -> processingOrder.get(x.getId()))));

                        } else {
                                processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
                                                .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
                                                                Collectors.summingInt(x -> processingOrder.get(x.getId()))));
                        }
                        pendingIndents.addAll(getBrandItemwiseDescription(brand, processingOrderMap));

                }

                List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
                                .collect(Collectors.toList());
                LOGGER.info("regionIds" + regionIds);
                if (regionIds.size() == 0) {
                        LOGGER.info("No region found for partner {}", fofoId);

                }
                Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
                                .selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
                                                Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));

                for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
                        List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());

                        if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {

                                FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
                                                processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
                                                warehousePoItemAvailabilityMap, items, customRetailer);

                                focusedModelShortageList.add(fm);
                        } else if (brand.equals("accessories")) {

                                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
                                        if (items.get(0).getCategoryId() != 0) {
                                                Category category = categoryRepository.selectById(items.get(0).getCategoryId());

                                                if (category.getParentCategoryId() == 10011) {
                                                        FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
                                                                        entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
                                                                        warehousePoItemAvailabilityMap, items, customRetailer);

                                                        focusedModelShortageList.add(fm);

                                                }
                                        }

                                }

                        } else if (brand.equals("TV")) {

                                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
                                        LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
                                        if (items.get(0).getCategoryId() != 0) {

                                                Category category = categoryRepository.selectById(items.get(0).getCategoryId());

                                                if (category.getParentCategoryId() == 14200) {
                                                        FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
                                                                        entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
                                                                        warehousePoItemAvailabilityMap, items, customRetailer);

                                                        focusedModelShortageList.add(fm);

                                                }
                                        }

                                }

                        }

                }

                LOGGER.info("focusedModelShortageList" + focusedModelShortageList);

                model.addAttribute("focusedModelShortageList", focusedModelShortageList);

                model.addAttribute("inStocks", inStocks);

                model.addAttribute("grnPendings", grnPendings);

                model.addAttribute("pendingIndents", pendingIndents);

                model.addAttribute("customRetailer", customRetailer);

                model.addAttribute("brand", brand);

                if (brand.equals("undefined")) {

                        Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
                                        .stream().collect(Collectors.groupingBy(x -> x.getBrandName()));

                        Map<String, List<PartnerStockDescriptionModel>> inStockBrandMap = inStocks.stream()
                                        .collect(Collectors.groupingBy(x -> x.getBrand()));

                        LOGGER.info("inStockBrandMap" + inStockBrandMap);

                        Map<String, List<PartnerStockDescriptionModel>> grnPendingBrandMap = grnPendings.stream()
                                        .collect(Collectors.groupingBy(x -> x.getBrand()));

                        LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);

                        Map<String, List<PartnerStockDescriptionModel>> pendingIndentBrandMap = pendingIndents.stream()
                                        .collect(Collectors.groupingBy(x -> x.getBrand()));

                        LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);

                        model.addAttribute("inStockBrandMap", inStockBrandMap);

                        model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);

                        model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);

                        model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);

                }
                return "partner-stock";

        }

        private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
                        Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
                List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();

                for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
                        List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());

                        if (brand.equals("accessories")) {
                                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {

                                        if (items.get(0).getCategoryId() != 0) {
                                                Category category = categoryRepository.selectById(items.get(0).getCategoryId());

                                                if (category.getParentCategoryId() == 10011) {
                                                        PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
                                                        psdp.setBrand(items.get(0).getBrand());
                                                        psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
                                                                        + items.get(0).getModelNumber());
                                                        psdp.setQty(inStock.getValue());
                                                        inStocks.add(psdp);
                                                }
                                        }

                                }

                        } else if (brand.equals("TV")) {
                                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {

                                        if (items.get(0).getCategoryId() != 0) {
                                                Category category = categoryRepository.selectById(items.get(0).getCategoryId());

                                                if (category.getParentCategoryId() == 14200) {
                                                        PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
                                                        psdp.setBrand(items.get(0).getBrand());
                                                        psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
                                                                        + items.get(0).getModelNumber());
                                                        psdp.setQty(inStock.getValue());
                                                        inStocks.add(psdp);
                                                }
                                        }

                                }

                        } else {
                                PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
                                psdp.setBrand(items.get(0).getBrand());
                                psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
                                                + items.get(0).getModelNumber());
                                psdp.setQty(inStock.getValue());
                                inStocks.add(psdp);
                        }

                }

                return inStocks;
        }

        private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
                        Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
                        Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
                        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
                        CustomRetailer customRetailer) throws ProfitMandiBusinessException {

                int minQty = qty;
                int inStockQty = 0;
                int processingQty = 0;
                int grnPendingQty = 0;
                int allColorNetAvailability = 0;
                int allColorPoAvailability = 0;
                if (processingOrderMap != null) {
                        processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);

                }
                if (grnPendingOrdersMap != null) {
                        grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);

                }
                if (catalogIdAndQtyMap != null) {
                        inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);

                }

                int grnStockQty = grnPendingQty + inStockQty;
                int totalQty = processingQty + grnPendingQty + inStockQty;

                int shortageQty = minQty - totalQty;
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);

                Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
                                .get(fofoStore.getWarehouseId());

                for (Item it : items) {
                        List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(),
                                        fofoStore.getWarehouseId());
                        List<SaholicPOItem> poItemAvailability = null;

                        if (poItemAvailabilityMap != null) {
                                poItemAvailability = poItemAvailabilityMap.get(it.getId());
                        }
                        if (currentAvailability != null) {
                                allColorNetAvailability += currentAvailability.stream()
                                                .collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
                        }

                        if (poItemAvailability != null) {
                                allColorPoAvailability += poItemAvailability.stream()
                                                .collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
                        }

                }

                FocusedModelShortageModel fm = new FocusedModelShortageModel();
                fm.setFofoId(fofoId);
                fm.setStoreCode(fofoStore.getCode());
                fm.setStoreName(customRetailer.getBusinessName());
                fm.setBrandName(items.get(0).getBrand());
                fm.setModelName(items.get(0).getModelName());
                fm.setModelNumber(items.get(0).getModelNumber());
                fm.setGrnStockQty(grnStockQty);
                fm.setPendingIndentQty(processingQty);
                fm.setShortageQty(shortageQty);
                fm.setPoAvailability(allColorPoAvailability);
                fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
                fm.setAvailability(allColorNetAvailability);
                return fm;

        }

        @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
        public String SendPONotification(HttpServletRequest request, Model model) {
                model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);
                return "send-po-notification";
        }

        @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
        public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
                        Model model) throws Exception {

                Map<Integer, Item> selectedCatalogItemMap = itemRepository
                                .selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
                                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));

                Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
                                .collect(Collectors.toSet());

                int warehouseId = poItemWarehouseModel.getWarehouseId();
                for (String brand : brands) {
                        List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
                                        .filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
                                        .map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
                        SendNotificationModel sendNotificationModel = new SendNotificationModel();
                        sendNotificationModel.setCampaignName("SendPo");
                        sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
                        sendNotificationModel.setMessage(String.join(", ", modelNames));
                        sendNotificationModel.setType("url");
                        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
                        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
                        sendNotificationModel.setMessageType(MessageType.notification);

                        List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
                                        .filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
                                                        && !x.isAccessory())
                                        .collect(Collectors.toList());
                        List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
                                        .collect(Collectors.toList());

                        List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
                                        .filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());

                        List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
                        sendNotificationModel.setUserIds(userIds);
                        notificationService.sendNotification(sendNotificationModel);
                }
                model.addAttribute("response1", true);
                return "response";
        }

}