Subversion Repositories SmartDukaan

Rev

Rev 31144 | Rev 31762 | 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.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
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.ExcelUtils;
import com.spice.profitmandi.common.util.PdfUtils;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.common.util.Utils.Attachment;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.catalog.*;
import com.spice.profitmandi.dao.entity.cs.Position;
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.fofo.LiveDemoSerialNumber;
import com.spice.profitmandi.dao.entity.transaction.*;
import com.spice.profitmandi.dao.entity.user.Address;
import com.spice.profitmandi.dao.enumuration.catalog.ByPassRequestStatus;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
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.CsService;
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
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.dtr.WebOfferRepository;
import com.spice.profitmandi.dao.repository.fofo.*;
import com.spice.profitmandi.dao.repository.inventory.NotifyStatus;
import com.spice.profitmandi.dao.repository.transaction.*;
import com.spice.profitmandi.dao.repository.user.AddressRepository;
import com.spice.profitmandi.dao.repository.user.UserRepository;
import com.spice.profitmandi.dao.repository.warehouse.WarehousePurchaseOrderRepository;
import com.spice.profitmandi.dao.repository.warehouse.WarehouseScanRepository;
import com.spice.profitmandi.service.NotificationService;
import com.spice.profitmandi.service.inventory.Combo;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.inventory.MappedComboModel;
import com.spice.profitmandi.service.order.OrderService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.TransactionServiceException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.thrift.TException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

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

        private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy H:m:s");

        private static final List<String> imeis = Arrays.asList("351030944216680", "351030944217183", "351030944217886",
                        "351030944507286", "351081710231270", "351081710238713", "351081710238796", "351081710241279",
                        "351081710244737", "355777112655976");

        List<EscalationType> esclationType = Arrays.asList(EscalationType.L3, EscalationType.L4);

        List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com");

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        @Qualifier("fofoInventoryService")
        private InventoryService inventoryService;

        @Autowired
        TagListingRepository tagListingRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private TagRankingRepository tagRankingRepository;

        @Autowired
        private InventoryItemRepository inventoryItemRepository;

        @Autowired
        private LiveDemoBillingRespository liveDemoBillingRespository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private Gson gson;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private NotifyItemRepository notifyItemRepository;

        @Autowired
        private NotifyColorChangeRepository notifyColorChangeRepository;

        @Autowired
        private NotifyOrderRespository notifyOrderRespository;

        @Autowired
        private NotificationService notificationService;

        @Autowired
        private NotifyMessageRepository notifyMessageRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private OrderService orderService;

        @Value("${saholic.api.host}")
        private String host;

        @Value("${saholic.api.port}")
        private int port;

        @Value("${saholic.api.webapp}")
        private String webapp;

        @Autowired
        JavaMailSender mailSender;

        @Autowired
        private NotifyCancelOrderRepository notifyCancelOrderRepository;

        @Autowired
        private WarehousePurchaseOrderRepository warehousePurchaseOrderRepository;

        @Autowired
        private WarehouseScanRepository warehouseScanRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;
        @Autowired
        private Mongo mongoClient;

        @Autowired
        private FocusedModelByPassRepository focusedModelByPassRepository;

        @Autowired
        private CsService csService;

        @Autowired
        AuthRepository authRepository;

        @Autowired
        PositionRepository positionRepository;

        @Autowired
        ActivatedImeiRepository activatedImeiRepository;

        @Autowired
        HighDemandItemsRepository highDemandItemsRepository;

        @Autowired
        WebOfferRepository webOfferRepository;

        @Autowired
        ComboModelRepository comboModelRepository;

        @Autowired
        ComboMappedModelRepository comboMappedModelRepository;

        @Autowired
        private UserRepository userUserRepository;

        @Autowired
        private AddressRepository addressRepository;

        @RequestMapping(value = "/getCurrentInventorySnapshot")
        public String getCurrentAvailability(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getCurrentInventorySnapshot(loginDetails.getFofoId(), offset, limit,
                                searchTerm);
                model.addAllAttributes(map);
                return "inventory-snapshot";
        }

        @RequestMapping(value = "/getBadInventorySnapshot")
        public String getBadAvailability(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws ProfitMandiBusinessException {
                if (searchTerm == null) {
                        searchTerm = "";
                }
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getBadInventorySnapshot(loginDetails.getFofoId(), offset, limit,
                                searchTerm);
                model.addAllAttributes(map);
                return "bad-inventory-snapshot";
        }

        @RequestMapping(value = "/getPaginatedCurrentInventorySnapshot")
        public String getPaginatedCurrentInventorySnapshot(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
                        throws ProfitMandiBusinessException {
                if (searchTerm == null) {
                        searchTerm = "";
                }
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getPaginatedCurrentInventorySnapshot(loginDetails.getFofoId(),
                                offset, limit, searchTerm);
                model.addAllAttributes(map);
                return "inventory-snapshot-paginated";
        }

        @RequestMapping(value = "/getCatalog")
        public String getCatalog(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "20") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
                        @RequestParam(name = "itemId", required = false, defaultValue = "0") int itemId,
                        @RequestParam(name = "accesories", required = false, defaultValue = "0") boolean accesories,

                        @RequestParam(name = "brand", required = false, defaultValue = "") String brand, Model model)

                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                if (searchTerm == null) {
                        searchTerm = "";
                }

                Map<String, Object> map = inventoryService.getCatalog(loginDetails.getFofoId(), offset, limit, searchTerm,
                                itemId, brand, accesories);
                model.addAllAttributes(map);
                model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));

                return "catalog";
        }

        @RequestMapping(value = "/getWebOfferByCatalogId")
        public String getCatalog(HttpServletRequest request, @RequestParam int catalogItemId, Model model)

                        throws ProfitMandiBusinessException {

                List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(catalogItemId);

                model.addAttribute("webOffers", webOffers);

                return "web-offer-model";
        }

        // This method is currently hardcoded to faciliate watches sold as gift.
        private boolean hasGift(int fofoId) {
                try {
                        return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
                                        .getAvailability() > 0;
                } catch (ProfitMandiBusinessException e) {
                        return false;
                }
        }

        @RequestMapping(value = "/getPaginatedCatalog")
        public String getCatalogPaginated(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "20") int limit,
                        @RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
                        @RequestParam(name = "itemId", required = false, defaultValue = "0") int itemId,
                        @RequestParam(name = "accesories", required = false, defaultValue = "0") boolean accesories,
                        @RequestParam(name = "brand", required = false, defaultValue = "") String brand, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                if (searchTerm == null) {
                        searchTerm = "";
                }
                Map<String, Object> map = inventoryService.getPaginatedCatalog(loginDetails.getFofoId(), offset, limit,
                                searchTerm, itemId, brand, accesories);
                model.addAllAttributes(map);
                return "catalog-paginated";
        }

        @RequestMapping(value = "/checkItemAvailability")
        public String getItemAvailability(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.ITEM_ID) int itemId, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                CustomCurrentInventorySnapshot customCurrentInventorySnapshot = inventoryService.checkItemAvailability(itemId,
                                loginDetails.getFofoId());
                /*
                 * customCurrentInventorySnapshot
                 * .setIconUrl(Utils.getIconUrl(customCurrentInventorySnapshot.getCatalogItemId(
                 * ), host, port, webapp));
                 */
                model.addAttribute("currentInventorySnapshot", new Gson().toJson(customCurrentInventorySnapshot));
                return "current-item-availability";

        }

        @RequestMapping(value = "/cart", method = RequestMethod.POST)
        public String addToCart(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                Map<String, Object> map = inventoryService.addToCart(cartData, loginDetails.getFofoId());
                model.addAllAttributes(map);
                return "cart";
        }

        @RequestMapping(value = "/validate-cart", method = RequestMethod.POST)
        public String validateCart(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam(name = "cartData") String cartData, Model model) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                Map<String, Object> map = inventoryService.validateCart(cartData, loginDetails.getFofoId());
                model.addAllAttributes(map);
                return "validate-cart";
        }

        @RequestMapping(value = "/grnHistory")
        public String getGrnHistory(HttpServletRequest request, @RequestParam(required = false) LocalDateTime startTime,
                        @RequestParam(required = false) LocalDateTime endTime,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = ProfitMandiConstants.PURCHASE_REFERENCE, defaultValue = "") String purchaseReference,
                        @RequestParam(name = "searchType", defaultValue = "") String searchType, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getGrnHistory(loginDetails.getFofoId(), startTime, endTime, offset,
                                limit, purchaseReference, searchType);
                model.addAllAttributes(map);
                return "grn-history";
        }

        @RequestMapping(value = "/downloadPurchaseInvoices")
        public ResponseEntity<?> downloadPurchaseInvoices(HttpServletRequest request,
                        @RequestParam(required = false) LocalDateTime startTime,
                        @RequestParam(required = false) LocalDateTime endTime,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = ProfitMandiConstants.PURCHASE_REFERENCE, defaultValue = "") String purchaseReference,
                        @RequestParam(name = "searchType", defaultValue = "") String searchType, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getGrnHistory(loginDetails.getFofoId(), startTime, endTime, offset,
                                limit, purchaseReference, searchType);

                List<FofoOrder> fofoOrders = (List<FofoOrder>) map.get("saleHistories");

                if (fofoOrders.size() == 0) {
                        throw new ProfitMandiBusinessException("Search criteria", "", "No orders found for criteria");
                }

                final HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_PDF);
                headers.set("Content-disposition", "inline; filename=invoices.pdf");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                List<InvoicePdfModel> pdfModels = new ArrayList<>();
                PdfUtils.generateAndWrite(pdfModels, byteArrayOutputStream);
                headers.setContentLength(byteArrayOutputStream.toByteArray().length);
                final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }

        @RequestMapping(value = "/getPaginatedGrnHistory")
        public String getPaginatedGrnHistory(HttpServletRequest request,
                        @RequestParam(required = false) LocalDateTime startTime,
                        @RequestParam(required = false) LocalDateTime endTime,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit,
                        @RequestParam(name = ProfitMandiConstants.PURCHASE_REFERENCE, defaultValue = "") String purchaseReference,
                        @RequestParam(name = "searchType", defaultValue = "") String searchType, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getPaginatedGrnHistory(loginDetails.getFofoId(), startTime, endTime,
                                offset, limit);
                model.addAllAttributes(map);
                return "grn-history-paginated";
        }

        @RequestMapping(value = "/grnHistoryDetailByPurchaseId")
        public String grnHistoryByPurchaseId(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.PURCHASE_ID) int purchaseId, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getGrnHistoryDetail(loginDetails.getFofoId(), purchaseId, host, port,
                                webapp);
                model.addAllAttributes(map);
                return "grn-details";
        }

        @RequestMapping(value = "/grnHistoryDetailByPurchaseReference")
        public String grnHistoryByPurchaseReference(HttpServletRequest request,
                        @RequestParam(name = ProfitMandiConstants.PURCHASE_REFERENCE) String purchaseReference, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getGrnHistoryDetail(loginDetails.getFofoId(), purchaseReference,
                                host, port, webapp);
                model.addAllAttributes(map);
                return "grn-details";
        }

        @RequestMapping(value = "/activatedImeis")
        public String activatedImeis(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(loginDetails.getFofoId());
                inventoryItems.stream().forEach(x -> {
                        try {
                                x.setItem(itemRepository.selectById(x.getItemId()));
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                });
                model.addAttribute("inventoryItems", inventoryItems);
                return "activated-imeis";
        }

        @RequestMapping(value = "/activated-imeis-grn-pending")
        public String activatedImeisGrnPending(HttpServletRequest request, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                List<Order> openOrders = orderRepository.selectGrnTimestampNull(loginDetails.getFofoId(),
                                Arrays.asList(OrderStatus.SHIPPED_FROM_WH, OrderStatus.DELIVERY_SUCCESS));
                List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository
                                .selectActivatedImeisByOrders(openOrders.stream().map(x -> x.getId()).collect(Collectors.toList()));
                Map<Integer, Order> ordersMap = openOrders.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
                model.addAttribute("ordersMap", ordersMap);
                model.addAttribute("imeiActivationTimestampModels", imeiActivationTimestampModels);
                return "activated-imeis-grn-pending";
        }

        @RequestMapping(value = "/view-invoices")
        public String viewInvoices(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                return "view-dummy-invoices";
        }

        @RequestMapping(value = "/dummy-invoices")
        public ResponseEntity<?> downloadInvoices(HttpServletRequest request, @RequestParam String serialNumber,
                        Model model) throws ProfitMandiBusinessException {
                byte[] bytes = null;
                if (!imeis.contains(serialNumber)) {

                        InvoicePdfModel pdfModel = orderService.getDummyPdfModel(serialNumber);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
                        bytes = byteArrayOutputStream.toByteArray();
                } else {
                        ClassPathResource resource = new ClassPathResource("/META-INF/" + serialNumber + ".pdf");
                        try {
                                bytes = FileUtils.readFileToByteArray(resource.getFile());
                        } catch (Exception e) {

                        }
                }
                final HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_PDF);
                headers.set("Content-disposition", "inline; filename=invoice-" + serialNumber + ".pdf");
                headers.setContentLength(bytes.length);
                final InputStream inputStream = new ByteArrayInputStream(bytes);
                final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }

        @RequestMapping(value = "/dummy-invoices-bulk")
        public ResponseEntity<?> downloadInvoicesBulk(HttpServletRequest request, @RequestParam List<String> serialNumbers,
                        Model model) throws Exception {
                byte[] bytes = null;
                List<Attachment> attachments = new ArrayList<>();
                for (String serialNumber : serialNumbers) {
                        if (!imeis.contains(serialNumber)) {
                                InvoicePdfModel pdfModel = null;
                                try {
                                        pdfModel = orderService.getDummyPdfModel(serialNumber);
                                } catch (Exception e) {
                                        continue;
                                }
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
                                bytes = byteArrayOutputStream.toByteArray();
                        } else {
                                ClassPathResource resource = new ClassPathResource("/META-INF/" + serialNumber + ".pdf");
                                try {
                                        bytes = FileUtils.readFileToByteArray(resource.getFile());
                                } catch (Exception e) {
                                        continue;
                                }
                        }
                        attachments.add(new Attachment("invoice-" + serialNumber + ".pdf", new ByteArrayResource(bytes)));
                }

                Utils.sendMailWithAttachments(mailSender, new String[] { "kuldeep.kumar@smartdukaan.com" }, null,
                                "Invoices List", "PFA", attachments.toArray(new Attachment[attachments.size()]));
                return new ResponseEntity<Boolean>(true, HttpStatus.OK);
        }

        @RequestMapping(value = "/getInventoryItemAgingByInterval", method = RequestMethod.POST)
        public String getInventoryItemAgingByInterval(HttpServletRequest request, @RequestBody List<Integer> intervals,
                        Model model, @RequestParam(name = "searchContent", defaultValue = "") String searchContent,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Object> map = inventoryService.getPaginatedItemAgingByInterval(loginDetails.getFofoId(), intervals,
                                searchContent, offset, limit);
                model.addAllAttributes(map);
                return "item-aging";
        }

        @RequestMapping(value = "/downloadInventoryItemAgingByInterval", method = RequestMethod.POST)
        public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
                        @RequestBody List<Integer> intervals, Model model) throws ProfitMandiBusinessException {
                LOGGER.info("Request received at url{} with body {}", request.getRequestURI(), intervals);
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);

                List<InventoryItemAgingModel> inventoryItemAgingModels = inventoryService
                                .getItemAgingByInterval(fofoDetails.getFofoId(), intervals);

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ExcelUtils.writeInventoryItemAgingModels(inventoryItemAgingModels, intervals, byteArrayOutputStream);

                final HttpHeaders headers = new HttpHeaders();
                // private static final String CONTENT_TYPE_XLSX =
                // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                // headers.set("Content-Type", "application/vnd.ms-excel");
                headers.set("Content-disposition", "inline; filename=InventoryItemAging.xlsx");
                headers.setContentLength(byteArrayOutputStream.toByteArray().length);
                final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }

        @RequestMapping(value = "/aging-report", method = RequestMethod.GET)
        public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request)
                        throws ProfitMandiBusinessException {

                List<Integer> intervals = Arrays.asList(5, 15, 30, 45);
                List<InventoryItemAgingModel> inventoryItemAgingModels = inventoryService.getItemAgingByInterval(intervals)
                                .values().stream().flatMap(Collection::stream).collect(Collectors.toList());
                LOGGER.info("Fofo Id {}", inventoryItemAgingModels.get(0).getFofoId());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ExcelUtils.writeInventoryItemAgingModels(inventoryItemAgingModels, intervals, byteArrayOutputStream);

                final HttpHeaders headers = new HttpHeaders();
                // private static final String CONTENT_TYPE_XLSX =
                // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                // headers.set("Content-Type", "application/vnd.ms-excel");
                headers.set("Content-disposition", "inline; filename=InventoryItemAging.xlsx");
                headers.setContentLength(byteArrayOutputStream.toByteArray().length);
                final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }

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

                List<TagRanking> tagRanking = null;
                tagRanking = tagRankingRepository.getAllTagRanking();
                LOGGER.info("tagRanking" + tagRanking);
                if (!tagRanking.isEmpty()) {
                        Set<Integer> catalogIds = tagRanking.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
                        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
                        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
                                        x -> x.getItemDescription(), (description1, description2) -> description1));

                        LOGGER.info("catalogDescription" + catalogDescription);
                        model.addAttribute("tagRanking", tagRanking);
                        model.addAttribute("catalogDescription", catalogDescription);

                } else {
                        model.addAttribute("tagRanking", tagRanking);

                }

                return "feature";

        }

        @PostMapping(value = "/imei/upload")
        public String uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
                        throws Exception {
                /*
                 * if(brand==null) { throw new
                 * ProfitMandiBusinessException("Please select brand", "Brand empty",
                 * "Brand required"); }
                 */
                List<CSVRecord> masterDataList = readFile(file);

                Map<String, LocalDateTime> imeisActivationMap = masterDataList.stream()
                                .collect(Collectors.toMap(x -> x.get(0).trim(), x -> {
                                        if (!StringUtils.isEmpty(x.get(1).trim())) {
                                                return LocalDateTime.parse((String) (x.get(1).trim()), formatter);
                                        } else {
                                                return null;
                                        }
                                }));
                inventoryService.addActivatedImeis(imeisActivationMap);
                model.addAttribute("response1", true);
                return "response";
        }

        private List<CSVRecord> readFile(MultipartFile file) throws Exception {
                List<CSVRecord> records = null;
                try (CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT)) {
                        records = parser.getRecords();
                        if (records.size() < 2) {
                                throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
                        }
                        records.remove(0);
                } catch (Exception e) {
                        throw new ProfitMandiBusinessException("Parsing Failed", "parse failed", "file parse failed");
                }
                return records;
        }

        @RequestMapping(value = "/itemfeature", method = RequestMethod.POST)
        public String Itemfeature(HttpServletRequest request, @RequestBody ItemFeatureDataModel itemFeatureDatatModel,
                        Model model) throws Exception {
                TagRanking tagRanking = tagRankingRepository.selectBycatalogItemId(itemFeatureDatatModel.getCatalogItemId());
                LOGGER.info("tagRanking" + tagRanking);
                if (tagRanking == null) {
                        tagRanking = new TagRanking();
                        tagRanking.setCatalogItemId(itemFeatureDatatModel.getCatalogItemId());
                }
                tagRanking.setFeature(itemFeatureDatatModel.getFeature());
                tagRanking.setRankPoints(itemFeatureDatatModel.getRankPoints());

                tagRankingRepository.persist(tagRanking);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "response";
        }

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

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

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

                List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
                                .collect(Collectors.toList());

                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
                                .filter(x -> x != null).collect(Collectors.toList()).stream()
                                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                String customRetailers = JSONObject.valueToString(customRetailersMap.values());
                List<String> serailNumberList = liveDemoBillingRespository.selectAllSerialNumber();
                LOGGER.info("serailNumberList" + serailNumberList);
                List<InventoryItem> inventoryItem = null;
                List<InventoryItem> inventoryItem1 = new ArrayList<>();
                if (fofoId > 0) {
                        List<Item> items = itemRepository.selectAllByBrand("Live Demo");
                        Set<Integer> itemIds = new HashSet<>();
                        for (Item Item : items) {
                                itemIds.add(Item.getId());
                        }
                        inventoryItem = inventoryItemRepository.selectByFofoIdItemIds(fofoId, itemIds);

                        Set<String> serial = new HashSet<>();
                        for (InventoryItem invItem : inventoryItem) {
                                if (!serailNumberList.contains(invItem.getSerialNumber())) {
                                        inventoryItem1.add(invItem);

                                }

                        }

                        LOGGER.info("inventoyItem" + inventoryItem1);
                        model.addAttribute("customRetailers", customRetailers);

                        model.addAttribute("liveDemo", inventoryItem1);
                        CustomRetailer fofoIdsAndRetailerName = retailerService.getFofoRetailer(fofoId);

                        model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);

                }

                else {
                        model.addAttribute("customRetailers", customRetailers);
                        model.addAttribute("liveDemo", inventoryItem1);
                }

                return "live_demo_billing";

        }

        @RequestMapping(value = "/enableliveDemoSerailNumber", method = RequestMethod.POST)
        public String EnableliveDemoSerailNumber(HttpServletRequest request, @RequestParam String serial_number,
                        Model model) throws Exception {

                LiveDemoSerialNumber liveDemoSerialNumber = new LiveDemoSerialNumber();
                liveDemoSerialNumber.setSerialNumber(serial_number);

                liveDemoBillingRespository.persist(liveDemoSerialNumber);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "response";
        }

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

                List<com.spice.profitmandi.dao.entity.transaction.Order> inProcessorder = orderRepository
                                .selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);
                List<Integer> retailerIds = new ArrayList<>();
                List<Integer> orderIds = new ArrayList<>();
                if (!inProcessorder.isEmpty()) {
                        for (com.spice.profitmandi.dao.entity.transaction.Order order : inProcessorder) {
                                retailerIds.add(order.getRetailerId());
                                orderIds.add(order.getId());

                        }

                        List<NotifyOrder> notify = notifyOrderRespository.selectByorderIds(orderIds);
                        for (NotifyOrder notifyOrder : notify) {

                                Order orderdetail = orderRepository.selectById(notifyOrder.getOrderId());
                                if (!orderdetail.getStatus().equals(OrderStatus.SUBMITTED_FOR_PROCESSING)) {
                                        notifyOrder.setStatus(NotifyStatus.rejected);
                                }
                        }

                        Map<Integer, Optional<NotifyOrder>> notifyOrders = notifyOrderRespository.selectByorderIds(orderIds)
                                        .stream().collect(Collectors.groupingBy(NotifyOrder::getOrderId,
                                                        Collectors.maxBy((x1, x2) -> x1.getId() - x2.getId())));

                        Map<Integer, NotifyCancel> notifyCancelOrders = notifyCancelOrderRepository.selectByOrderIds(orderIds)
                                        .stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
                        Map<Integer, String> storeIdAndFofoIdMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
                                        .collect(Collectors.toMap(FofoStore::getId, FofoStore::getCode));

                        model.addAttribute("inProcessorder", inProcessorder);
                        model.addAttribute("storeIdAndFofoIdMap", storeIdAndFofoIdMap);
                        model.addAttribute("latestNotifyOrders", notifyOrders);
                        model.addAttribute("notifyCancelOrders", notifyCancelOrders);
                } else {
                        model.addAttribute("inProcessorder", inProcessorder);
                }
                return "review_order";
        }

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

                List<com.spice.profitmandi.dao.entity.transaction.Order> pendingPaymentorder = orderRepository
                                .selectAllOrderDatesBetweenByStatus(LocalDateTime.now().minusMonths(3), LocalDateTime.now(),
                                                OrderStatus.PAYMENT_PENDING);
                List<com.spice.profitmandi.dao.entity.transaction.Order> failedPaymentorder = orderRepository
                                .selectAllOrderDatesBetweenByStatus(LocalDateTime.now().minusMonths(3), LocalDateTime.now(),
                                                OrderStatus.PAYMENT_FAILED);
                pendingPaymentorder.addAll(failedPaymentorder);
                model.addAttribute("pendingPaymentorder", pendingPaymentorder);

                return "payment-pending-order";
        }

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

                List<com.spice.profitmandi.dao.entity.transaction.Order> keepatab = orderRepository
                                .selectAllOrder(OrderStatus.KEEP_A_TAB);

                model.addAttribute("keepatab", keepatab);

                return "keep-a-tab";
        }

        @RequestMapping(value = "/closeOrder", method = RequestMethod.POST)
        public String closeOrder(HttpServletRequest request, @RequestParam int orderId, Model model) throws Exception {

                Order order = orderRepository.selectById(orderId);
                if (order != null) {
                        order.setStatus(OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);

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

                } else {
                        model.addAttribute("response1", mvcResponseSender.createResponseString(false));

                }
                return "response";
        }

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

                List<Order> inProcessselectedOrder = orderRepository.selectByItemIdOrderStatus(itemId,
                                OrderStatus.SUBMITTED_FOR_PROCESSING);

                List<Integer> retailerIds = new ArrayList<>();
                for (com.spice.profitmandi.dao.entity.transaction.Order order : inProcessselectedOrder) {
                        retailerIds.add(order.getRetailerId());

                }

                Map<Integer, String> storeIdAndFofoIdMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
                                .collect(Collectors.toMap(FofoStore::getId, FofoStore::getCode));

                model.addAttribute("inProcessCancelOrder", inProcessselectedOrder);
                model.addAttribute("storeIdAndFofoIdMap", storeIdAndFofoIdMap);

                return "cancel-order-modal";
        }

        @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
        public String cancelOrder(HttpServletRequest request, @RequestBody OrderCancellationModel orderCancellationModel,
                        Model model) throws Exception {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                LOGGER.info("orderId" + orderCancellationModel.getOrderIds());

                try {
                        // List<Order> orders =
                        // orderRepository.selectByOrderIds(orderCancellationModel.getOrderIds());

                        List<Order> orders = orderRepository.selectByOrderIdsOrdersStatus(orderCancellationModel.getOrderIds(),
                                        OrderStatus.SUBMITTED_FOR_PROCESSING);
                        if (!orders.isEmpty()) {
                                for (Order order : orders) {

                                        orderRepository.refundOrder(order.getId(), loginDetails.getEmailId(),
                                                        orderCancellationModel.getReason(), OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);
                                        List<NotifyOrder> notifyOrders = notifyOrderRespository.selectByOrder(order.getId());
                                        for (NotifyOrder notifyOrder : notifyOrders) {
                                                if (notifyOrder.getStatus() == NotifyStatus.pending) {
                                                        notifyOrder.setStatus(NotifyStatus.rejected);
                                                }
                                        }
                                        sendCancellationNotificationToPartner(order, orderCancellationModel.getReason());
                                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));

                                }
                        }
                } catch (TransactionServiceException | TException e) {
                        model.addAttribute("response1", mvcResponseSender.createResponseString(false));

                }

                return "response";
        }

        private void sendCancellationNotificationToPartner(Order order, String reason) throws Exception {
                Item item = itemRepository.selectById(order.getLineItem().getItemId());

                String title = "Order Cancellation";
                String message = String.format("Order %s %d(Pcs) has been cancelled", item.getItemDescription(),
                                order.getLineItem().getQuantity());

                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(order.getRetailerId());

                Address address = addressRepository.selectById(user.getAddressId());

                SendNotificationModel sendNotificationModel = new SendNotificationModel();
                sendNotificationModel.setCampaignName(title);
                sendNotificationModel.setTitle(message);
                sendNotificationModel.setType("url");
                sendNotificationModel.setMessage(reason);
                sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/orderDetails");
                sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
                sendNotificationModel.setMessageType(MessageType.notification);
                int userId = userAccountRepository.selectUserIdByRetailerId(order.getRetailerId());
                sendNotificationModel.setUserIds(Arrays.asList(userId));
                notificationService.sendNotification(sendNotificationModel);

                // notificationService.sendWhatsappMessage(message, title,
                // address.getPhoneNumber());

        }

        @RequestMapping(value = "/getNotifyItemColor", method = RequestMethod.GET)
        public String getNotifyItemColor(HttpServletRequest request, @RequestParam int catalogItemId,
                        @RequestParam int itemId, Model model) throws ProfitMandiBusinessException {

                List<Item> availableColorItems = itemRepository.selectAllByCatalogItemId(catalogItemId);
                Iterator<Item> itemsIterator = availableColorItems.iterator();

                while (itemsIterator.hasNext()) {
                        Item item = itemsIterator.next();
                        TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());

                        if (itemTagListing == null) {
                                itemsIterator.remove();

                        }

                        else if (!itemTagListing.isActive()) {
                                itemsIterator.remove();

                        }
                }

                List<Order> inProcessselectedOrder = orderRepository.selectByItemIdOrderStatus(itemId,
                                OrderStatus.SUBMITTED_FOR_PROCESSING);
                List<Integer> retailerIds = new ArrayList<>();

                for (com.spice.profitmandi.dao.entity.transaction.Order order : inProcessselectedOrder) {
                        retailerIds.add(order.getRetailerId());

                }

                Map<Integer, String> storeIdAndFofoIdMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
                                .collect(Collectors.toMap(FofoStore::getId, FofoStore::getCode));
                LOGGER.info("item" + availableColorItems);
                model.addAttribute("item", availableColorItems);
                model.addAttribute("inProcessselectedOrder", inProcessselectedOrder);
                model.addAttribute("storeIdAndFofoIdMap", storeIdAndFofoIdMap);

                return "notify-order-modal";
        }

        @RequestMapping(value = "/notifyOrder", method = RequestMethod.POST)
        public String NotifyOrder(HttpServletRequest request, @RequestBody NotifyOrderModel notifyOrderModel, Model model)
                        throws Exception {

                com.spice.profitmandi.dao.entity.transaction.NotifyItem notifyItem = null;
                List<Integer> orderIds = new ArrayList<>();

                NotifyColorChange notifytimestamp = new NotifyColorChange();
                notifytimestamp.setCreated(LocalDateTime.now());
                notifyColorChangeRepository.persist(notifytimestamp);
                NotifyMessage notifyMessage = new NotifyMessage();
                notifyMessage.setNotifyId(notifytimestamp.getId());
                notifyMessage.setNotifyMessages(notifyOrderModel.getMessage());
                notifyMessageRepository.persist(notifyMessage);
                for (NotifyItemIdModel itemid : notifyOrderModel.getItemIds()) {

                        notifyItem = new com.spice.profitmandi.dao.entity.transaction.NotifyItem();
                        notifyItem.setItemId(itemid.getItemId());
                        notifyItem.setResponseTime(itemid.getResponseTime());
                        notifyItem.setProcuredDate(itemid.getProcuredTime());
                        notifyItem.setNotifyColorchangeId(notifytimestamp.getId());
                        notifyItemRepository.persist(notifyItem);
                        LOGGER.info("notifyItem" + notifyItem);
                }
                for (NotifyOrderIdModel st : notifyOrderModel.getOrderIds()) {
                        List<NotifyOrder> existingOrder = notifyOrderRespository.selectByOrder(st.getOrderId());
                        if (!existingOrder.isEmpty()) {
                                LOGGER.info("existingOrder" + existingOrder);
                                for (NotifyOrder notifyOrder : existingOrder) {
                                        if (NotifyStatus.pending == notifyOrder.getStatus()) {
                                                notifyOrder.setStatus(NotifyStatus.rejected);
                                                notifyOrder.setUpdateTimestamp(LocalDateTime.now());
                                        }
                                }
                        }
                        NotifyOrder orderStatus = new NotifyOrder();
                        orderStatus.setOrderId(st.getOrderId());
                        orderStatus.setNotifyId(notifytimestamp.getId());
                        orderStatus.setItemId(st.getOlditemId());
                        Order id = orderRepository.selectById(st.getOrderId());
                        orderStatus.setFofoId(id.getRetailerId());
                        orderStatus.setStatus(NotifyStatus.pending);
                        notifyOrderRespository.persist(orderStatus);

                        LOGGER.info("itemStatus" + orderStatus);
                        orderIds.add(st.getOrderId());
                }

                LOGGER.info("orderIds" + orderIds);
                List<Order> orders = orderRepository.selectByOrderIds(orderIds);
                for (Order order : orders) {
                        LOGGER.info("order" + order.getId());

                        String title = "Alert!";

                        NotifyMessage message = notifyMessageRepository.selectByNotifyId(notifytimestamp.getId());

                        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(order.getRetailerId());

                        Address address = addressRepository.selectById(user.getAddressId());

                        SendNotificationModel sendNotificationModel = new SendNotificationModel();
                        sendNotificationModel.setCampaignName("Notify Partner");
                        sendNotificationModel.setMessage(message.getNotifyMessages());
                        sendNotificationModel.setType("url");
                        sendNotificationModel.setTitle("Alert");
                        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifyOrder");
                        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
                        sendNotificationModel.setMessageType(MessageType.notification);
                        int userId = userAccountRepository.selectUserIdByRetailerId(order.getRetailerId());

                        sendNotificationModel.setUserIds(Arrays.asList(userId));
                        notificationService.sendNotification(sendNotificationModel);

                        // notificationService.sendWhatsappMessage(message.getNotifyMessages(), title,
                        // address.getPhoneNumber());

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

        @RequestMapping(value = "/getAllNotifyOrder", method = RequestMethod.GET)
        public String getAllNotifyOrder(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                List<NotifyOrder> notifyOrders = null;
                List<com.spice.profitmandi.dao.entity.transaction.Order> inProcessorder = orderRepository
                                .selectAllOrder(OrderStatus.SUBMITTED_FOR_PROCESSING);

                List<Integer> orderIds = new ArrayList<>();
                if (!inProcessorder.isEmpty()) {
                        for (com.spice.profitmandi.dao.entity.transaction.Order order : inProcessorder) {

                                orderIds.add(order.getId());

                        }
                        notifyOrders = notifyOrderRespository.selectByorderIds(orderIds);
                        Set<Integer> oldItemIds = new HashSet<>();
                        List<Integer> fofoIds = new ArrayList<>();
                        List<Integer> notifyIds = new ArrayList<>();
                        if (!notifyOrders.isEmpty()) {
                                for (NotifyOrder notifyOrder : notifyOrders) {
                                        oldItemIds.add(notifyOrder.getItemId());
                                        fofoIds.add(notifyOrder.getFofoId());
                                        notifyIds.add(notifyOrder.getNotifyId());
                                }

                                List<NotifyColorChange> notifyColorChanges = notifyColorChangeRepository.selectByNotifyId(notifyIds);
                                Map<Integer, NotifyColorChange> notifyIdNotifyColorMap = this
                                                .notifyOrdersToNotifyId(notifyColorChanges);
                                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                                Map<Integer, CustomRetailer> fofoIdsAndRetailerName = fofoIds.stream().distinct()
                                                .map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream()
                                                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                                Map<Integer, String> itemdescription = inventoryService.getItemIdDescriptionMap(oldItemIds);

                                model.addAttribute("notifyOrders", notifyOrders);
                                model.addAttribute("notifyIdNotifyColorMap", notifyIdNotifyColorMap);
                                model.addAttribute("itemdescription", itemdescription);
                                model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);

                        } else {
                                model.addAttribute("notifyOrders", notifyOrders);
                        }
                } else {
                        model.addAttribute("notifyOrders", notifyOrders);
                }
                return "notify_order";
        }

        private Map<Integer, NotifyColorChange> notifyOrdersToNotifyId(List<NotifyColorChange> notifyColorChanges) {
                Map<Integer, NotifyColorChange> notifyIdNotifyColorMap = new HashMap<>();
                for (NotifyColorChange notifyColorChange : notifyColorChanges) {
                        notifyIdNotifyColorMap.put(notifyColorChange.getId(), notifyColorChange);
                }
                return notifyIdNotifyColorMap;
        }

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

                Set<Integer> itemIds = itemRepository.selectAllByCatalogItemId(catalogItemId).stream().map(x -> x.getId())
                                .collect(Collectors.toSet());

                List<Order> notAvailableProcessingOrder = orderRepository.selectByItemIdsOrderStatus(itemIds,
                                OrderStatus.SUBMITTED_FOR_PROCESSING);
                LOGGER.info("notAvailableProcessingOrder" + notAvailableProcessingOrder);

                List<Integer> retailerIds = new ArrayList<>();
                for (com.spice.profitmandi.dao.entity.transaction.Order order : notAvailableProcessingOrder) {
                        retailerIds.add(order.getRetailerId());

                }

                Map<Integer, String> storeIdAndFofoIdMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
                                .collect(Collectors.toMap(FofoStore::getId, FofoStore::getCode));

                model.addAttribute("notAvailableProcessingOrder", notAvailableProcessingOrder);
                model.addAttribute("storeIdAndFofoIdMap", storeIdAndFofoIdMap);

                return "partner-cancel-order-modal";
        }

        @RequestMapping(value = "/notifyCancelOrder", method = RequestMethod.POST)
        public String NotifyCancelOrder(HttpServletRequest request, @RequestBody NotifyOrderModel notifyOrderModel,
                        Model model) throws Exception {
                for (NotifyOrderIdModel st : notifyOrderModel.getOrderIds()) {
                        LOGGER.info("orderId" + st.getOrderId());
                        Order order = orderRepository.selectById(st.getOrderId());
                        NotifyCancel nc = notifyCancelOrderRepository.selectByOrderId(st.getOrderId());
                        if (nc == null) {
                                nc = new NotifyCancel();
                                nc.setOrderId(st.getOrderId());
                                nc.setItemId(st.getOlditemId());
                                nc.setFofoId(order.getRetailerId());
                                nc.setCancellation(false);
                                nc.setCreatedTimestamp(LocalDateTime.now());
                                nc.setUpdatedTimestamp(LocalDateTime.now());
                                notifyCancelOrderRepository.persist(nc);
                        } else {
                                nc.setOrderId(st.getOrderId());
                                nc.setItemId(st.getOlditemId());
                                nc.setFofoId(order.getRetailerId());
                                nc.setCancellation(false);
                                nc.setUpdatedTimestamp(LocalDateTime.now());
                                notifyCancelOrderRepository.persist(nc);
                        }

                        SendNotificationModel sendNotificationModel = new SendNotificationModel();
                        sendNotificationModel.setCampaignName("Notify Partner");
                        sendNotificationModel.setMessage(notifyOrderModel.getMessage());
                        sendNotificationModel.setType("url");
                        sendNotificationModel.setTitle("Alert");
                        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifyCancelOrder");
                        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
                        sendNotificationModel.setMessageType(MessageType.notification);
                        int userId = userAccountRepository.selectUserIdByRetailerId(order.getRetailerId());

                        sendNotificationModel.setUserIds(Arrays.asList(userId));
                        notificationService.sendNotification(sendNotificationModel);

                }

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

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

                List<NotifyCancel> notifyCancels = notifyCancelOrderRepository.selectAllNonCancelOrder();
                if (!notifyCancels.isEmpty()) {
                        List<Integer> retailerIds = new ArrayList<>();
                        Set<Integer> itemIds = new HashSet<>();
                        for (NotifyCancel nc : notifyCancels) {
                                retailerIds.add(nc.getFofoId());
                                itemIds.add(nc.getItemId());
                        }

                        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();

                        Map<Integer, CustomRetailer> fofoIdsAndRetailerName = retailerIds.stream()
                                        .map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream()
                                        .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
                        Map<Integer, String> itemdescription = inventoryService.getItemIdDescriptionMap(itemIds);
                        model.addAttribute("notifyCancels", notifyCancels);
                        model.addAttribute("itemdescription", itemdescription);
                        model.addAttribute("fofoIdsAndRetailerName", fofoIdsAndRetailerName);
                } else {

                        model.addAttribute("notifyCancels", notifyCancels);

                }
                return "notify_cancel";
        }

        @RequestMapping(value = "/getNotifyItems", method = RequestMethod.GET)
        public String getNotifyItems(HttpServletRequest request, @RequestParam int itemId, Model model) throws Exception {
                Item item = itemRepository.selectById(itemId);

                List<Integer> itemIds = itemRepository.selectAllByCatalogItemId(item.getCatalogItemId()).stream()
                                .map(x -> x.getId()).collect(Collectors.toList());

                List<NotifyCancel> ncs = notifyCancelOrderRepository.selectByItemIdsAndStatus(itemIds);
                List<Integer> retailerIds = new ArrayList<>();
                Map<Integer, Object> orders = new HashMap<>();
                for (NotifyCancel nc : ncs) {
                        retailerIds.add(nc.getFofoId());
                        Order od = orderRepository.selectById(nc.getOrderId());
                        orders.put(nc.getOrderId(), od);
                }

                Map<Integer, String> storeIdAndFofoIdMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
                                .collect(Collectors.toMap(FofoStore::getId, FofoStore::getCode));

                model.addAttribute("notifyItems", ncs);
                model.addAttribute("orders", orders);
                model.addAttribute("storeIdAndFofoIdMap", storeIdAndFofoIdMap);

                return "notify_cancel_order_modal";
        }

        @RequestMapping(value = "/changeNotifyCancelRequest", method = RequestMethod.POST)
        public String changeNotifyCancelRequest(HttpServletRequest request, @RequestBody NotifyOrderModel notifyOrderModel,
                        Model model) throws Exception {
                List<Integer> orderIds = notifyOrderModel.getOrderIds().stream().map(x -> x.getOrderId())
                                .collect(Collectors.toList());

                List<NotifyCancel> ncs = notifyCancelOrderRepository.selectByOrderIds(orderIds);
                for (NotifyCancel nc : ncs) {
                        nc.setCancellation(true);
                }

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

        @RequestMapping(value = "/getProducts", method = RequestMethod.GET)
        public String getProducts(HttpServletRequest request, Model model)
                        throws ProfitMandiBusinessException, URISyntaxException, IOException {

                return "product-detail";
        }

        @RequestMapping(value = "/getProductInfo", method = RequestMethod.GET)
        public String getProductInfo(HttpServletRequest request, long catalogId, Model model) throws Exception {
                ContentPojo cp = mongoClient.getEntityById(catalogId);
                model.addAttribute("cp", cp);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "product-info";
        }

        @RequestMapping(value = "/getProductCompareInfo", method = RequestMethod.GET)
        public String getProductCompareInfo(HttpServletRequest request, @RequestParam List<Long> catalogIds, Model model)
                        throws Exception {
                List<ContentPojo> cps = new ArrayList<>();
                Set<Integer> cataogIds = catalogIds.stream().mapToInt(Long::intValue).boxed().collect(Collectors.toSet());
                LOGGER.info("tagListingMOP" + cataogIds);
                for (Long cId : catalogIds) {
                        ContentPojo cp = mongoClient.getEntityById(cId);
                        if (cp.getName() == null) {
                                cp.setName(itemRepository.selectAllByCatalogItemId(cId.intValue()).get(0).getItemDescriptionNoColor());
                        }
                        List<Item> items = itemRepository.selectAllByCatalogItemId(cId.intValue());
                        LOGGER.info("itemsMop" + items);
                        int i = 0;
                        for (Item item : items) {
                                TagListing tagListing = tagListingRepository.selectByItemId(items.get(i).getId());

                                if (tagListing != null) {
                                        cp.setPrice(tagListing.getMop());

                                        LOGGER.info("tagListingMOP" + tagListing);

                                        break;

                                }
                                i++;
                        }
                        cps.add(cp);

                }

                List<Map<String, String>> entityList = new ArrayList<>();
                for (ContentPojo cp : cps) {
                        Map<String, String> specsMap = new HashMap<>();
                        for (SpecificationGroup sg : cp.getDetailedSpecs()) {
                                String title = sg.getTitle();
                                for (Specification s : sg.getSpecs()) {
                                        String key = title + s.getName();
                                        specsMap.put(key, String.join(", ", s.getValues()));
                                }
                        }
                        entityList.add(specsMap);

                }

                LOGGER.info("cps" + cps);
                model.addAttribute("cps", cps);
                model.addAttribute("catalogIds", gson.toJson(catalogIds, List.class));
                model.addAttribute("entityList", entityList);
                return "product-compare";
        }

        @RequestMapping(value = "/inventory", method = RequestMethod.GET)
        public String Inventory(HttpServletRequest request,
                        @RequestParam(name = "warehouseIds", required = true, defaultValue = "0") List<Integer> warehouseIds,
                        Model model) throws Exception {
                model.addAttribute("warehouseId", warehouseIds);
                LOGGER.info("warehouseIds" + warehouseIds);

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                if (warehouseIds.contains(0)) {
                        warehouseIds.addAll(warehouseMap.keySet());
                }

                long poTodayValue = 0;
                long poThreedaysValue = 0;
                long poSevendaysValue = 0;
                long poTodayQty = 0;
                long poThreedaysQty = 0;
                long poSevendaysQty = 0;

                List<OpenPoModel> openPO = warehousePurchaseOrderRepository.selectOpenPo(warehouseIds);
                for (OpenPoModel po : openPO) {
                        poTodayValue += po.getTodayValue();
                        poThreedaysValue += po.getThreedaysValue();
                        poSevendaysValue += po.getSevendaysValue();
                        poTodayQty += po.getTodayQty();
                        poThreedaysQty += po.getThreedaysQty();
                        poSevendaysQty += po.getSevendaysQty();
                }
                OpenPoModel poModel = new OpenPoModel();
                poModel.setBrand("Total Values");
                poModel.setTodayValue(poTodayValue);
                poModel.setThreedaysValue(poThreedaysValue);
                poModel.setSevendaysValue(poSevendaysValue);
                poModel.setSevendaysQty(poSevendaysQty);
                poModel.setThreedaysQty(poThreedaysQty);
                poModel.setTodayQty(poTodayQty);
                openPO.add(poModel);

                long purtodayValue = 0;
                long purthreedaysValue = 0;
                long purlmsValue = 0;
                long purmtd = 0;
                long purtodayQty = 0;
                long purthreedaysQty = 0;
                long purlmsQty = 0;
                long purmtdQty = 0;

                List<OurPurchaseModel> purchase = warehouseScanRepository.selectOurPurchase(warehouseIds);

                for (OurPurchaseModel pm : purchase) {
                        purtodayValue += pm.getTodayValue();
                        purthreedaysValue += pm.getThreedaysValue();
                        purlmsValue += pm.getLms();
                        purmtd += pm.getMtd();
                        purtodayQty += pm.getTodayQty();
                        purthreedaysQty += pm.getThreedaysQty();
                        purlmsQty += pm.getLmsQty();
                        purmtdQty += pm.getMtdQty();
                }
                OurPurchaseModel omp = new OurPurchaseModel();
                omp.setBrand("Total Values");
                omp.setTodayValue(purtodayValue);
                omp.setThreedaysValue(purthreedaysValue);
                omp.setLms(purlmsValue);
                omp.setMtd(purmtd);
                omp.setTodayQty(purtodayQty);
                omp.setThreedaysQty(purthreedaysQty);
                omp.setLmsQty(purlmsQty);
                omp.setMtdQty(purmtdQty);
                purchase.add(omp);

                List<BrandWiseTertiaryModel> tertiary = fofoOrderRepository.selectGroupByBrandPartnerTertiary(warehouseIds);
                long tertodayValue = 0;
                long terthreedaysValue = 0;
                long termtd = 0;
                long terlmtd = 0;
                long terlms = 0;
                long tertodayQty = 0;
                long terthreedaysQty = 0;
                long termtdQty = 0;
                long terlmtdQty = 0;
                long terlmsQty = 0;
                for (BrandWiseTertiaryModel btm : tertiary) {
                        tertodayValue += btm.getTodayValue();
                        terthreedaysValue += btm.getThreedaysValue();
                        termtd += btm.getMtd();
                        terlmtd += btm.getLmtd();
                        terlms += btm.getLms();
                        tertodayQty += btm.getTodayQty();
                        terthreedaysQty += btm.getThreedaysQty();
                        termtdQty += btm.getMtdQty();
                        terlmtdQty += btm.getLmtdQty();
                        terlmsQty += btm.getLmsQty();
                }
                BrandWiseTertiaryModel bwt = new BrandWiseTertiaryModel();
                bwt.setBrand("Total Values");
                bwt.setTodayValue(tertodayValue);
                bwt.setThreedaysValue(terthreedaysValue);
                bwt.setMtd(termtd);
                bwt.setLmtd(terlmtd);
                bwt.setLms(terlms);
                bwt.setTodayQty(tertodayQty);
                bwt.setThreedaysQty(terthreedaysQty);
                bwt.setMtdQty(termtdQty);
                bwt.setLmtdQty(terlmtdQty);
                bwt.setLmsQty(terlmsQty);
                tertiary.add(bwt);

                List<SecondaryOrderBillingModel> billing = orderRepository.selectAllBilledOrderGroupByBrand(warehouseIds);
                long sectodayValue = 0;
                long secthreedaysValue = 0;
                long secmtd = 0;
                long seclmtd = 0;
                long seclms = 0;
                long sectodayQty = 0;
                long secthreedaysQty = 0;
                long secmtdQty = 0;
                long seclmtdQty = 0;
                long seclmsQty = 0;
                for (SecondaryOrderBillingModel sbm : billing) {
                        sectodayValue += sbm.getTodayValue();
                        secthreedaysValue += sbm.getThreedaysValue();
                        secmtd += sbm.getMtd();
                        seclmtd += sbm.getLmtd();
                        seclms += sbm.getLms();
                        sectodayQty += sbm.getTodayQty();
                        secthreedaysQty += sbm.getThreedaysQty();
                        secmtdQty += sbm.getMtdQty();
                        seclmtdQty += sbm.getLmtdQty();
                        seclmsQty += sbm.getLmsQty();
                }

                SecondaryOrderBillingModel som = new SecondaryOrderBillingModel();
                som.setBrand("Total Values");
                som.setTodayValue(sectodayValue);
                som.setThreedaysValue(secthreedaysValue);
                som.setMtd(secmtd);
                som.setLmtd(seclmtd);
                som.setLms(seclms);
                som.setTodayQty(sectodayQty);
                som.setThreedaysQty(secthreedaysQty);
                som.setMtdQty(secmtdQty);
                som.setLmtdQty(seclmtdQty);
                som.setLmsQty(seclmsQty);
                billing.add(som);
                LOGGER.info("openPO" + openPO);
                LOGGER.info("purchase" + purchase);
                LOGGER.info("tertiary" + tertiary);
                LOGGER.info("billing" + billing);

                LOGGER.info("warehouseIds" + warehouseIds);
                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("openPO", openPO);
                model.addAttribute("purchase", purchase);
                model.addAttribute("tertiary", tertiary);
                model.addAttribute("billing", billing);

                return "inventory-listing";

        }

        @RequestMapping(value = "/getOpenPoItemByBrand", method = RequestMethod.GET)
        public String Inventory(HttpServletRequest request,
                        @RequestParam(name = "warehouseIds", required = true, defaultValue = "0") List<Integer> warehouseIds,
                        @RequestParam(name = "brand", required = true, defaultValue = "") List<String> brand, int timeValue,
                        Model model) throws Exception {
                model.addAttribute("warehouseId", warehouseIds);
                LOGGER.info("warehouseIds" + warehouseIds);

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                if (warehouseIds.contains(0)) {
                        warehouseIds.addAll(warehouseMap.keySet());
                }
                LOGGER.info("brand" + brand);

                if (brand.contains("Total Values")) {
                        List<String> poBrands = warehousePurchaseOrderRepository.selectOpenPo(warehouseIds).stream()
                                        .map(x -> x.getBrand()).collect(Collectors.toList());

                        brand.addAll(poBrands);
                }

                LOGGER.info("brand" + brand);
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                List<OpenPoItemModel> openPOItem = null;
                if (timeValue != 0) {
                        openPOItem = warehousePurchaseOrderRepository.selectOpenPoItem(warehouseIds, brand,
                                        curDate.minusDays(timeValue), curDate);
                } else {
                        openPOItem = warehousePurchaseOrderRepository.selectTodayOpenPoItem(warehouseIds, brand, curDate);
                }
                LOGGER.info("openPOItem" + openPOItem);

                model.addAttribute("openPOItem", openPOItem);

                return "inventory-listing-po-item";

        }

        @RequestMapping(value = "/getOurPurchaseItemByBrand", method = RequestMethod.GET)
        public String getOurPurchaseItemByBrand(HttpServletRequest request,
                        @RequestParam(name = "warehouseIds", required = true, defaultValue = "0") List<Integer> warehouseIds,
                        @RequestParam(name = "brand", required = true, defaultValue = "") List<String> brand, int timeValue,
                        Model model) throws Exception {
                model.addAttribute("warehouseId", warehouseIds);
                LOGGER.info("warehouseIds" + warehouseIds);

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                if (warehouseIds.contains(0)) {
                        warehouseIds.addAll(warehouseMap.keySet());
                }
                LocalDateTime curDate = LocalDate.now().atStartOfDay();

                if (brand.contains("Total Values")) {
                        List<String> purchasebrands = warehouseScanRepository.selectOurPurchase(warehouseIds).stream()
                                        .map(x -> x.getBrand()).collect(Collectors.toList());

                        brand.addAll(purchasebrands);
                }
                List<OurPurchaseItemModel> ourPurchaseItem = null;
                if (timeValue != 0) {
                        if (timeValue == 1) {
                                ourPurchaseItem = warehouseScanRepository.selectOurPurchaseItemByBrand(warehouseIds, brand,
                                                curDate.withDayOfMonth(1), curDate.plusDays(1));

                        } else if (timeValue == -1) {

                                ourPurchaseItem = warehouseScanRepository.selectOurPurchaseItemByBrand(warehouseIds, brand,
                                                curDate.minusMonths(1).withDayOfMonth(1), curDate.withDayOfMonth(1));

                        } else {
                                ourPurchaseItem = warehouseScanRepository.selectOurPurchaseItemByBrand(warehouseIds, brand,
                                                curDate.minusDays(timeValue), curDate);

                        }
                } else {
                        ourPurchaseItem = warehouseScanRepository.selectTodayOurPurchaseItemByBrand(warehouseIds, brand, curDate);
                }
                LOGGER.info("ourPurchaseItem" + ourPurchaseItem);

                model.addAttribute("ourPurchaseItem", ourPurchaseItem);
                model.addAttribute("warehouseMap", warehouseMap);

                return "inventory-listing-purchase-item";

        }

        @RequestMapping(value = "/getWarehouseWiseSecondaryBillingByBrand", method = RequestMethod.GET)
        public String getWarehouseWiseSecondaryBillingByBrand(HttpServletRequest request,
                        @RequestParam(name = "brand", required = true, defaultValue = "") String brand, int timeValue, Model model)
                        throws Exception {

                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                int dayOfMonth = curDate.getDayOfMonth();
                LocalDateTime startOfMonth = curDate.withDayOfMonth(1);
                int lengthOfMonth = YearMonth.from(startOfMonth.minusMonths(1)).lengthOfMonth();

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                SecondaeryOrderDateRange sr = null;
                if (brand.equals("Total Values")) {
                        brand = null;
                }
                if (timeValue != 0) {
                        if (timeValue == 1) {

                                sr = getSecondaryModel(brand, curDate.withDayOfMonth(1), curDate.plusDays(1));

                        } else if (timeValue == 2) {
                                LOGGER.info("curDate" + curDate.withDayOfMonth(1).minusMonths(1));
                                LOGGER.info("curDate" + curDate.minusMonths(1).plusDays(Math.min(dayOfMonth, lengthOfMonth)));

                                sr = getSecondaryModel(brand, curDate.withDayOfMonth(1).minusMonths(1),
                                                startOfMonth.minusMonths(1).plusDays(Math.min(dayOfMonth, lengthOfMonth)));

                        } else if (timeValue == -1) {

                                sr = getSecondaryModel(brand, curDate.minusMonths(1).withDayOfMonth(1), startOfMonth);

                        } else {

                                sr = getSecondaryModel(brand, curDate.minusDays(timeValue), curDate);
                        }

                } else {
                        sr = getSecondaryModel(brand, curDate, curDate.plusDays(1));
                }

                Map<BrandRegionModel, Map<LocalDate, SecondaryWarehouseWiseOrderBilllingModel>> brandWarehouseOrderMap = sr
                                .getSecondaryModel().stream()
                                .collect(Collectors.groupingBy(x -> new BrandRegionModel(x.getWarehouseId(), x.getBrand()),
                                                Collectors.collectingAndThen(Collectors.toList(),
                                                                x -> x.stream().collect(Collectors.toMap(y -> y.getBillingTimestamp(), y -> y)))));

                Map<LocalDate, Integer> dateWiseTotal = sr.getSecondaryModel().stream().collect(
                                Collectors.groupingBy(x -> x.getBillingTimestamp(), Collectors.summingInt(x -> (int) x.getValue())));

                Map<LocalDate, Integer> dateWiseQtyTotal = sr.getSecondaryModel().stream().collect(
                                Collectors.groupingBy(x -> x.getBillingTimestamp(), Collectors.summingInt(x -> (int) x.getQty())));

                LOGGER.info("dateWiseTotal" + dateWiseTotal);

                brandWarehouseOrderMap.entrySet().stream().forEach(x -> {
                        x.getKey().setTotal(x.getValue().entrySet().stream()
                                        .collect(Collectors.summingInt(y -> (int) y.getValue().getValue())));
                });

                brandWarehouseOrderMap.entrySet().stream().forEach(x -> {
                        x.getKey().setQty(
                                        x.getValue().entrySet().stream().collect(Collectors.summingInt(y -> (int) y.getValue().getQty())));
                });
                LOGGER.info("brandWarehouseOrderMap" + brandWarehouseOrderMap);

                model.addAttribute("brandWarehouseOrderMap", brandWarehouseOrderMap);
                model.addAttribute("dateWiseTotal", dateWiseTotal);
                model.addAttribute("dateWiseQtyTotal", dateWiseQtyTotal);
                model.addAttribute("dateRange", sr.getDateRange());
                model.addAttribute("warehouseMap", warehouseMap);
                return "secondary-warehouse-billing-order";

        }

        public SecondaeryOrderDateRange getSecondaryModel(String brand, LocalDateTime startDate, LocalDateTime endDate) {

                SecondaeryOrderDateRange sr = new SecondaeryOrderDateRange();
                List<SecondaryWarehouseWiseOrderBilllingModel> secondaryOrderbilling = orderRepository
                                .selectAllBilledOrderGroupByBrandWarehouse(brand, startDate, endDate).stream()
                                .sorted(Comparator.comparing(SecondaryWarehouseWiseOrderBilllingModel::getBillingTimestamp))
                                .collect(Collectors.toList());
                long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);

                List<LocalDate> dateRange = Stream.iterate(startDate.toLocalDate(), date -> date.plusDays(1))
                                .limit(noOfDaysBetween).collect(Collectors.toList());

                sr.setDateRange(dateRange);
                sr.setSecondaryModel(secondaryOrderbilling);

                return sr;

        }

        @RequestMapping(value = "/getSecondaryBillingItemByBrand", method = RequestMethod.GET)
        public String getSecondaryBillingItemByBrand(HttpServletRequest request,
                        @RequestParam(name = "warehouseId", required = true, defaultValue = "0") int warehouseId,
                        @RequestParam(name = "brand", required = true, defaultValue = "") String brand,
                        @RequestParam List<LocalDate> date, Model model) throws Exception {

                List<SecondaryOrderItemBillingModel> orderItemBilling = orderRepository
                                .selectAllBilledOrderItemByBrand(warehouseId, brand, date);

                LOGGER.info("orderItemBilling" + orderItemBilling);
                model.addAttribute("billedItem", orderItemBilling);
                model.addAttribute("date", date);
                model.addAttribute("brand", brand);
                return "inventory-listing-billing-item";

        }

        @RequestMapping(value = "/getPartnerTertiaryItemByBrand", method = RequestMethod.GET)
        public String getPartnerTertiaryItemByBrand(HttpServletRequest request,
                        @RequestParam(name = "warehouseIds", required = true, defaultValue = "0") List<Integer> warehouseIds,
                        @RequestParam(name = "brand", required = true, defaultValue = "") List<String> brand, int timeValue,
                        Model model) throws Exception {
                model.addAttribute("warehouseId", warehouseIds);
                LOGGER.info("warehouseIds" + warehouseIds);

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
                if (warehouseIds.contains(0)) {
                        warehouseIds.addAll(warehouseMap.keySet());
                }
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
                int dayOfMonth = curDate.getDayOfMonth();
                LocalDateTime startOfMonth = curDate.withDayOfMonth(1);
                int lengthOfMonth = YearMonth.from(startOfMonth.minusMonths(1)).lengthOfMonth();
                if (brand.contains("Total Values")) {
                        List<String> tertiaryBrands = fofoOrderRepository.selectGroupByBrandPartnerTertiary(warehouseIds).stream()
                                        .map(x -> x.getBrand()).collect(Collectors.toList());

                        brand.addAll(tertiaryBrands);
                }
                List<BrandItemWiseTertiaryModel> tertiaryItem = null;
                if (timeValue != 0) {
                        if (timeValue == 1) {

                                tertiaryItem = fofoOrderRepository.selectItemPartnerTertiaryByBrand(warehouseIds, brand,
                                                curDate.withDayOfMonth(1), curDate.plusDays(1));

                        } else if (timeValue == 2) {
                                LOGGER.info("curDate" + startOfMonth.minusMonths(1));
                                LOGGER.info("curDate" + startOfMonth.minusMonths(1).plusDays(Math.min(dayOfMonth, lengthOfMonth)));

                                tertiaryItem = fofoOrderRepository.selectItemPartnerTertiaryByBrand(warehouseIds, brand,
                                                startOfMonth.minusMonths(1),
                                                startOfMonth.minusMonths(1).plusDays(Math.min(dayOfMonth, lengthOfMonth)));

                        } else if (timeValue == -1) {
                                LOGGER.info("date" + curDate.minusMonths(1).withDayOfMonth(1));
                                LOGGER.info("date" + curDate.minusMonths(1).withDayOfMonth(lengthOfMonth).plusDays(1));

                                tertiaryItem = fofoOrderRepository.selectItemPartnerTertiaryByBrand(warehouseIds, brand,
                                                curDate.minusMonths(1).withDayOfMonth(1), startOfMonth);
                        } else {
                                tertiaryItem = fofoOrderRepository.selectItemPartnerTertiaryByBrand(warehouseIds, brand,
                                                curDate.minusDays(timeValue), curDate);
                        }

                } else {
                        tertiaryItem = fofoOrderRepository.selectTodayItemPartnerTertiaryByBrand(warehouseIds, brand, curDate);
                }
                LOGGER.info("tertiaryItem" + tertiaryItem);

                model.addAttribute("tertiaryItem", tertiaryItem);

                return "inventory-item-tertiary-item";

        }

        @RequestMapping(value = "/planogram")
        public String Planogram(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                String email = loginDetails.getEmailId();
                AuthUser authUser = authRepository.selectByEmailOrMobile(email);
                List<FocusedModelByPassRequest> byPassRequest = null;
                Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();

                Set<Integer> authfofoIds = null;

                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());

                if (emails.contains(authUser.getEmailId())) {
                        authfofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
                        LOGGER.info("fofoIds" + authfofoIds);
                } else {

                        for (Position ps : positions) {
                                if (esclationType.contains(ps.getEscalationType())) {
                                        authfofoIds = storeGuyMap.get(email);
                                        break;
                                }

                        }
                }
                if (authfofoIds != null) {
                        byPassRequest = focusedModelByPassRepository.selectByStatusAndFofoIds(new ArrayList<>(authfofoIds),
                                        ByPassRequestStatus.PENDING);
                }
                Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
                model.addAttribute("customRetailerMap", customRetailerMap);
                model.addAttribute("byPassRequest", byPassRequest);
                return "planogram";
        }

        @RequestMapping(value = "/byPassRequestAction", method = RequestMethod.PUT)
        public String addAmountToWalletRequestRejected(HttpServletRequest request,
                        @RequestParam(name = "id", defaultValue = "0") int id, @RequestParam ByPassRequestStatus status,
                        @RequestParam(name = "reason", required = false) String reason, Model model) throws Exception {

                FocusedModelByPassRequest byPassRequest = focusedModelByPassRepository.selectById(id);
                if (status.equals(ByPassRequestStatus.APPROVED)) {
                        byPassRequest.setByPass(true);
                        byPassRequest.setStatus(ByPassRequestStatus.APPROVED);
                        byPassRequest.setUpdatedTimestamp(LocalDateTime.now());
                        byPassRequest.setReason(reason);
                } else if (status.equals(ByPassRequestStatus.REJECTED)) {
                        byPassRequest.setByPass(false);
                        byPassRequest.setStatus(ByPassRequestStatus.REJECTED);
                        byPassRequest.setUpdatedTimestamp(LocalDateTime.now());
                        byPassRequest.setReason(reason);
                }

                com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(byPassRequest.getFofoId());

                Address address = addressRepository.selectById(user.getAddressId());

                String title = "Billing Request";

                String message = String.format("Your Billing  Request is " + status
                                + ". Please ensure to order the missing focus models as soon as possible.");

                SendNotificationModel sendNotificationModel = new SendNotificationModel();
                sendNotificationModel.setCampaignName("Billing Request");
                sendNotificationModel.setTitle(title);
                sendNotificationModel.setMessage(message);
                sendNotificationModel.setType("url");
                sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
                sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
                sendNotificationModel.setMessageType(MessageType.notification);
                sendNotificationModel
                                .setUserIds(Arrays.asList(userAccountRepository.selectUserIdByRetailerId(byPassRequest.getFofoId())));

                notificationService.sendNotification(sendNotificationModel);

                notificationService.sendWhatsappMessage(message, title, address.getPhoneNumber());

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

        @RequestMapping(value = "/highDemandItem", method = RequestMethod.GET)
        public String highDemandItem(HttpServletRequest request, Model model) throws Exception {
                List<HighDemandItem> hdis = highDemandItemsRepository.selectAll();
                if (!hdis.isEmpty()) {
                        Map<Integer, Item> itemMap = this.getItemByCatalogId(hdis);
                        model.addAttribute("itemMap", itemMap);
                }

                model.addAttribute("hdis", hdis);

                return "high_demand_item";
        }

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

                return itemMap;
        }

        @RequestMapping(value = "/addHighDemandItem", method = RequestMethod.POST)
        public String addHighDemandItem(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int qty,
                        Model model) throws Exception {
                HighDemandItem hdi = highDemandItemsRepository.selectByFofoIdAndCatalogId(catalogId);

                if (hdi == null) {
                        hdi = new HighDemandItem();
                        hdi.setCatalogId(catalogId);
                        hdi.setQty(qty);
                        hdi.setCreateTimestamp(LocalDateTime.now());
                        hdi.setUpdateTimestamp(LocalDateTime.now());
                        highDemandItemsRepository.persist(hdi);
                }

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

        @RequestMapping(value = "/removeHighDemandItem", method = RequestMethod.DELETE)
        public String removeHighDemandItem(HttpServletRequest request,
                        @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
                highDemandItemsRepository.deleteById(id);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));
                return "response";
        }

        @GetMapping(value = "/imei")
        public String getImei(HttpServletRequest request, Model model, @RequestParam int fofoId, @RequestParam String query)
                        throws Exception {

                List<String> serialNumber = inventoryItemRepository.selectAllByFofoId(fofoId, query).stream()
                                .map(x -> x.getSerialNumber()).collect(Collectors.toList());
                LOGGER.info("serialNumber" + serialNumber);
                LOGGER.info("query" + query);

                model.addAttribute("response1", mvcResponseSender.createResponseString(serialNumber));

                return "response";
        }

        @Autowired
        private ObjectMapper objectMapper;

        @RequestMapping(value = "/imei/validate", method = RequestMethod.GET)
        public String validateImei(HttpServletRequest request, @RequestParam String imei, Model model) throws Exception {
                boolean isImei = false;

                try {
                        InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(imei);

                        isImei = true;

                } catch (Exception e) {
                        isImei = false;
                }

                model.addAttribute("response1", objectMapper.writeValueAsString(isImei));
                return "response";
        }

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

                Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;

                List<ComboModel> comboModels = comboModelRepository.selectAll();

                model.addAttribute("warehouseMap", warehouseMap);
                model.addAttribute("comboModels", comboModels);
                return "create-combo";
        }

        @RequestMapping(value = "/addCombo", method = RequestMethod.POST)
        public String addCombo(HttpServletRequest request, @RequestBody Combo combo, Model model) throws Exception {

                for (Integer warehouseId : combo.getWarehouseId()) {

                        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(combo.getCatalogId(),
                                        warehouseId, combo.getQty());
                        if (comboModel != null) {
                                List<ComboMappedModel> comboMappedModels = comboMappedModelRepository
                                                .selectByComboId(comboModel.getId());
                                for (ComboMappedModel comboMappedModel : comboMappedModels) {
                                        comboMappedModelRepository.delete(comboMappedModel);
                                }

                                comboModelRepository.delete(comboModel);
                        }
                        ComboModel cm = new ComboModel();
                        cm.setCatalogId(combo.getCatalogId());
                        cm.setQty(combo.getQty());
                        cm.setWarehouseId(warehouseId);
                        comboModelRepository.persist(cm);

                        LOGGER.info("cm" + cm);

                        for (MappedComboModel mcc : combo.getMappedComboModel()) {
                                ComboMappedModel cmm = new ComboMappedModel();
                                cmm.setComboCatalogId(mcc.getCatalogId());
                                cmm.setComboQty(mcc.getQty());
                                cmm.setComboId(cm.getId());
                                comboMappedModelRepository.persist(cmm);

                        }

                }

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

                return "response";

        }

        @RequestMapping(value = "/combo/remove", method = RequestMethod.POST)
        public String removeCombo(HttpServletRequest request, @RequestParam int id, Model model) throws Exception {
                comboMappedModelRepository.deleteByEquals(id);
                comboModelRepository.deleteById(id);
                model.addAttribute("response1", mvcResponseSender.createResponseString(true));

                return "response";

        }
}