Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.thrift.TException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.enumuration.CounterSize;
import com.spice.profitmandi.common.enumuration.IndentStatus;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BrandPerformance;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.ItemIdAvailability;
import com.spice.profitmandi.common.model.StockAllocationModel;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.IndentItem;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.entity.user.User;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.IndentItemRepository;
import com.spice.profitmandi.dao.repository.dtr.IndentRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
import com.spice.profitmandi.dao.repository.user.UserRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.StockAllocationService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.thrift.clients.PaymentClient;
import com.spice.profitmandi.thrift.clients.TransactionClient;
import com.spice.profitmandi.thrift.clients.UserClient;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

import in.shop2020.logistics.PickUpType;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionService;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.user.ItemPriceQuantity;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.model.v1.user.UserContextService.Client;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;

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

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

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

        @Autowired
        private CookiesProcessor cookiesProcessor;
        
        @Autowired
        private UserWalletRepository userWalletRepository;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private IndentRepository indentRepository;

        @Autowired
        private StockAllocationService stockAllocationService;

        @Autowired
        private IndentItemRepository indentItemRepository;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private TagListingRepository tagListingRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private PurchaseRepository purchaseRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        RoleManager roleManager;

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

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

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

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

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

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

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

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

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

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

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

                Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                Map<Integer, Integer> itemsInTransit = null;
                LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
                List<TagListing> tagListings = tagListingRepository.selectAll(true);
                if (!roleManager.isAdmin(roleIds)) {
                        tagListings = new ArrayList<>(tagListings);
                        List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
                        inTransitOrders = this.filterValidOrders(inTransitOrders);
                        itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
                } else {
                        itemsInTransit = new HashMap<>();
                }
                Iterator<TagListing> iterator = tagListings.iterator();
                int totalPcs = 0;
                int toBeOrdered = 0;
                float totalAmount = 0;
                while (iterator.hasNext()) {
                        TagListing tagListing = iterator.next();
                        LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
                        Item item = itemRepository.selectById(tagListing.getItemId());
                        if (roleManager.isAdmin(roleIds)) {
                                if (item.getBrand() == null || item.getCategoryId() == 0) {
                                        iterator.remove();
                                        continue;
                                }
                        } else {
                                if (!itemCisMap.containsKey(tagListing.getItemId())
                                                && !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
                                        iterator.remove();
                                        continue;
                                }
                        }
                        ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
                        tagListing.setStockInHand(itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability());
                        StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());

                        if (itemsInTransit.containsKey(tagListing.getItemId())) {
                                tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
                        } else {
                                tagListing.setInTransitQuantity(0);
                        }
                        if (stockAllocationModel != null) {
                                tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
                                toBeOrdered = Math.max(tagListing.getAllocatedQuantity() - tagListing.getInTransitQuantity()
                                                - tagListing.getStockInHand(), 0);
                                totalPcs += toBeOrdered;
                                totalAmount += toBeOrdered * tagListing.getSellingPrice();
                                tagListing.setToBeOrdered(toBeOrdered);
                        } else {
                                tagListing.setAllocatedQuantity(0);
                        }
                        tagListing.setBrand(item.getBrand());
                        tagListing.setItemDescription(item.getItemDescription());
                        if (item.getCategoryId() == 10006) {
                                tagListing.setCategoryId(item.getCategoryId());
                        }
                        // LOGGER.info(" tagListing.setAllocatedQuantity {}",
                        // tagListing.getAllocatedQuantity());
                }

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

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

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

                List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
                                .collect(Collectors.toList());
                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
                if (fofoId > 0) {
                        CustomRetailer customRetailer = customRetailersMap.get(fofoId);
                        model.addAttribute("retailerName",
                                        customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
                        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
                        model.addAttribute("retailerId", customRetailer.getPartnerId());
                        model.addAttribute("counterSize", fs.getCounterSize().toString());
                } else {
                        model.addAttribute("counterSize", counterSize.toString());
                }
                String customRetailers = JSONObject.valueToString(customRetailersMap.values());
                LOGGER.info("Custom retailers {}", customRetailers);
                Comparator<TagListing> firstCmp = Comparator
                                .comparing(x -> ((x.getAllocatedQuantity() - x.getStockInHand() - x.getInTransitQuantity() == 0)
                                                ? Integer.MIN_VALUE
                                                : (x.getAllocatedQuantity() - x.getStockInHand())), Comparator.reverseOrder());
                model.addAttribute("tagListings", tagListings.stream().sorted(firstCmp).collect(Collectors.toList()));
                model.addAttribute("customRetailers", customRetailers);
                model.addAttribute("brandPerformanceList", brandPerformanceList);
                model.addAttribute("accsBrandPerformanceList", accsBrandPerformanceList);
                model.addAttribute("counterSizes", CounterSize.values());
                model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
                model.addAttribute("totalAmount", totalAmount);
                model.addAttribute("totalPcs", totalPcs);
                model.addAttribute("walletAmount", userWalletRepository.selectByRetailerId(fofoId).getAmount());
                // model.addAttribute("itemCisMap", itemCisMap);
                return "open-indent";
        }

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

                                }
                        }
                }
                return lastOrdersList;
        }

        @RequestMapping(value = "/indent/confirm-pause/{tagId}", method=RequestMethod.POST)
        public String raisePO(HttpServletRequest request, Model model, @PathVariable int tagId) throws Exception {
                tagListingRepository.updateActiveById(tagId, false);
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";
        }
                @RequestMapping(value = "/indent/create-po", method=RequestMethod.POST)
        public String raisePO(HttpServletRequest request, Model model) throws Exception {
                boolean success = false;
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                int fofoId = loginDetails.getFofoId();
                List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
                CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
                Client userClient = new UserClient().getClient();
                double totalAmount = itemQuantities.stream().mapToDouble(x->x.getQty()*x.getPrice()).sum();

                if(totalAmount > 0) {
                        userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
                        User user = userRepository.selectById(loginDetails.getFofoId());
                        userClient = new UserClient().getClient();
                        LOGGER.info("Setting wallet amount in cart");
                        long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(), 7890,
                                        OrderSource.WEBSITE.getValue(), true);
                        LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
                        createPayment(user, totalAmount, transactionId);
                        TransactionService.Client  transactionClient = new TransactionClient().getClient();
                        transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
                                        "Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B,
                                        OrderSource.WEBSITE);
                        transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
                                        "Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B,
                                        OrderSource.WEBSITE);
                        LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
                        transactionClient = new TransactionClient().getClient();
                        transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
                        try {
                                transactionClient.enqueueTransactionInfoEmail(transactionId);
                        } catch (Exception e1) {
                                e1.printStackTrace();
                                LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
                        }
                        resetCart(transactionClient.getTransaction(transactionId));
                }
                model.addAttribute("response", mvcResponseSender.createResponseString(success));
                return "response";
        }
        
        private void createPayment(User user, double totalAmount, long transactionId) throws NumberFormatException, PaymentException, TException {
                List<Attribute> paymentAttributes = new ArrayList<Attribute>();
                in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
                paymentAttributes.add(new Attribute("payMethod", "7890"));
                long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId, false);
                paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null,
                                paymentAttributes);
        }
        private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
                List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
                Map<Integer, ItemIdAvailability> itemCisMap = null;
                List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
                                .selectItemsStock(fofoId);
                itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);

                Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
                Map<Integer, Integer> itemsInTransit = null;
                LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
                List<TagListing> tagListings = tagListingRepository.selectAll(false);
                List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
                inTransitOrders = this.filterValidOrders(inTransitOrders);
                itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
                                Collectors.summingInt(x -> x.getLineItem().getQuantity())));

                Iterator<TagListing> iterator = tagListings.iterator();

                int toBeOrdered = 0;
                while (iterator.hasNext()) {
                        TagListing tagListing = iterator.next();
                        LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
                        if (!itemCisMap.containsKey(tagListing.getItemId())
                                        && !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
                                iterator.remove();
                                continue;
                        }
                        ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
                        tagListing.setStockInHand(itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability());
                        StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());

                        if (itemsInTransit.containsKey(tagListing.getItemId())) {
                                tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
                        } else {
                                tagListing.setInTransitQuantity(0);
                        }
                        if (stockAllocationModel != null) {
                                tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
                                toBeOrdered = Math.max(tagListing.getAllocatedQuantity() - tagListing.getInTransitQuantity()
                                                - tagListing.getStockInHand(), 0);
                                if (toBeOrdered > 0) {
                                        ItemPriceQuantity ipq = new ItemPriceQuantity();
                                        ipq.setItemId(tagListing.getItemId());
                                        ipq.setQty((long)toBeOrdered);
                                        ipq.setPrice(tagListing.getSellingPrice());
                                        itemQuantities.add(ipq);
                                }
                        }
                }
                return itemQuantities;

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

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

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

}