Rev 35765 | Rev 35776 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.controller;import com.spice.profitmandi.common.enumuration.ActivationType;import com.spice.profitmandi.common.enumuration.CounterSize;import com.spice.profitmandi.common.enumuration.MessageType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.*;import com.spice.profitmandi.common.util.FileUtil;import com.spice.profitmandi.common.util.Utils;import com.spice.profitmandi.common.util.Utils.Attachment;import com.spice.profitmandi.common.web.util.ResponseSender;import com.spice.profitmandi.dao.entity.auth.AuthUser;import com.spice.profitmandi.dao.entity.catalog.*;import com.spice.profitmandi.dao.entity.cs.Region;import com.spice.profitmandi.dao.entity.fofo.*;import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;import com.spice.profitmandi.dao.entity.transaction.Loan;import com.spice.profitmandi.dao.entity.transaction.Order;import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;import com.spice.profitmandi.dao.entity.transaction.UserWallet;import com.spice.profitmandi.dao.entity.user.User;import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;import com.spice.profitmandi.dao.enumuration.cs.EscalationType;import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;import com.spice.profitmandi.dao.event.TagListingEventPublisher;import com.spice.profitmandi.dao.model.*;import com.spice.profitmandi.dao.repository.auth.AuthRepository;import com.spice.profitmandi.dao.repository.catalog.*;import com.spice.profitmandi.dao.repository.cs.*;import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.Mongo;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.fofo.*;import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;import com.spice.profitmandi.dao.repository.transaction.LoanRepository;import com.spice.profitmandi.dao.repository.transaction.OrderRepository;import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;import com.spice.profitmandi.dao.repository.user.UserRepository;import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;import com.spice.profitmandi.model.WarehouseItemQtyModel;import com.spice.profitmandi.service.FofoUser;import com.spice.profitmandi.service.NotificationService;import com.spice.profitmandi.service.RbmTargetService;import com.spice.profitmandi.service.authentication.RoleManager;import com.spice.profitmandi.service.catalog.BrandsService;import com.spice.profitmandi.service.inventory.*;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.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.model.v1.order.LineItem;import in.shop2020.model.v1.order.OrderStatus;import in.shop2020.model.v1.order.Transaction;import in.shop2020.model.v1.user.ItemPriceQuantity;import in.shop2020.model.v1.user.ShoppingCartException;import in.shop2020.model.v1.user.UserContextService.Client;import in.shop2020.payments.Attribute;import in.shop2020.payments.PaymentException;import in.shop2020.payments.PaymentStatus;import org.apache.commons.io.output.ByteArrayOutputStream;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.thrift.TException;import org.json.JSONArray;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.ByteArrayResource;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.stereotype.Controller;import org.springframework.transaction.annotation.Transactional;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import javax.servlet.http.HttpServletRequest;import java.math.BigDecimal;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.YearMonth;import java.util.*;import java.util.Map.Entry;import java.util.function.Function;import java.util.stream.Collectors;@Controller@Transactional(rollbackFor = Throwable.class)public class IndentController {private static final Logger LOGGER = LogManager.getLogger(IndentController.class);private static final int WALLET_GATEWAY_ID = 8;private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,OrderStatus.REACHED_DESTINATION_CITY);private static final int PLANNING_OPEN_DAY = 20;private static final int PLANNING_CLOSE_DAY = 1;private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";@AutowiredWalletService walletService;@AutowiredBrandRegionMappingRepository brandRegionMappingRepository;@Autowiredprivate JavaMailSender googleMailSender;@Autowiredprivate ResponseSender responseSender;@Autowiredprivate CookiesProcessor cookiesProcessor;@Autowiredprivate UserWalletRepository userWalletRepository;@Autowiredprivate UserRepository userRepository;@AutowiredFofoStoreRepository fofoStoreRepository;@Autowiredprivate OrderRepository orderRepository;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate StockAllocationService stockAllocationService;@Autowiredprivate RetailerService retailerService;@Autowiredprivate TagListingRepository tagListingRepository;@Autowiredprivate TagListingEventPublisher tagListingEventPublisher;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;@Autowiredprivate InventoryItemRepository inventoryItemRepository;@Autowiredprivate PurchaseRepository purchaseRepository;@Autowiredprivate MVCResponseSender mvcResponseSender;@Autowiredprivate FocusedModelRepository focusedModelRepository;@Autowiredprivate MonthlyPlannedRepository monthlyPlannedRepository;@Autowiredprivate FofoOrderRepository fofoOrderRepository;@Autowiredprivate FofoOrderItemRepository fofoOrderItemRepository;@Autowiredprivate PlannedDetailRepository plannedDetailRepository;@AutowiredRoleManager roleManager;@AutowiredPartnerTypeChangeRepository partnerTypeChangeRepository;@Autowiredprivate Mongo mongoClient;@Autowiredprivate InventoryService inventoryService;@Autowiredprivate CsService1 csService1;@Autowiredprivate CsService csService;@Autowiredprivate AuthRepository authRepository;@AutowiredWarehouseRepository warehouseRepository;@Autowiredprivate SuggestedPoRepository suggestedPoRepository;@Autowiredprivate NotificationService notificationService;@Autowiredprivate RegionRepository regionRepository;@Autowiredprivate PartnerRegionRepository partnerRegionRepository;@Autowiredprivate SaholicInventoryCISRepository saholicInventoryCISRepository;@Autowiredprivate SaholicInventoryService saholicInventoryService;@Autowiredprivate PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;@Autowiredprivate SuggestedPoDetailRepository suggestedPoDetailRepository;@AutowiredSaholicCISTableRepository saholicCISTableRepository;@AutowiredMonthlyTargetRepository monthlyTargetRepository;@AutowiredAgeingService ageingService;@AutowiredLoanRepository loanRepository;@AutowiredRbmTargetService rbmTargetService;@AutowiredFofoUser fofoUser;@AutowiredBrandsService brandsService;@AutowiredSDCreditRequirementRepository sdCreditRequirementRepository;@AutowiredCategorisedCatalogRepository categorisedCatalogRepository;@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,@RequestParam int itemQty, @RequestParam int fofoId) throws Exception {if (fofoId == 0) {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);fofoId = loginDetails.getFofoId();}LocalDate currentMonthDate = LocalDate.now();MonthlyPlanned monthlyPlanned = null;if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);LOGGER.info("monthlyPlanned" + monthlyPlanned);saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);}model.addAttribute("response1", mvcResponseSender.createResponseString(false));return "response";}private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,int catalogId, int itemQty) {if (monthlyPlanned == null) {monthlyPlanned = new MonthlyPlanned();monthlyPlanned.setFofoId(fofoId);monthlyPlanned.setYearMonth(currentMonthDate);monthlyPlannedRepository.persist(monthlyPlanned);PlannedDetail pd = new PlannedDetail();pd.setCatalogId(catalogId);pd.setPlannedId(monthlyPlanned.getId());pd.setQuantity(itemQty);pd.setUpdatedTimestamp(LocalDateTime.now());plannedDetailRepository.persist(pd);} else {PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),catalogId);if (plannedDetail == null) {plannedDetail = new PlannedDetail();plannedDetail.setCatalogId(catalogId);plannedDetail.setPlannedId(monthlyPlanned.getId());plannedDetail.setQuantity(itemQty);plannedDetail.setUpdatedTimestamp(LocalDateTime.now());plannedDetailRepository.persist(plannedDetail);} else if (itemQty == 0) {plannedDetailRepository.delete(plannedDetail);} else {plannedDetail.setCatalogId(catalogId);plannedDetail.setQuantity(itemQty);plannedDetail.setUpdatedTimestamp(LocalDateTime.now());}}}@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)public String confirmOpenIndent(HttpServletRequest request,@RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {if (fofoId == 0) {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);fofoId = loginDetails.getFofoId();}CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);LocalDate currentDate = LocalDate.now();LocalDate planningMonthDate = null;MonthlyPlanned monthlyPlanned = null;if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);} else if (currentDate.isBefore(currentDate.withDayOfMonth(8))) {planningMonthDate = LocalDate.now().withDayOfMonth(1);monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);}model.addAttribute("response1", mvcResponseSender.createResponseString(true));return "response";}private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)throws Exception {List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());List<PlannedModel> plannedModel = new ArrayList<>();for (PlannedDetail plannedDetail : plannedDetails) {List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());String itemDesription = items.get(0).getItemDescriptionNoColor();PlannedModel pm = new PlannedModel();pm.setItemDescription(itemDesription);pm.setStoreName(customRetailer.getBusinessName());pm.setQty(plannedDetail.getQuantity());pm.setFofoId(fofoId);plannedModel.add(pm);LOGGER.info("plannedModel" + plannedModel);}List<String> ccemails = new ArrayList<>();LOGGER.info("ccemails" + ccemails);Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);LOGGER.info("emailEsclationType" + emailEsclationType);if (emailEsclationType.get(EscalationType.L1) != null) {ccemails.add(emailEsclationType.get(EscalationType.L1));}if (emailEsclationType.get(EscalationType.L2) != null) {ccemails.add(emailEsclationType.get(EscalationType.L2));}LOGGER.info("ccemails" + ccemails);List<String> bccemails = new ArrayList<>();bccemails.add(emailEsclationType.get(EscalationType.L3));LOGGER.info("bccemails" + bccemails);ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),plannedModel.stream().map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty())).collect(Collectors.toList()));LOGGER.info("baos" + baos);Utils.sendMailWithAttachments(googleMailSender, new String[]{customRetailer.getEmail()},ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),"Planned Indent", "PFA",new Attachment[]{new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())),});}@RequestMapping(value = "/indent/download", method = RequestMethod.GET)public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,@RequestParam(required = false, defaultValue = "0") int fofoId,@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);Set<Integer> roleIds = loginDetails.getRoleIds();LOGGER.info("Counter size is {}", counterSize);LOGGER.info("Fofo Id is {}", fofoId);if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,true);Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));Map<String, Integer> catalogUserQtyMap = new HashMap<>();currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {int retailerId = x.getFofoId();int catalogId;try {catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();String key = catalogId + "-" + retailerId;if (!catalogUserQtyMap.containsKey(key)) {catalogUserQtyMap.put(key, 0);}catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());} catch (ProfitMandiBusinessException e) {// TODO Auto-generated catch blockthrow 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 blockreturn "";}}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();List<TagListing> tagListings = tagListingRepository.selectAll(true);Iterator<TagListing> iterator = tagListings.iterator();while (iterator.hasNext()) {TagListing tagListing = iterator.next();Item item = itemRepository.selectById(tagListing.getItemId());int catalogId = item.getCatalogItemId();if (item.getCategoryId() != 10006) {continue;}int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)? modelStockAllocationMap.get(catalogId): 0;for (int retailerId : fofoIds) {String key = catalogId + "-" + retailerId;if (catalogListingMap.containsKey(key)) {continue;}int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {continue;}CatalogListingModel catalogListingModel = new CatalogListingModel();catalogListingModel.setFofoId(retailerId);catalogListingModel.setModelName(item.getModelName());catalogListingModel.setModelNumber(item.getModelNumber());catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);catalogListingModel.setInTransitQuantity(catalogInTransit);catalogListingModel.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);catalogListingModel.setStockInHand(catalogInStock);catalogListingModel.setBrand(item.getBrand());catalogListingModel.setModelName(item.getModelName());catalogListingModel.setModelNumber(item.getModelNumber());catalogListingModel.setCategoryId(item.getCategoryId());catalogListingMap.put(key, catalogListingModel);}}List<List<?>> listOfRows = new ArrayList<>();for (CatalogListingModel clm : catalogListingMap.values()) {CustomRetailer cr = crm.get(clm.getFofoId());listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),clm.getToBeOrdered()));}ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number","DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),listOfRows);HttpHeaders headers = new HttpHeaders();headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,HttpStatus.OK);}return null;}@RequestMapping(value = "/itemsByCatalogId")public String getItemsByCatalogId(HttpServletRequest request, Model model,@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)throws ProfitMandiBusinessException {if (catalogId == 0) {catalogId = itemRepository.selectById(itemId).getCatalogItemId();}List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);LOGGER.info("Items {}", items);Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_")).collect(Collectors.toMap(Item::getId, Item::getColor));Map<Integer, TagListing> tagsMap = tagListingRepository.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags).stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));LOGGER.info("Items color map {}", itemsColorMap);JSONArray response = new JSONArray();itemsColorMap.keySet().stream().forEach(x -> {response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));});model.addAttribute("response1", response.toString());return "response";}@RequestMapping(value = "/hotdealsitemsByCatalogId")public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)throws ProfitMandiBusinessException {if (catalogId == 0) {catalogId = itemRepository.selectById(itemId).getCatalogItemId();}List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);LOGGER.info("Items {}", items);Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_")).collect(Collectors.toMap(Item::getId, Item::getColor));Map<Integer, TagListing> tagsMap = tagListingRepository.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags).stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));LOGGER.info("Items color map {}", itemsColorMap);JSONArray response = new JSONArray();itemsColorMap.keySet().stream().forEach(x -> {response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));});model.addAttribute("response1", response.toString());return "response";}private List<Order> filterValidOrders(List<Order> lastOrdersList) {int orderRemovedCount = 0;Iterator<Order> orderIterator = lastOrdersList.iterator();while (orderIterator.hasNext()) {Order o = orderIterator.next();if (o.getInvoiceNumber() != null) {try {purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());orderIterator.remove();orderRemovedCount++;} catch (Exception e) {}}}LOGGER.info("Order removed count is {}", orderRemovedCount);return lastOrdersList;}// Clean up the saholic cis table@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)public String updateTagListing(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)throws Exception {JSONArray jsonArray = new JSONArray(jsonArrayString);Set<Integer> updatedCatalogIds = new HashSet<>();for (int i = 0; i < jsonArray.length(); i++) {JSONObject obj = jsonArray.getJSONObject(i);int itemId = obj.getInt("id");TagListing tl = tagListingRepository.selectByItemId(itemId);if (tl == null) {continue;} else {tl.setActive(obj.getBoolean("active"));if (!tl.isActive()) {saholicCISTableRepository.selectAllByItemId(tl.getItemId()).stream().forEach(x -> saholicCISTableRepository.delete(x));}// Collect catalogIds for Solr updatestry {Item item = itemRepository.selectById(itemId);updatedCatalogIds.add(item.getCatalogItemId());} catch (Exception e) {LOGGER.error("Failed to get catalogId for itemId: {}", itemId, e);}}}// Publish events for all updated catalogsfor (Integer catalogId : updatedCatalogIds) {try {tagListingEventPublisher.publishStatusChange(0, catalogId);} catch (Exception e) {LOGGER.error("Failed to publish status change event for catalogId: {}", catalogId, e);}}model.addAttribute("response1", true);return "response";}@RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)throws Exception {JSONArray jsonArray = new JSONArray(jsonArrayString);Set<Integer> updatedCatalogIds = new HashSet<>();for (int i = 0; i < jsonArray.length(); i++) {JSONObject obj = jsonArray.getJSONObject(i);int itemId = obj.getInt("id");TagListing tl = tagListingRepository.selectByItemId(itemId);if (tl == null) {continue;} else {tl.setHotDeals(obj.getBoolean("hotDeals"));tagListingRepository.persist(tl);// Collect catalogIds for Solr updatestry {Item item = itemRepository.selectById(itemId);updatedCatalogIds.add(item.getCatalogItemId());} catch (Exception e) {LOGGER.error("Failed to get catalogId for itemId: {}", itemId, e);}}}// Publish events for all updated catalogsfor (Integer catalogId : updatedCatalogIds) {try {tagListingEventPublisher.publishStatusChange(0, catalogId);} catch (Exception e) {LOGGER.error("Failed to publish status change event for catalogId: {}", catalogId, e);}}model.addAttribute("response1", true);return "response";}private void createPayment(User user, double totalAmount, long transactionId)throws NumberFormatException, PaymentException, TException {List<Attribute> paymentAttributes = new ArrayList<Attribute>();in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();paymentAttributes.add(new Attribute("payMethod", "7890"));long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,false);paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,PaymentStatus.SUCCESS, null, paymentAttributes);}@RequestMapping(value = "/indent/loadIndent")public String loadOpenIndent(HttpServletRequest request, Model model,@RequestParam(required = false, defaultValue = "0") int fofoId,@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);Set<Integer> roleIds = loginDetails.getRoleIds();LOGGER.info("Counter size is {}", counterSize);LOGGER.info("Fofo Id is {}", fofoId);boolean isAdmin = roleManager.isAdmin(roleIds);List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).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 if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {planningMonthDate = LocalDate.now().withDayOfMonth(8);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().getMonth());} else {planningMonthDate = LocalDate.now().withDayOfMonth(1);LocalDateTime curDate = LocalDate.now().atStartOfDay();monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);model.addAttribute("planningMonth", planningMonthDate.getMonth());model.addAttribute("mtd", true);model.addAttribute("freezed", true);fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId()).collect(Collectors.toList());LOGGER.info("monthlyPlanned1" + monthlyPlanned);}Map<Integer, Integer> plannedDetailMap = null;if (monthlyPlanned != null) {plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));}LOGGER.info("plannedDetailMap" + plannedDetailMap);LOGGER.info("fofoOrderIds" + fofoOrderIds);Map<String, Object> equalsJoinMap = new HashMap<>();equalsJoinMap.put("orderId", fofoOrderIds);Map<Integer, Integer> last15daysMap = null;if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {last15daysMap = itemRepository.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,notEqualsJoinMap, "quantity").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));}LOGGER.info("last15daysMap" + last15daysMap);Map<Integer, TagListing> taglistingMap = tagListings.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));LOGGER.info("catalogIdItemMap");Map<String, Object> equalsItemJoinMap = new HashMap<>();equalsItemJoinMap.put("active", 1);List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id","itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");LOGGER.info("tagListingCatalogIds");for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {int catalogId = catalogIdAggregateValue.getCatalogId();Item item = catalogIdItemMap.get(catalogId).get(0);TagListing tagListing = taglistingMap.get(item.getId());CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);if (!catalogListingMap.containsKey(catalogId)) {catalogListingModel = new CatalogListingModel();catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());if (plannedDetailMap != null) {Integer quantity = plannedDetailMap.get(catalogId);if (quantity != null) {catalogListingModel.setAllocatedQuantity(quantity);}}if (last15daysMap != null) {Integer last15DaysSale = last15daysMap.get(catalogId);if (last15DaysSale != null) {catalogListingModel.setLast15DaysSale(last15DaysSale);} else {catalogListingModel.setLast15DaysSale(0);}} else {catalogListingModel.setLast15DaysSale(0);}catalogListingModel.setBrand(item.getBrand());if (item.getCategoryId() == 10006) {catalogListingModel.setCategoryId(item.getCategoryId());}FocusedModel fm = focusedModelMap.get(catalogId);if (fm != null) {catalogListingModel.setRecommendedQty(fm.getRecommendedQty());catalogListingModel.setMinimumQty(fm.getMinimumQty());} else {catalogListingModel.setRecommendedQty(0);catalogListingModel.setMinimumQty(0);}catalogListingMap.put(catalogId, catalogListingModel);}int itemAvailability = 0;if (currentStockMap != null) {Integer qty = currentStockMap.get(catalogId);itemAvailability = qty == null ? 0 : qty;catalogListingModel.setStockInHand(itemAvailability);} else {catalogListingModel.setStockInHand(0);}Integer inTransitQuantity = itemsInTransit.get(item.getId());int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);if (plannedDetailMap != null) {if (plannedDetailMap.get(catalogId) != null) {int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();LOGGER.info("remaning" + remaining);if (remaining != 0) {catalogListingModel.setRemaining(remaining);} else {catalogListingModel.setRemaining(0);}}}}Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);if (fofoId > 0) {CustomRetailer customRetailer = customRetailersMap.get(fofoId);model.addAttribute("retailerName",customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);model.addAttribute("retailerId", customRetailer.getPartnerId());model.addAttribute("counterSize", fs.getCounterSize().toString());} else {model.addAttribute("counterSize", counterSize.toString());}String customRetailers = JSONObject.valueToString(customRetailersMap.values());List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,Comparator.reverseOrder());LOGGER.info("monthlyPlanned" + monthlyPlanned);model.addAttribute("catalogTagListings",catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());model.addAttribute("customRetailers", customRetailers);model.addAttribute("totalAmount", totalAmount);model.addAttribute("monthlyPlanned", monthlyPlanned);model.addAttribute("totalPcs", totalPcs);return "open-indent";}private long resetCart(Transaction transaction) {long sum = 0;Map<Long, Double> items = new HashMap<Long, Double>();for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {sum += order.getGvAmount();for (LineItem lineitem : order.getLineitems()) {Long itemId = lineitem.getItem_id();Double quantity = items.get(itemId);if (quantity == null) {quantity = lineitem.getQuantity();} else {quantity = quantity + lineitem.getQuantity();}items.put(itemId, quantity);}}LOGGER.debug("Items to reset in cart are: " + items);try {Client userClient = new UserClient().getClient();userClient.resetCart(transaction.getShoppingCartid(), items);} catch (TException e) {LOGGER.error("Error while updating information in payment database.", e);} catch (ShoppingCartException e) {LOGGER.error("Error while reseting the cart in cart database.", e);} catch (Exception e) {LOGGER.error("Unexpected exception", e);}return sum;}private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {List<ItemPriceQuantity> itemQuantities = new ArrayList<>();/** Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>* currentInventorySnapshots = currentInventorySnapshotRepository* .selectItemsStock(fofoId); itemCisMap =* currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)* .collect(Collectors.toMap(x -> x.getItemId(), x -> x));* List<StockAllocationModel> stockAllocationList =* stockAllocationService.getStockAllocation(fofoId, true);** Map<Integer, StockAllocationModel> itemStockAllocationMap =* stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x* -> x)); Map<Integer, Integer> itemsInTransit = null;* LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);* List<TagListing> tagListings = tagListingRepository.selectAll(false);* List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,* validOrderStatusList); inTransitOrders =* this.filterValidOrders(inTransitOrders); itemsInTransit =* inTransitOrders.stream().collect(Collectors.groupingBy(x ->* x.getLineItem().getItemId(), Collectors.summingInt(x ->* x.getLineItem().getQuantity())));** Iterator<TagListing> iterator = tagListings.iterator();** int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =* iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",* tagListing.getAllocatedQuantity()); if* (!itemCisMap.containsKey(tagListing.getItemId()) &&* !itemStockAllocationMap.containsKey(tagListing.getItemId())) {* iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =* itemCisMap.get(tagListing.getItemId());* tagListing.setStockInHand(itemIdAvailability == null ? 0 :* itemIdAvailability.getAvailability()); StockAllocationModel* stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());** if (itemsInTransit.containsKey(tagListing.getItemId())) {* tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));* } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=* null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());* toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -* tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if* (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();* ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);* ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }*/return itemQuantities;}@RequestMapping(value = "/indent/loadIndentPreviousMonth")public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,@RequestParam(required = false, defaultValue = "0") int fofoId,@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {LocalDate planMonthStart = null;if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);} else {planMonthStart = LocalDate.now().withDayOfMonth(1);}LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);Set<Integer> roleIds = loginDetails.getRoleIds();LOGGER.info("Counter size is {}", counterSize);LOGGER.info("Fofo Id is {}", fofoId);boolean isAdmin = roleManager.isAdmin(roleIds);List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());Map<String, Object> equalsMap = new HashMap<>();equalsMap.put("categoryId", 10006);equalsMap.put("brand", brands);Map<String, List<?>> notEqualsMap = new HashMap<>();Map<String, List<?>> notEqualsJoinMap = new HashMap<>();Map<Integer, Integer> currentStockMap;if (!isAdmin && fofoId == 0) {fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));LOGGER.info("currentStock");} else {if (fofoId == 0) {Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));} else {Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));}}LOGGER.info("currentStock" + currentStockMap);Map<Integer, Integer> itemsInTransit = null;List<TagListing> tagListings = tagListingRepository.selectAll(true);if (!isAdmin) {tagListings = new ArrayList<>(tagListings);List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,OrderRepository.validOrderStatusList);inTransitOrders = this.filterValidOrders(inTransitOrders);itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),Collectors.summingInt(x -> x.getLineItem().getQuantity())));} else {itemsInTransit = new HashMap<>();}int totalPcs = 0;float totalAmount = 0;Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream().collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,planMonthStart.minusMonths(1));model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());Map<Integer, Integer> plannedDetailMap = null;if (monthlyPlanned != null) {plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));}LOGGER.info("plannedDetailMap" + plannedDetailMap);List<Integer> fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay()).stream().map(x -> x.getId()).collect(Collectors.toList());LOGGER.info("fofoOrderIds" + fofoOrderIds);Map<String, Object> equalsJoinMap = new HashMap<>();equalsJoinMap.put("orderId", fofoOrderIds);Map<Integer, Integer> lastMonthSaleMap = null;if (!fofoOrderIds.isEmpty()) {lastMonthSaleMap = itemRepository.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,notEqualsJoinMap, "quantity").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));}LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);Map<Integer, TagListing> taglistingMap = tagListings.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));LOGGER.info("catalogIdItemMap");Map<String, Object> equalsItemJoinMap = new HashMap<>();equalsItemJoinMap.put("active", 1);List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id","itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");LOGGER.info("tagListingCatalogIds");for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {int catalogId = catalogIdAggregateValue.getCatalogId();Item item = catalogIdItemMap.get(catalogId).get(0);TagListing tagListing = taglistingMap.get(item.getId());CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);if (!catalogListingMap.containsKey(catalogId)) {catalogListingModel = new CatalogListingModel();catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());if (plannedDetailMap != null) {Integer quantity = plannedDetailMap.get(catalogId);if (quantity != null) {catalogListingModel.setAllocatedQuantity(quantity);}}if (lastMonthSaleMap != null) {Integer lastMonthSale = lastMonthSaleMap.get(catalogId);if (lastMonthSale != null) {catalogListingModel.setLastMonthSaleMap(lastMonthSale);} else {catalogListingModel.setLastMonthSaleMap(0);}} else {catalogListingModel.setLast15DaysSale(0);}catalogListingModel.setBrand(item.getBrand());if (item.getCategoryId() == 10006) {catalogListingModel.setCategoryId(item.getCategoryId());}FocusedModel fm = focusedModelMap.get(catalogId);if (fm != null) {catalogListingModel.setRecommendedQty(fm.getRecommendedQty());catalogListingModel.setMinimumQty(fm.getMinimumQty());} else {catalogListingModel.setRecommendedQty(0);catalogListingModel.setMinimumQty(0);}catalogListingMap.put(catalogId, catalogListingModel);}int itemAvailability = 0;if (currentStockMap != null) {Integer qty = currentStockMap.get(catalogId);itemAvailability = qty == null ? 0 : qty;catalogListingModel.setStockInHand(itemAvailability);} else {catalogListingModel.setStockInHand(0);}Integer inTransitQuantity = itemsInTransit.get(item.getId());int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);}Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);if (fofoId > 0) {CustomRetailer customRetailer = customRetailersMap.get(fofoId);model.addAttribute("retailerName",customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);model.addAttribute("retailerId", customRetailer.getPartnerId());model.addAttribute("counterSize", fs.getCounterSize().toString());} else {model.addAttribute("counterSize", counterSize.toString());}String customRetailers = JSONObject.valueToString(customRetailersMap.values());List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,Comparator.reverseOrder());LOGGER.info("monthlyPlanned" + monthlyPlanned);model.addAttribute("catalogTagListings",catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));model.addAttribute("previousMonth", true);model.addAttribute("freezed", true);model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));model.addAttribute("customRetailers", customRetailers);model.addAttribute("totalAmount", totalAmount);model.addAttribute("monthlyPlanned", monthlyPlanned);model.addAttribute("totalPcs", totalPcs);return "open-indent";}private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {Map<Integer, Item> itemMap = new HashMap<>();for (FocusedModel focusedModel : focusedModels) {List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());itemMap.put(items.get(0).getCatalogItemId(), items.get(0));}return itemMap;}private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {Map<Integer, Region> regionMap = new HashMap<>();for (FocusedModel focusedModel : focusedModels) {Region region = regionRepository.selectById(focusedModel.getRegionId());regionMap.put(region.getId(), region);}return regionMap;}@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)public String getFocusedModel(HttpServletRequest request,@RequestParam(name = "offset", defaultValue = "0") int offset,@RequestParam(name = "limit", defaultValue = "0") int limit, Model model)throws ProfitMandiBusinessException {long size = 0;List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);Collections.reverse(focusedModels);size = focusedModelRepository.selectAllCount();if (!focusedModels.isEmpty()) {Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);LOGGER.info("regionMap" + regionMap);model.addAttribute("focusedModels", focusedModels);model.addAttribute("itemMap", itemMap);model.addAttribute("regionMap", regionMap);model.addAttribute("start", offset + 1);model.addAttribute("size", size);model.addAttribute("url", "/getPaginatedFocusedModel");if (focusedModels.size() < limit) {model.addAttribute("end", offset + focusedModels.size());} else {model.addAttribute("end", offset + limit);}} else {model.addAttribute("walletRequest", focusedModels);model.addAttribute("size", size);}List<Region> regions = regionRepository.selectAll();model.addAttribute("regions", regions);return "focused_model";}@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)public String getPaginatedFocusedModel(HttpServletRequest request,@RequestParam(name = "offset", defaultValue = "0") int offset,@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)throws ProfitMandiBusinessException {LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);if (!focusedModels.isEmpty()) {Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);model.addAttribute("focusedModels", focusedModels);model.addAttribute("itemMap", itemMap);model.addAttribute("regionMap", regionMap);model.addAttribute("url", "/getPaginatedFocusedModel");} else {model.addAttribute("focusedModels", focusedModels);}List<Region> regions = regionRepository.selectAll();model.addAttribute("regions", regions);return "focused-model-paginated";}private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);List<BrandCatalog> mobileBrands = brandsService.getBrands(fofoId, null, 3);List<BrandStockPrice> brandStockPrices = new ArrayList<>();mobileBrands.stream().forEach(x -> {String brand = x.getName();if (brandStockPricesMap.containsKey(brand)) {BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);brandStockPrice.setBrandUrl(x.getLogoUrl());brandStockPrice.setRank(x.getBrandCategory().getRank());brandStockPrices.add(brandStockPrice);}});return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank()).collect(Collectors.toList());}@RequestMapping(value = "/getPartnerAllocation")public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();List<Integer> fofoIds = pp.get(authUser.getId());Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));model.addAttribute("customRetailersMap", crm);model.addAttribute("fofoStoreMap", fofoStoreMap);return "partners_allocation";}@RequestMapping(value = "/partnerPendingOrder")public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();List<Integer> fofoIds = pp.get(authUser.getId());Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));model.addAttribute("customRetailersMap", crm);return "partner-po";}@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,@RequestParam(name = "recommended", defaultValue = "0") int recommended,@RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,@RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,@RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,Model model) throws ProfitMandiBusinessException {FocusedModel fm = new FocusedModel();fm.setCatalogId(catalogId);fm.setMinimumQty(minimumQty);fm.setRecommendedQty(recommended);fm.setRegionId(regionId);fm.setObsRecommendedQty(obvrecommend);fm.setObsMinimumQty(obvminimum);fm.setCreatedTimestamp(LocalDateTime.now());focusedModelRepository.persist(fm);return "focused_model";}@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)public String removeFocusedModelItem(HttpServletRequest request,@RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {focusedModelRepository.deleteById(id);model.addAttribute("response1", mvcResponseSender.createResponseString(true));return "response";}@RequestMapping(value = "/getPartnerloadContent")public String getPartnerloadContent(HttpServletRequest request, Model model,@RequestParam(required = false, defaultValue = "0") int fofoId,@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);Set<Integer> roleIds = loginDetails.getRoleIds();LOGGER.info("Counter size is {}", counterSize);LOGGER.info("Fofo Id is {}", fofoId);boolean isAdmin = roleManager.isAdmin(roleIds);List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());Map<String, Object> equalsMap = new HashMap<>();equalsMap.put("categoryId", 10006);equalsMap.put("brand", brands);Map<String, List<?>> notEqualsMap = new HashMap<>();Map<String, List<?>> notEqualsJoinMap = new HashMap<>();Map<Integer, Integer> currentStockMap;if (!isAdmin && fofoId == 0) {fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));LOGGER.info("currentStock");} else {if (fofoId == 0) {Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));} else {Map<String, Object> equalsStockJoinMap = new HashMap<>();equalsStockJoinMap.put("fofoId", fofoId);currentStockMap = itemRepository.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,equalsStockJoinMap, notEqualsJoinMap, "availability").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));}}FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);LOGGER.info("currentStock" + currentStockMap);Map<Integer, Integer> itemsInTransit = null;List<TagListing> tagListings = tagListingRepository.selectAll(true);if (!isAdmin) {tagListings = new ArrayList<>(tagListings);List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,OrderRepository.validOrderStatusList);inTransitOrders = this.filterValidOrders(inTransitOrders);itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),Collectors.summingInt(x -> x.getLineItem().getQuantity())));} else {itemsInTransit = new HashMap<>();}int totalPcs = 0;float totalAmount = 0;Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream().collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));LocalDate currentMonthDate = LocalDate.now();MonthlyPlanned monthlyPlanned = null;List<Integer> fofoOrderIds = null;LOGGER.info("localDate" + LocalDate.now());if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);LOGGER.info("monthlyPlanned2" + monthlyPlanned);fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId()).collect(Collectors.toList());model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());} else {currentMonthDate = LocalDate.now().withDayOfMonth(1);LocalDateTime curDate = LocalDate.now().atStartOfDay();monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);model.addAttribute("planningMonth", currentMonthDate.getMonth());model.addAttribute("mtd", true);model.addAttribute("freezed", true);fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId()).collect(Collectors.toList());LOGGER.info("monthlyPlanned1" + monthlyPlanned);}Map<Integer, Integer> plannedDetailMap = null;if (monthlyPlanned != null) {plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));}LOGGER.info("plannedDetailMap" + plannedDetailMap);LOGGER.info("fofoOrderIds" + fofoOrderIds);Map<String, Object> equalsJoinMap = new HashMap<>();equalsJoinMap.put("orderId", fofoOrderIds);Map<Integer, Integer> last15daysMap = null;if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {last15daysMap = itemRepository.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,notEqualsJoinMap, "quantity").stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));}LOGGER.info("last15daysMap" + last15daysMap);Map<Integer, TagListing> taglistingMap = tagListings.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));LOGGER.info("catalogIdItemMap");Map<String, Object> equalsItemJoinMap = new HashMap<>();equalsItemJoinMap.put("active", 1);List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id","itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");Map<Integer, Integer> ourStockAvailability = new HashMap<>();Map<Integer, List<Integer>> catalogItemIdMap = itemRepository.selectAllByCatalogIds(new HashSet<>(tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList()))).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),Collectors.mapping(y -> y.getId(), Collectors.toList())));for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {List<Integer> itemIds = catalogItem.getValue();int availability = 0;for (Integer itemId : itemIds) {List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId,fofoStore.getWarehouseId());if (saholicCISTableList != null) {availability += saholicCISTableList.stream().collect(Collectors.summingInt(x -> x.getAvailability()));}}Integer catalogItemId = catalogItem.getKey();ourStockAvailability.put(catalogItemId, availability);}LOGGER.info("ourStockAvailability" + ourStockAvailability);for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {int catalogId = catalogIdAggregateValue.getCatalogId();Item item = catalogIdItemMap.get(catalogId).get(0);TagListing tagListing = taglistingMap.get(item.getId());CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);if (!catalogListingMap.containsKey(catalogId)) {catalogListingModel = new CatalogListingModel();catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());if (plannedDetailMap != null) {Integer quantity = plannedDetailMap.get(catalogId);if (quantity != null) {catalogListingModel.setAllocatedQuantity(quantity);}}if (last15daysMap != null) {Integer last15DaysSale = last15daysMap.get(catalogId);if (last15DaysSale != null) {catalogListingModel.setLast15DaysSale(last15DaysSale);} else {catalogListingModel.setLast15DaysSale(0);}} else {catalogListingModel.setLast15DaysSale(0);}catalogListingModel.setBrand(item.getBrand());if (item.getCategoryId() == 10006) {catalogListingModel.setCategoryId(item.getCategoryId());}Integer ourStock = ourStockAvailability.get(catalogId);LOGGER.info("catalogId" + catalogId);LOGGER.info("ourStock" + ourStock);if (ourStock != null) {catalogListingModel.setOurStockQty(ourStock);}FocusedModel fm = focusedModelMap.get(catalogId);if (fm != null) {catalogListingModel.setRecommendedQty(fm.getRecommendedQty());catalogListingModel.setMinimumQty(fm.getMinimumQty());catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());} else {catalogListingModel.setRecommendedQty(0);catalogListingModel.setMinimumQty(0);catalogListingModel.setObsRecommendedQty(0);catalogListingModel.setObsMinimumQty(0);}catalogListingMap.put(catalogId, catalogListingModel);}int itemAvailability = 0;if (currentStockMap != null) {Integer qty = currentStockMap.get(catalogId);itemAvailability = qty == null ? 0 : qty;catalogListingModel.setStockInHand(itemAvailability);} else {catalogListingModel.setStockInHand(0);}Integer inTransitQuantity = itemsInTransit.get(item.getId());int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);if (plannedDetailMap != null) {if (plannedDetailMap.get(catalogId) != null) {int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();LOGGER.info("remaning" + remaining);if (remaining != 0) {catalogListingModel.setRemaining(remaining);} else {catalogListingModel.setRemaining(0);}}}}Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);if (fofoId > 0) {CustomRetailer customRetailer = customRetailersMap.get(fofoId);model.addAttribute("retailerName",customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);model.addAttribute("retailerId", customRetailer.getPartnerId());model.addAttribute("counterSize", fs.getCounterSize().toString());} else {model.addAttribute("counterSize", counterSize.toString());}String customRetailers = JSONObject.valueToString(customRetailersMap.values());List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,Comparator.reverseOrder());LOGGER.info("monthlyPlanned" + monthlyPlanned);model.addAttribute("catalogTagListings",catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());model.addAttribute("customRetailers", customRetailers);model.addAttribute("totalAmount", totalAmount);model.addAttribute("monthlyPlanned", monthlyPlanned);model.addAttribute("totalPcs", totalPcs);UserWallet userWallet = walletService.getUserWallet(fofoId);model.addAttribute("userWallet", userWallet);return "create-partner-po";}@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)throws Exception {List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);List<Item> items = new ArrayList<>();for (Item item : selecteditems) {TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);if (tagListing != null) {items.add(item);}}model.addAttribute("items", items);LOGGER.info("itemIdAndColorMap" + items);return "select-item-color";}List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com","niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "vikas.jangra@smartdukaan.com");@Autowiredprivate PositionRepository positionRepository;@Autowiredprivate PartnerTypeChangeService partnerTypeChangeService;@Autowiredprivate com.spice.profitmandi.service.transaction.TransactionService transactionService;@Autowiredprivate CategoryRepository categoryRepository;@Autowiredprivate BrandLimitRepository brandLimitRepository;private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,OrderStatus.ACCEPTED);public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();static {Brand_Amount_Limit.put("accessories", 10000.00);Brand_Amount_Limit.put("TV", 27000.00);}@RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);String email = loginDetails.getEmailId();List<String> brands = ProfitMandiConstants.BRANDS;AuthUser authUser = authRepository.selectByEmailOrMobile(email);Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();Map<Integer, Map<String, Double>> fofoIdBrandQtyMap = new HashMap<>();Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();Map<Integer, InStockAccessoriesTvQtyFofoIdModel> inStockQtyAccessTv = new HashMap<>();Map<Integer, InStockAccessoriesTvQtyFofoIdModel> pendingIndentQtyAccessTv = new HashMap<>();Map<Integer, InStockAccessoriesTvQtyFofoIdModel> grnPendingQtyAccessTvOrders = new HashMap<>();Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();Map<Integer, CustomRetailer> customRetailers = new HashMap<>();Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();if (fofoIds != null && fofoIds.size() > 0) {List<Integer> fofoIdList = new ArrayList<>(fofoIds);Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));//Only L3 and above can change the accessTypeboolean canChangeActionType = positionRepository.selectAllByAuthUserId(authUser.getId()).stream().filter(x -> x.getEscalationType().isGreaterThanEqualTo(EscalationType.L3)).count() > 0;model.addAttribute("canChangeActivationType", canChangeActionType);model.addAttribute("partnerActivationType", partnerActivationType);model.addAttribute("activationTypes", ActivationType.values());Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit().stream().collect(Collectors.groupingBy(x -> x.getFofoId(),Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));Map<Integer, Map<String, Double>> inStockBrandModel;Map<Integer, Map<String, Double>> inStockBrandModelQty;Map<Integer, Map<String, Double>> pendingIndent;Map<Integer, Map<String, Double>> pendingIndentQty;Map<Integer, Map<String, Double>> grnPendingOrders;Map<Integer, Map<String, Double>> grnPendingOrdersQty;// mobileList<InStockBrandFofoIdModel> inStockBrandFofoIdModels = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList);inStockBrandModel = inStockBrandFofoIdModels.stream().collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));inStockBrandModelQty = inStockBrandFofoIdModels.stream().collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,Collectors.summingDouble(InStockBrandFofoIdModel::getQty))));List<Order> pendingIndentOrders = transactionService.getInTransitOrders(fofoIdList);pendingIndent = pendingIndentOrders.stream().filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID).collect(Collectors.groupingBy(x -> x.getRetailerId(),Collectors.groupingBy(y -> y.getLineItem().getBrand(),Collectors.summingDouble(y -> (double) y.getTotalAmount()))));pendingIndentQty = pendingIndentOrders.stream().filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID).collect(Collectors.groupingBy(x -> x.getRetailerId(),Collectors.groupingBy(y -> y.getLineItem().getBrand(),Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));List<Order> grnPendingOrderList = orderRepository.selectPendingGrnOrders(fofoIdList);grnPendingOrders = grnPendingOrderList.stream().filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID).collect(Collectors.groupingBy(x -> x.getRetailerId(),Collectors.groupingBy(y -> y.getLineItem().getBrand(),Collectors.summingDouble(y -> (double) y.getTotalAmount()))));grnPendingOrdersQty = grnPendingOrderList.stream().filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID).collect(Collectors.groupingBy(x -> x.getRetailerId(),Collectors.groupingBy(y -> y.getLineItem().getBrand(),Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));// accessoriesinStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));inStockQtyAccessTv = currentInventorySnapshotRepository.selectQtySumInStockAccessoriesAndTv(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));pendingIndentQtyAccessTv = orderRepository.selectAllQtyPendingIndentAccessoriesTvGroupByFofoId(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));grnPendingQtyAccessTvOrders = orderRepository.selectAllQtyGrnPendingAccessoriesTvGroupByFofoId(fofoIdList).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));// Bulk fetch partner types to avoid N+1 queriesfofoIdPartnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(customRetailers.keySet()), LocalDate.now());for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());Map<String, Double> stockBrandQty = inStockBrandModelQty.get(customRetailer.getKey());Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());Map<String, Double> pendingIndentBrandQty = pendingIndentQty.get(customRetailer.getKey());Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());Map<String, Double> grnBrandQty = grnPendingOrdersQty.get(customRetailer.getKey());double totalAmount = 0;double totalQty = 0;Map<String, Double> brandAmountMap = new HashMap<>();Map<String, Double> brandQtyMap = new HashMap<>();for (String brand : brands) {double stockValue = 0;double stockQty = 0;double pendingValue = 0;double pendingQty = 0;double grnValue = 0;double grnQty = 0;if (stockBrand != null) {if (stockBrand.get(brand) != null) {stockValue = stockBrand.get(brand);}}if (stockBrandQty != null) {if (stockBrandQty.get(brand) != null) {stockQty = stockBrandQty.get(brand);}}if (pendingIndentBrand != null) {if (pendingIndentBrand.get(brand) != null) {pendingValue = pendingIndentBrand.get(brand);}}if (pendingIndentBrandQty != null) {if (pendingIndentBrandQty.get(brand) != null) {pendingQty = pendingIndentBrandQty.get(brand);}}if (grnBrand != null) {if (grnBrand.get(brand) != null) {grnValue = grnBrand.get(brand);}}if (grnBrandQty != null) {if (grnBrandQty.get(brand) != null) {grnQty = grnBrandQty.get(brand);}}totalAmount = stockValue + pendingValue + grnValue;totalQty = stockQty + pendingQty + grnQty;brandAmountMap.put(brand, totalAmount);brandQtyMap.put(brand, totalQty);}fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);fofoIdBrandQtyMap.put(customRetailer.getKey(), brandQtyMap);}List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));if (!partnerDailyInvestments.isEmpty()) {partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));}}Map<Integer, MonthlyTarget> fofoIdMonthlyTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(YearMonth.now(), new ArrayList<>(fofoIds)).stream().collect(Collectors.toMap(MonthlyTarget::getFofoId, x -> x,(existing, replacement) -> replacement // Keep the last entry));Map<Integer, Float> fofoMTDSaleMap = fofoOrderRepository.selectSaleSumGroupByFofoIds(YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now());Map<Integer, Double> currentMonthTillDateRetailerPOValueMap = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(new ArrayList<>(fofoIds),Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));List<Loan> loans = loanRepository.selectAllActiveLoan().stream().filter(x -> fofoIds.contains(x.getFofoId())).collect(Collectors.toList());Map<Integer, List<Loan>> loanMap = loans.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toList()));Map<Integer, BigDecimal> totalDueMap = new HashMap<>();for (Entry<Integer, List<Loan>> fofoIdLoanEntry : loanMap.entrySet()) {List<Loan> Loans = fofoIdLoanEntry.getValue();int fofoId = fofoIdLoanEntry.getKey();BigDecimal totalDue = new BigDecimal(0);for (Loan loan : Loans) {BigDecimal pendingAmount = loan.getPendingAmount();BigDecimal interestAccrued = loan.getInterestAccrued();BigDecimal interestPaid = loan.getInterestPaid();totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));}totalDueMap.put(fofoId, totalDue);}//Only L3 and above can change the activationTypemodel.addAttribute("customRetailers", customRetailers);model.addAttribute("totalDueMap", totalDueMap);model.addAttribute("fofoMTDSaleMap", fofoMTDSaleMap);model.addAttribute("fofoIdMonthlyTargetMap", fofoIdMonthlyTargetMap);model.addAttribute("currentMonthTillDateRetailerPOValueMap", currentMonthTillDateRetailerPOValueMap);//LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);model.addAttribute("brands", brands);model.addAttribute("brandAmountLimit", Brand_Amount_Limit);model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);model.addAttribute("fofoIdBrandQtyMap", fofoIdBrandQtyMap);model.addAttribute("inStockAccessTv", inStockAccessTv);model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);model.addAttribute("inStockQtyAccessTv", inStockQtyAccessTv);model.addAttribute("pendingIndentQtyAccessTv", pendingIndentQtyAccessTv);model.addAttribute("grnPendingQtyAccessTvOrders", grnPendingQtyAccessTvOrders);model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);return "partner-brandwise-detail";}@RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)public String changeActivationType(HttpServletRequest request, @RequestParam String code,@RequestParam ActivationType activationType, Model model) throws Exception {FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);fofoStore.setActivationType(activationType);model.addAttribute("response1", mvcResponseSender.createResponseString(true));return "response";}@RequestMapping(value = "/createPo", method = RequestMethod.POST)public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);SuggestedPo mp = new SuggestedPo();mp.setFofoId(monthlyPoModel.getFofoId());mp.setCreateTimestamp(LocalDateTime.now());mp.setStatus("open");mp.setAuthId(loginDetails.getEmailId());suggestedPoRepository.persist(mp);for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {SuggestedPoDetail mpd = new SuggestedPoDetail();mpd.setItemId(poId.getItemId());mpd.setQuantity(poId.getQty());mpd.setUpdatedTimestamp(LocalDateTime.now());mpd.setPoId(mp.getId());suggestedPoDetailRepository.persist(mpd);}SendNotificationModel sendNotificationModel = new SendNotificationModel();sendNotificationModel.setCampaignName("Alert");sendNotificationModel.setMessage("Suggested Po");sendNotificationModel.setType("url");sendNotificationModel.setTitle("Alert");sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));sendNotificationModel.setMessageType(MessageType.notification);int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());sendNotificationModel.setUserIds(Arrays.asList(userId));notificationService.sendNotification(sendNotificationModel);model.addAttribute("response1", mvcResponseSender.createResponseString(true));return "response";}@RequestMapping(value = "/createSuggestedPo", method = RequestMethod.POST)public String createSuggestedPo(HttpServletRequest request, @RequestBody List<SuggestedPoCatalogModel> poCatalogModel, @RequestParam int fofoId, Model model)throws Exception {LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);List<SuggestedPo> suggestedPos = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId);for (SuggestedPo suggestedPo : suggestedPos) {suggestedPo.setStatus("closed");}SuggestedPo mp = new SuggestedPo();mp.setFofoId(fofoId);mp.setCreateTimestamp(LocalDateTime.now());mp.setStatus("open");mp.setAuthId(loginDetails.getEmailId());suggestedPoRepository.persist(mp);for (SuggestedPoCatalogModel catalogModel : poCatalogModel) {SuggestedPoDetail mpd = new SuggestedPoDetail();mpd.setItemId(catalogModel.getItemId());mpd.setQuantity(catalogModel.getQty());mpd.setUpdatedTimestamp(LocalDateTime.now());mpd.setPoId(mp.getId());suggestedPoDetailRepository.persist(mpd);}SendNotificationModel sendNotificationModel = new SendNotificationModel();sendNotificationModel.setCampaignName("Alert");sendNotificationModel.setMessage("Suggested Po");sendNotificationModel.setType("url");sendNotificationModel.setTitle("Alert");sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));sendNotificationModel.setMessageType(MessageType.notification);int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);sendNotificationModel.setUserIds(Arrays.asList(userId));notificationService.sendNotification(sendNotificationModel);model.addAttribute("response1", mvcResponseSender.createResponseString(true));return "response";}@RequestMapping(value = "/getPartnerShortageStockDetail", method = RequestMethod.GET)public String getPartnerShortageStockDetail(HttpServletRequest request,@RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)throws Exception {Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService.getSaholicPOItems();List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);Map<Integer, Integer> processingOrderMap = null;Map<Integer, Integer> catalogIdAndQtyMap = null;Map<Integer, Integer> grnPendingOrdersMap = null;Map<String, Set<PartnerStockDetailModel>> brandToUniqueItemsMap = new HashMap<>();List<PartnerStockDetailModel> inStocks = new ArrayList<>();Map<String, PartnerStockDetailModel> inStocksDescriptionModelMap = new HashMap<>();List<PartnerStockDetailModel> grnPendings = new ArrayList<>();Map<String, PartnerStockDetailModel> grnPendingsDescriptionModelMap = new HashMap<>();List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();Map<String, PartnerStockDetailModel> pendingIndentsDescriptionModelMap = new HashMap<>();Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));if (!currentInventorySnapshot.isEmpty()) {catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));inStocks.addAll(getBrandItemwiseDetail(brand, catalogIdAndQtyMap));inStocksDescriptionModelMap = inStocks.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));}Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),Collectors.summingInt(x -> x.getLineItem().getQuantity())));if (!grnPendingOrders.isEmpty()) {grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));grnPendings.addAll(getBrandItemwiseDetail(brand, grnPendingOrdersMap));grnPendingsDescriptionModelMap = grnPendings.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));}Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),Collectors.summingInt(x -> x.getLineItem().getQuantity())));if (!processingOrder.isEmpty()) {processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),Collectors.summingInt(x -> processingOrder.get(x.getId()))));pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));pendingIndentsDescriptionModelMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));}List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());LOGGER.info("regionIds" + regionIds);if (regionIds.size() == 0) {LOGGER.info("No region found for partner {}", fofoId);}// this code is using for focusedModel()Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,warehousePoItemAvailabilityMap, items, customRetailer);focusedModelShortageList.add(fm);} else if (brand.equals("accessories")) {if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {if (items.get(0).getCategoryId() != 0) {Category category = categoryRepository.selectById(items.get(0).getCategoryId());if (category.getParentCategoryId() == 10011) {FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,warehousePoItemAvailabilityMap, items, customRetailer);focusedModelShortageList.add(fm);}}}} else if (brand.equals("TV")) {if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());if (items.get(0).getCategoryId() != 0) {Category category = categoryRepository.selectById(items.get(0).getCategoryId());if (category.getParentCategoryId() == 14200) {FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,warehousePoItemAvailabilityMap, items, customRetailer);focusedModelShortageList.add(fm);}}}}}List<PartnerStockDetailModel> allStockItems = new ArrayList<>();allStockItems.addAll(inStocks);allStockItems.addAll(grnPendings);allStockItems.addAll(pendingIndents);//LOGGER.info("allStockItems {}", allStockItems);brandToUniqueItemsMap =allStockItems.stream().collect(Collectors.groupingBy(PartnerStockDetailModel::getBrand,Collectors.toSet()));model.addAttribute("focusedModelShortageList", focusedModelShortageList);model.addAttribute("inStocks", inStocks);model.addAttribute("inStocksDescriptionModelMap", inStocksDescriptionModelMap);model.addAttribute("brandToUniqueItemsMap", brandToUniqueItemsMap);model.addAttribute("fofoId", fofoId);model.addAttribute("grnPendings", grnPendings);model.addAttribute("grnPendingsDescriptionModelMap", grnPendingsDescriptionModelMap);model.addAttribute("pendingIndents", pendingIndents);model.addAttribute("pendingIndentsDescriptionModelMap", pendingIndentsDescriptionModelMap);model.addAttribute("customRetailer", customRetailer);model.addAttribute("brand", brand);if (brand.equals("undefined")) {Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList.stream().collect(Collectors.groupingBy(x -> x.getBrandName()));Map<String, List<PartnerStockDetailModel>> inStockBrandMap = inStocks.stream().collect(Collectors.groupingBy(x -> x.getBrand()));LOGGER.info("inStockBrandMap" + inStockBrandMap);Map<String, List<PartnerStockDetailModel>> grnPendingBrandMap = grnPendings.stream().collect(Collectors.groupingBy(x -> x.getBrand()));LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);Map<String, List<PartnerStockDetailModel>> pendingIndentBrandMap = pendingIndents.stream().collect(Collectors.groupingBy(x -> x.getBrand()));LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);model.addAttribute("inStockBrandMap", inStockBrandMap);model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);}return "partner-stock-detail";}@RequestMapping(value = "/getPoCatalogsItems", method = RequestMethod.GET)public String getPoCatalogsItems(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam float price, Model model)throws Exception {List<Item> poItems = itemRepository.selectAllByCatalogItemId(catalogId);List<Integer> itemIds = poItems.stream().map(x -> x.getId()).collect(Collectors.toList());Map<Integer, Integer> saholicInventoryMap = saholicInventoryService.getTotalAvailabilityByItemIds(itemIds);Set<Integer> availableStockItemIds = saholicInventoryMap.entrySet().stream().filter(x -> x.getValue() > 0).map(Map.Entry::getKey).collect(Collectors.toSet());List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == warehouseId)).collect(Collectors.toList());Set<Integer> intransitItemIds = warehouseIntransitDataModels.stream().filter(x -> x.getQty() > 0).map(WarehouseIntransitDataModel::getItemId).collect(Collectors.toSet());// Filter intransitItemIds to only those in itemIdsSet<Integer> intransitItemIdsFiltered = new HashSet<>(intransitItemIds);intransitItemIdsFiltered.retainAll(itemIds);Set<Integer> itemIdsWithBothStocks = new HashSet<>();itemIdsWithBothStocks.addAll(intransitItemIdsFiltered); // keeps only the common onesitemIdsWithBothStocks.addAll(availableStockItemIds); // keeps only the common onesLOGGER.info("itemIds {}", itemIds);LOGGER.info("itemIdsWithBothStocks {}", itemIdsWithBothStocks);LOGGER.info("availableStockItemIds {}", availableStockItemIds);LOGGER.info("intransitItemIdsFiltered {}", intransitItemIdsFiltered);List<Item> instockItems = itemRepository.selectByIds(itemIdsWithBothStocks);model.addAttribute("poItems", instockItems);model.addAttribute("price", price);return "po-catalog-items";}@RequestMapping(value = "/getItemsByCatalog", method = RequestMethod.GET)public ResponseEntity<?> getItemsByCatalog(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int fofoId, Model model)throws Exception {List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);Map<Integer, Item> itemMap = items.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));Set<Integer> itemSet = items.stream().map(x -> x.getId()).collect(Collectors.toSet());List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemSet);// Get activated but not sold inventory items for this fofoIdList<InventoryItem> activatedNotSoldItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);// Group activated items by itemId with their serial numbersMap<Integer, List<String>> activatedItemImeiMap = activatedNotSoldItems.stream().collect(Collectors.groupingBy(InventoryItem::getItemId,Collectors.mapping(InventoryItem::getSerialNumber, Collectors.toList())));List<InStockItemDetailModel> inStockItemDetailModels = new ArrayList<>();for (CurrentInventorySnapshot snap : currentInventorySnapshots) {InStockItemDetailModel inStockItemDetailModel = new InStockItemDetailModel();inStockItemDetailModel.setAvailability(snap.getAvailability());inStockItemDetailModel.setItemId(snap.getItemId());inStockItemDetailModel.setCatalogId(itemMap.get(snap.getItemId()).getCatalogItemId());inStockItemDetailModel.setItemDescription(itemMap.get(snap.getItemId()).getItemDescription());inStockItemDetailModel.setFofoId(snap.getFofoId());// Check if this item has any activated but not sold IMEIs and set the IMEI listList<String> activatedImeis = activatedItemImeiMap.get(snap.getItemId());if (activatedImeis != null && !activatedImeis.isEmpty()) {inStockItemDetailModel.setHasActivatedImei(true);inStockItemDetailModel.setActivatedImeis(activatedImeis);}inStockItemDetailModels.add(inStockItemDetailModel);}return responseSender.ok(inStockItemDetailModels);}@RequestMapping(value = "/indent/getOurStockDetails", method = RequestMethod.GET)public ResponseEntity<?> getOurStockDetails(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, Model model)throws Exception {try {// Get all items by catalogIdList<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());if (itemIds.isEmpty()) {return responseSender.ok(Collections.emptyList());}// Get saholic stock for these itemsMap<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);// Build result with item description and qty where netAvailability > 0List<Map<String, Object>> result = new ArrayList<>();for (Item item : items) {List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());if (stockList != null && !stockList.isEmpty()) {int totalNetAvailability = stockList.stream().mapToInt(WarehouseItemQtyModel::getNetAvailability).sum();if (totalNetAvailability > 0) {Map<String, Object> itemDetail = new HashMap<>();itemDetail.put("itemId", item.getId());itemDetail.put("color", item.getColor());itemDetail.put("itemDescription", item.getItemDescription());itemDetail.put("qty", totalNetAvailability);result.add(itemDetail);}}}return responseSender.ok(result);} catch (Exception e) {LOGGER.error("Error getting our stock details for catalogId: {} warehouseId: {}", catalogId, warehouseId, e);return responseSender.ok(Collections.emptyList());}}@RequestMapping(value = "/indent/getOutOfStockDetails", method = RequestMethod.GET)public ResponseEntity<?> getOutOfStockDetails(HttpServletRequest request, @RequestParam String brand, @RequestParam int warehouseId, Model model) throws Exception {try {// Get all catalogs for the brand with their movement statusList<CategorisedCatalogListModel> catalogMovements = categorisedCatalogRepository.getBrandWiseCatalogMovement(brand);// Filter only HID, FASTMOVING, RUNNING statusSet<CatalogMovingEnum> validStatuses = new HashSet<>(Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING));List<CategorisedCatalogListModel> filteredCatalogs = catalogMovements.stream().filter(c -> validStatuses.contains(c.getCurrentStatus())).collect(Collectors.toList());if (filteredCatalogs.isEmpty()) {return responseSender.ok(Collections.emptyList());}List<Map<String, Object>> result = new ArrayList<>();for (CategorisedCatalogListModel catalogModel : filteredCatalogs) {int catalogId = catalogModel.getModelId();// Get all items for this catalogList<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());if (itemIds.isEmpty()) {// No items means out of stock for this modelMap<String, Object> itemDetail = new HashMap<>();itemDetail.put("catalogId", catalogId);itemDetail.put("modelNumber", catalogModel.getModelNumber());itemDetail.put("status", catalogModel.getCurrentStatus().getValue());itemDetail.put("qty", 0);result.add(itemDetail);continue;}// Get saholic stock for these itemsMap<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);// Calculate total net availability for this catalogint totalNetAvailability = 0;for (Item item : items) {List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());if (stockList != null && !stockList.isEmpty()) {totalNetAvailability += stockList.stream().mapToInt(WarehouseItemQtyModel::getNetAvailability).sum();}}// Only include if out of stock (netAvailability <= 0)if (totalNetAvailability <= 0) {Map<String, Object> itemDetail = new HashMap<>();itemDetail.put("catalogId", catalogId);itemDetail.put("modelNumber", catalogModel.getModelNumber());itemDetail.put("status", catalogModel.getCurrentStatus().getValue());itemDetail.put("qty", totalNetAvailability);result.add(itemDetail);}}return responseSender.ok(result);} catch (Exception e) {LOGGER.error("Error getting out of stock details for brand: {} warehouseId: {}", brand, warehouseId, e);return responseSender.ok(Collections.emptyList());}}@AutowiredFofoOpeningStockRepository fofoOpeningStockRepository;@RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)public String getPartnerShortageStock(HttpServletRequest request,@RequestParam(required = false, defaultValue = "") String brand, @RequestParam(required = false, defaultValue = "0") long shortInvest, @RequestParam(required = false, defaultValue = "0") long totalDueWithInterest, @RequestParam int fofoId, Model model)throws Exception {LocalDateTime presentDate = LocalDateTime.now();LocalDateTime curDate = LocalDate.now().atStartOfDay();FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);int warehouseId = fofoStore.getWarehouseId();List<BrandWisePartnerSaleModel> brandWisePartnerSaleModels = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(Arrays.asList(fofoId));LOGGER.info("brandWisePartnerSaleModels {}", brandWisePartnerSaleModels);Map<String, Long> brandToMtdMap = brandWisePartnerSaleModels.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getMtd()));Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));double purchaseMtd = secondaryMtd.getOrDefault(fofoId, 0.0);Map<Integer, Double> secondaryToday = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),curDate, curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));double purchasedFtd = secondaryToday.getOrDefault(fofoId, 0.0);MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);double purchaseTargetFtd = rbmTargetService.calculateFofoIdTodayTarget(fofoId, purchaseMtd, LocalDate.now());double saleMtd = (Double) fofoUser.getSales(fofoId).get("mtdSale");double recoverableAmount = saleMtd - purchaseMtd;SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);UserWallet userWallet = walletService.getUserWallet(fofoId);BigDecimal totalAvailableFunds = sdCreditRequirement.getAvailableLimit().add(BigDecimal.valueOf(userWallet.getAmount()));List<Loan> loans = loanRepository.selectActiveLoan(fofoId);double totalPendingAmount = loans.stream().map(Loan::getPendingAmount).mapToDouble(BigDecimal::doubleValue).sum();boolean isLoanPending = false;if (loans.size() > 0) {isLoanPending = true;}List<PartnerWarehouseStockSummaryModel> partnerWarehouseStockSummaryModels = saholicInventoryService.getSaholicAndPartnerStock(fofoId, fofoStore.getWarehouseId());List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == fofoStore.getWarehouseId())).collect(Collectors.toList());Map<Integer, Long> catalogWiseQtyMap = new HashMap<>();Set<Integer> inTransitCatalogIds = new HashSet<>();List<PartnerWarehouseStockSummaryModel> intransistSummaryList = new ArrayList<>();if (warehouseIntransitDataModels.size() > 0) {Map<Integer, List<WarehouseIntransitDataModel>> warewarehouseIntransitDataModelsMap = warehouseIntransitDataModels.stream().collect(Collectors.groupingBy(WarehouseIntransitDataModel::getCatalogId));catalogWiseQtyMap = warehouseIntransitDataModels.stream().collect(Collectors.groupingBy(WarehouseIntransitDataModel::getCatalogId,Collectors.summingLong(WarehouseIntransitDataModel::getQty)));LOGGER.info("catalogWiseQtyMap key set {}", catalogWiseQtyMap.keySet());List<FofoOpeningStock> fofoOpeningStocksLitsForIntransist = fofoOpeningStockRepository.fofoOpeningStockByFofoId(catalogWiseQtyMap.keySet(), fofoId);LOGGER.info("fofoOpeningStocksLitsForIntransist {}", fofoOpeningStocksLitsForIntransist);// Optional: Build a map for faster lookupMap<Integer, FofoOpeningStock> inTransistfofoOpeningStockMap = fofoOpeningStocksLitsForIntransist.stream().collect(Collectors.toMap(FofoOpeningStock::getCatalogId, stock -> stock));for (Map.Entry<Integer, Long> entry : catalogWiseQtyMap.entrySet()) {int catalogId = entry.getKey();long netAvailability = entry.getValue();FofoOpeningStock openingStock = inTransistfofoOpeningStockMap.get(catalogId);WarehouseIntransitDataModel warehouseIntransitDataModel = warewarehouseIntransitDataModelsMap.get(catalogId).get(0);PartnerWarehouseStockSummaryModel inTransistmodel = new PartnerWarehouseStockSummaryModel(warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getBrand() : "Unknown",catalogId,warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getItemDescription() : "Unknown",warehouseIntransitDataModel != null ? 10006 : 0,(int) netAvailability,openingStock != null ? openingStock.getOpeningQty() : 0,openingStock != null ? openingStock.getCurrentQty() : 0,openingStock != null ? (openingStock.getOpeningQty() - openingStock.getCurrentQty()) : 0,warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getStatus() : "Unknown");intransistSummaryList.add(inTransistmodel);}}List<DateWiseSoldCatalogQtyModel> sevenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(7));List<DateWiseSoldCatalogQtyModel> fourteenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(14));List<DateWiseSoldCatalogQtyModel> twentyOneDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(21));LOGGER.info("twentyOneDayAboveSoldsCatalogs {}", twentyOneDayAboveSoldsCatalogs);List<DateWiseSoldCatalogQtyModel> twentyEightDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(28));Set<Integer> catalogIds = partnerWarehouseStockSummaryModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());if (!catalogWiseQtyMap.isEmpty()) {inTransitCatalogIds = catalogWiseQtyMap.keySet().stream().filter(catalogId -> !catalogIds.contains(catalogId)).collect(Collectors.toSet());}// Add the missing IDs to the original setcatalogIds.addAll(inTransitCatalogIds);List<Integer> catalogsList = new ArrayList<>(catalogIds);Map<Integer, TagListing> tagListingsMap = tagListingRepository.selectAllByCatalogIds(catalogsList);List<CatalogAgingModel> catalogAgingModels = ageingService.getCatalogsAgingByWarehouse(catalogIds, fofoStore.getWarehouseId());Map<Integer, CatalogAgingModel> catalogAgingModelMap = catalogAgingModels.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));List<PartnerWarehouseStockAgingSummaryModel> partnerWarehouseStockAgingSummaryModelList = new ArrayList<>();for (PartnerWarehouseStockSummaryModel stockSummary : partnerWarehouseStockSummaryModels) {PartnerWarehouseStockAgingSummaryModel partnerWarehouseStockAgingSummaryModel = new PartnerWarehouseStockAgingSummaryModel();partnerWarehouseStockAgingSummaryModel.setCatalogId(stockSummary.getCatalogId());partnerWarehouseStockAgingSummaryModel.setBrand(stockSummary.getBrand());partnerWarehouseStockAgingSummaryModel.setModelNumber(stockSummary.getModelNumber());partnerWarehouseStockAgingSummaryModel.setNetAvailability(stockSummary.getShaholicNetAvailability());partnerWarehouseStockAgingSummaryModel.setPartnerStockAvailability(stockSummary.getPartnerFullFilledQty());partnerWarehouseStockAgingSummaryModel.setPartnerCurrentAvailability(stockSummary.getPartnerCurrentQty());partnerWarehouseStockAgingSummaryModel.setPartnerShortageStock(stockSummary.getPartnerShortageQty());if (catalogAgingModelMap.get(stockSummary.getCatalogId()) != null) {partnerWarehouseStockAgingSummaryModel.setExceedDays(catalogAgingModelMap.get(stockSummary.getCatalogId()).getExceedDays());} else {partnerWarehouseStockAgingSummaryModel.setExceedDays(0);}partnerWarehouseStockAgingSummaryModel.setStatus(stockSummary.getStatus());partnerWarehouseStockAgingSummaryModelList.add(partnerWarehouseStockAgingSummaryModel);}Set<Integer> existingCatalogIdsInAgingSummaryList = partnerWarehouseStockAgingSummaryModelList.stream().map(PartnerWarehouseStockAgingSummaryModel::getCatalogId).collect(Collectors.toSet());if (intransistSummaryList.size() > 0) {// Step 2: Iterate over intransitSummaryList and add missing onesfor (PartnerWarehouseStockSummaryModel intransitStock : intransistSummaryList) {if (!existingCatalogIdsInAgingSummaryList.contains(intransitStock.getCatalogId())) {PartnerWarehouseStockAgingSummaryModel agingModel = new PartnerWarehouseStockAgingSummaryModel();agingModel.setCatalogId(intransitStock.getCatalogId());agingModel.setBrand(intransitStock.getBrand());agingModel.setModelNumber(intransitStock.getModelNumber());agingModel.setNetAvailability(0); // Not part of original aging summaryagingModel.setPartnerStockAvailability(intransitStock.getPartnerFullFilledQty());agingModel.setPartnerCurrentAvailability(intransitStock.getPartnerCurrentQty());agingModel.setPartnerShortageStock(intransitStock.getPartnerShortageQty());if (catalogAgingModelMap.get(intransitStock.getCatalogId()) != null) {agingModel.setExceedDays(catalogAgingModelMap.get(intransitStock.getCatalogId()).getExceedDays());} else {agingModel.setExceedDays(0);}agingModel.setStatus(intransitStock.getStatus() == null ? "OTHER" : intransitStock.getStatus());partnerWarehouseStockAgingSummaryModelList.add(agingModel);}}}List<String> statusOrder = Arrays.asList("HID", "FASTMOVING", "RUNNING", "SLOWMOVING", "OTHER");Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> brandStatusWiseStockListMap =partnerWarehouseStockAgingSummaryModelList.stream().collect(Collectors.groupingBy(PartnerWarehouseStockAgingSummaryModel::getBrand,Collectors.groupingBy(PartnerWarehouseStockAgingSummaryModel::getStatus)));//map of list as hid,fast,slow and other in last otherwise other is coming in start (here is using status order)Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> sortedBrandStatusWiseStockListMap =brandStatusWiseStockListMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, // Key (Brand)entry -> {Map<String, List<PartnerWarehouseStockAgingSummaryModel>> sortedStatusMap = entry.getValue().entrySet().stream().sorted((e1, e2) -> Integer.compare(statusOrder.indexOf(e1.getKey()),statusOrder.indexOf(e2.getKey()))).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(v1, v2) -> v1,LinkedHashMap::new // Ensure ordering is maintained));return sortedStatusMap;},(v1, v2) -> v1,LinkedHashMap::new // Maintain order of brands));LOGGER.info("brandToMtdMap {}", brandToMtdMap);List<String> sortedBrandsByMtd = brandToMtdMap.entrySet().stream().sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // Descending MTD.map(Map.Entry::getKey).collect(Collectors.toList());List<String> remainingBrands = ProfitMandiConstants.BRANDS.stream().filter(x -> !brandToMtdMap.containsKey(x)).filter(x -> sortedBrandStatusWiseStockListMap.containsKey(x)).collect(Collectors.toList());List<String> remainingBrandsWithoutStock = ProfitMandiConstants.BRANDS.stream().filter(x -> !brandToMtdMap.containsKey(x)).filter(x -> !sortedBrandStatusWiseStockListMap.containsKey(x)) // no stock.collect(Collectors.toList());List<InStockBrandItemModel> inStockBrandItemModels = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);Map<String, Long> brandsWithPartnerStockMap = inStockBrandItemModels.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand, Collectors.summingLong(InStockBrandItemModel::getQty)));List<String> brandsWithPartnerStock = brandsWithPartnerStockMap.entrySet().stream().filter(x -> x.getValue() > 0).map(x -> x.getKey()).collect(Collectors.toList());List<String> sortedBrands = new ArrayList<>();sortedBrands.addAll(sortedBrandsByMtd);sortedBrands.addAll(remainingBrands);sortedBrands.addAll(remainingBrandsWithoutStock);List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);List<String> finalSortedBrands = sortedBrands.stream().filter(x -> !partnerIneligibleBrands.contains(x) && !"itel".equalsIgnoreCase(x)).collect(Collectors.toList());Map<Integer, Integer> processingOrderMap = null;List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();Map<Integer, PartnerStockDetailModel> pendingIndentsDetailMap = new HashMap<>();Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),Collectors.summingInt(x -> x.getLineItem().getQuantity())));if (!processingOrder.isEmpty()) {processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),Collectors.summingInt(x -> processingOrder.get(x.getId()))));pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));pendingIndentsDetailMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));}LOGGER.info("pendingIndents {}", pendingIndents);LOGGER.info("pendingIndentsDetailMap {}", pendingIndentsDetailMap);model.addAttribute("brandStatusWiseStockListMap", sortedBrandStatusWiseStockListMap);model.addAttribute("brandsWithPartnerStock", brandsWithPartnerStock);model.addAttribute("pendingIndentsDetailMap", pendingIndentsDetailMap);model.addAttribute("brands", finalSortedBrands);model.addAttribute("brandToMtdMap", brandToMtdMap);model.addAttribute("catalogWiseQtyMap", catalogWiseQtyMap);model.addAttribute("intransistSummaryList", intransistSummaryList);model.addAttribute("brand", brand);model.addAttribute("fofoId", fofoId);model.addAttribute("warehouseId", warehouseId);model.addAttribute("customRetailer", customRetailer);model.addAttribute("shortInvest", shortInvest);model.addAttribute("totalDueWithInterest", totalDueWithInterest);model.addAttribute("interestDue", Math.subtractExact(totalDueWithInterest, sdCreditRequirement.getUtilizedAmount().intValue()));model.addAttribute("purchaseMtd", purchaseMtd);model.addAttribute("purchasedFtd", purchasedFtd);model.addAttribute("saleMtd", saleMtd);model.addAttribute("purchaseTargetFtd", purchaseTargetFtd);model.addAttribute("recoverableAmount", recoverableAmount);model.addAttribute("isLoanPending", isLoanPending);model.addAttribute("totalAvailableFunds", totalAvailableFunds);model.addAttribute("sdCreditRequirement", sdCreditRequirement);model.addAttribute("userWallet", userWallet);model.addAttribute("monthlyTarget", monthlyTarget);model.addAttribute("totalPendingAmount", totalPendingAmount);model.addAttribute("tagListingsMap", tagListingsMap);model.addAttribute("sevenDayAboveSoldsCatalogs", sevenDayAboveSoldsCatalogs);model.addAttribute("fourteenDayAboveSoldsCatalogs", fourteenDayAboveSoldsCatalogs);model.addAttribute("twentyOneDayAboveSoldsCatalogs", twentyOneDayAboveSoldsCatalogs);model.addAttribute("twentyEightDayAboveSoldsCatalogs", twentyEightDayAboveSoldsCatalogs);return "partner-stock";}private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());if (brand.equals("accessories")) {if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {if (items.get(0).getCategoryId() != 0) {Category category = categoryRepository.selectById(items.get(0).getCategoryId());if (category.getParentCategoryId() == 10011) {PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();psdp.setBrand(items.get(0).getBrand());psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "+ items.get(0).getModelNumber());psdp.setQty(inStock.getValue());inStocks.add(psdp);}}}} else if (brand.equals("TV")) {if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {if (items.get(0).getCategoryId() != 0) {Category category = categoryRepository.selectById(items.get(0).getCategoryId());if (category.getParentCategoryId() == 14200) {PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();psdp.setBrand(items.get(0).getBrand());psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "+ items.get(0).getModelNumber());psdp.setQty(inStock.getValue());inStocks.add(psdp);}}}} else {PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();psdp.setBrand(items.get(0).getBrand());psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "+ items.get(0).getModelNumber());psdp.setQty(inStock.getValue());inStocks.add(psdp);}}return inStocks;}private List<PartnerStockDetailModel> getBrandItemwiseDetail(String brand,Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {List<PartnerStockDetailModel> inStocks = new ArrayList<>();for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());PartnerStockDetailModel psdp = new PartnerStockDetailModel();psdp.setBrand(items.get(0).getBrand());psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "+ items.get(0).getModelNumber());psdp.setQty(inStock.getValue());psdp.setCatalogId(items.get(0).getCatalogItemId());inStocks.add(psdp);}return inStocks;}private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,CustomRetailer customRetailer) throws ProfitMandiBusinessException {int minQty = qty;int inStockQty = 0;int processingQty = 0;int grnPendingQty = 0;int allColorNetAvailability = 0;int allColorPoAvailability = 0;if (processingOrderMap != null) {processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);}if (grnPendingOrdersMap != null) {grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);}if (catalogIdAndQtyMap != null) {inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);}int grnStockQty = grnPendingQty + inStockQty;int totalQty = processingQty + grnPendingQty + inStockQty;int shortageQty = minQty - totalQty;FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap.get(fofoStore.getWarehouseId());for (Item it : items) {List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(),fofoStore.getWarehouseId());List<SaholicPOItem> poItemAvailability = null;if (poItemAvailabilityMap != null) {poItemAvailability = poItemAvailabilityMap.get(it.getId());}if (currentAvailability != null) {allColorNetAvailability += currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));}if (poItemAvailability != null) {allColorPoAvailability += poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));}}FocusedModelShortageModel fm = new FocusedModelShortageModel();fm.setFofoId(fofoId);fm.setStoreCode(fofoStore.getCode());fm.setStoreName(customRetailer.getBusinessName());fm.setBrandName(items.get(0).getBrand());fm.setModelName(items.get(0).getModelName());fm.setModelNumber(items.get(0).getModelNumber());fm.setGrnStockQty(grnStockQty);fm.setPendingIndentQty(processingQty);fm.setShortageQty(shortageQty);fm.setPoAvailability(allColorPoAvailability);fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());fm.setAvailability(allColorNetAvailability);return fm;}@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)public String SendPONotification(HttpServletRequest request, Model model) {model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);return "send-po-notification";}@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,Model model) throws Exception {Map<Integer, Item> selectedCatalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase()).collect(Collectors.toSet());int warehouseId = poItemWarehouseModel.getWarehouseId();for (String brand : brands) {List<String> modelNames = selectedCatalogItemMap.entrySet().stream().filter(x -> x.getValue().getBrand().toLowerCase().equals(brand)).map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());SendNotificationModel sendNotificationModel = new SendNotificationModel();sendNotificationModel.setCampaignName("SendPo");sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));sendNotificationModel.setMessage(String.join(", ", modelNames));sendNotificationModel.setType("url");sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));sendNotificationModel.setMessageType(MessageType.notification);List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream().filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId&& !x.isAccessory()).collect(Collectors.toList());List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId()).collect(Collectors.toList());List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream().filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);sendNotificationModel.setUserIds(userIds);notificationService.sendNotification(sendNotificationModel);}model.addAttribute("response1", true);return "response";}}