Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

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 com.mongodb.DBObject;
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.BrandStockPrice;
import com.spice.profitmandi.common.model.CatalogIdAggregateValue;
import com.spice.profitmandi.common.model.CatalogListingModel;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.PlannedModel;
import com.spice.profitmandi.common.model.SendNotificationModel;
import com.spice.profitmandi.common.model.StockAllocationModel;
import com.spice.profitmandi.common.model.SuggestedPoIdModel;
import com.spice.profitmandi.common.model.SuggestedPoModel;
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.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.CurrentInventorySnapshot;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
import com.spice.profitmandi.dao.entity.inventory.SaholicCIS;
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.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
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.CsService;
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
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.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
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.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.LineItem;
import in.shop2020.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionService;
import in.shop2020.model.v1.order.TransactionStatus;
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;

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

        @Autowired
        WalletService walletService;

        @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 CsService csService;

        @Autowired
        private AuthRepository authRepository;

        @Autowired
        private SuggestedPoRepository monthlyPoRepository;

        @Autowired
        private SuggestedPoDetailRepository monthlyPoDetailRepository;

        @Autowired
        private NotificationService notificationService;

        @Autowired
        private RegionRepository regionRepository;

        @Autowired
        private PartnerRegionRepository partnerRegionRepository;

        @Autowired
        private SaholicInventoryCISRepository saholicInventoryCISRepository;

        @Autowired
        private SaholicInventoryService saholicInventoryService;

        @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("response", 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("response", 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);
                ccemails.add(emailEsclationType.get(EscalationType.L1));
                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> customRetailersMap = retailerService.getFofoRetailers(fofoIds);

                        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 = customRetailersMap.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("response", 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("response", response.toString());
                return "response";

        }

        @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<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                LOGGER.info("tagListingCatalogIds");
                for (CatalogIdAggregateValue 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";

        }

        @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<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                LOGGER.info("tagListingCatalogIds");
                for (CatalogIdAggregateValue 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 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;
        }

        @RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
        public String raisePO(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"));
                                tagListingRepository.persist(tl);
                        }
                }
                model.addAttribute("response", 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("response", 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.getFofoRetailers(Arrays.asList(fofoId)).get(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("response", 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);
        }

        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;

        }

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

        @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 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 = "/focusedModel", method = RequestMethod.POST)
        public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
                        @RequestParam int minimumQty, @RequestParam int regionId, Model model) throws ProfitMandiBusinessException {

                FocusedModel fm = new FocusedModel();
                fm.setCatalogId(catalogId);
                fm.setMinimumQty(minimumQty);
                fm.setRecommendedQty(recommended);
                fm.setRegionId(regionId);
                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("response", mvcResponseSender.createResponseString(true));
                return "response";
        }

        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> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
                Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));

                model.addAttribute("customRetailersMap", customRetailersMap);
                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> customRetailersMap = retailerService.getFofoRetailers(fofoIds);

                model.addAttribute("customRetailersMap", customRetailersMap);

                return "partner-po";

        }

        @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<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
                                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
                Map<Integer, Integer> ourStockAvailability = new HashMap<>();
                Map<Integer, List<SaholicCIS>> itemAvailabilityMap = saholicInventoryService.getSaholicStock()
                                .get(fofoStore.getWarehouseId());

                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<SaholicCIS> scis = itemAvailabilityMap.get(itemId);
                                if (scis != null) {
                                        availability += scis.stream().collect(Collectors.summingInt(x -> x.getAvailability()));
                                }
                        }
                        Integer catalogItemId = catalogItem.getKey();
                        ourStockAvailability.put(catalogItemId, availability);
                }
                LOGGER.info("ourStockAvailability" + ourStockAvailability);

                for (CatalogIdAggregateValue 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());

                                } 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(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 = "/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());
                monthlyPoRepository.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());
                        monthlyPoDetailRepository.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("response", mvcResponseSender.createResponseString(true));

                return "response";
        }

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

}