Rev 24824 | Rev 25702 | 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.io.Serializable;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.Optional;import java.util.Set;import java.util.stream.Collectors;import javax.servlet.http.HttpServletRequest;import org.apache.commons.io.output.ByteArrayOutputStream;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.thrift.TException;import org.json.JSONArray;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.ByteArrayResource;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.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.mongodb.TaggableReadPreference;import com.spice.profitmandi.common.enumuration.CounterSize;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.BrandPerformance;import com.spice.profitmandi.common.model.CatalogListingModel;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.common.util.FileUtil;import com.spice.profitmandi.dao.entity.catalog.Item;import com.spice.profitmandi.dao.entity.catalog.TagListing;import com.spice.profitmandi.dao.entity.fofo.FofoStore;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.fofo.CurrentInventorySnapshotRepository;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.model.v1.user.UserContextService.forgotPassword_args;import in.shop2020.payments.Attribute;import in.shop2020.payments.PaymentException;import in.shop2020.payments.PaymentStatus;@Controller@Transactional(rollbackFor = Throwable.class)public class IndentController {private static final Logger LOGGER = LogManager.getLogger(IndentController.class);private static final int WALLET_GATEWAY_ID = 8;private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));private final List<OrderStatus> 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);private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,OrderStatus.REACHED_DESTINATION_CITY);@Autowiredprivate CookiesProcessor cookiesProcessor;@Autowiredprivate UserWalletRepository userWalletRepository;@Autowiredprivate UserRepository userRepository;@AutowiredFofoStoreRepository fofoStoreRepository;@Autowiredprivate OrderRepository orderRepository;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate StockAllocationService stockAllocationService;@Autowiredprivate RetailerService retailerService;@Autowiredprivate TagListingRepository tagListingRepository;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;@Autowiredprivate PurchaseRepository purchaseRepository;@Autowiredprivate MVCResponseSender mvcResponseSender;@AutowiredRoleManager 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 = "/indent/download", method = RequestMethod.GET)public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,@RequestParam(required = false, defaultValue = "0") int fofoId,@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {Set<Integer> roleIds = cookiesProcessor.getCookiesObject(request).getRoleIds();LOGGER.info("Counter size is {}", counterSize);LOGGER.info("Fofo Id is {}", fofoId);if (roleManager.isAdmin(roleIds)) {List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,true);Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));Map<String, Integer> catalogUserQtyMap = new HashMap<>();currentInventorySnapshotRepository.selectAll(Optional.of(true)).stream().forEach(x -> {int retailerId = x.getFofoId();int catalogId;try {catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();String key = catalogId + "-" + retailerId;if (!catalogUserQtyMap.containsKey(key)) {catalogUserQtyMap.put(key, 0);}catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());} catch (ProfitMandiBusinessException e) {// TODO Auto-generated catch blockthrow new RuntimeException(e);}});List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {try {return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"+ x.getRetailerId();} catch (ProfitMandiBusinessException e) {// TODO Auto-generated catch blockreturn "";}}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();List<TagListing> tagListings = tagListingRepository.selectAll(true);Iterator<TagListing> iterator = tagListings.iterator();while (iterator.hasNext()) {TagListing tagListing = iterator.next();Item item = itemRepository.selectById(tagListing.getItemId());int catalogId = item.getCatalogItemId();if (item.getCategoryId() != 10006) {continue;}int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)? modelStockAllocationMap.get(catalogId): 0;for (int retailerId : fofoIds) {String key = catalogId + "-" + retailerId;if (catalogListingMap.containsKey(key)) {continue;}int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {continue;}CatalogListingModel catalogListingModel = new CatalogListingModel();catalogListingModel.setFofoId(retailerId);catalogListingModel.setModelName(item.getModelName());catalogListingModel.setModelNumber(item.getModelNumber());catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);catalogListingModel.setInTransitQuantity(catalogInTransit);catalogListingModel.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);catalogListingModel.setStockInHand(catalogInStock);catalogListingModel.setBrand(item.getBrand());catalogListingModel.setModelName(item.getModelName());catalogListingModel.setModelNumber(item.getModelNumber());catalogListingModel.setCategoryId(item.getCategoryId());catalogListingMap.put(key, catalogListingModel);}}List<List<? extends Serializable>> listOfRows = new ArrayList<>();for (CatalogListingModel clm : catalogListingMap.values()) {CustomRetailer cr = customRetailersMap.get(clm.getFofoId());listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),clm.getToBeOrdered()));}ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number","DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),listOfRows);HttpHeaders headers = new HttpHeaders();headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,HttpStatus.OK);}return null;}@RequestMapping(value = "/itemsByCatalogId")public String getItemsByCatalogId(HttpServletRequest request, Model model,@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)throws ProfitMandiBusinessException {if (catalogId == 0) {catalogId = itemRepository.selectById(itemId).getCatalogItemId();}List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);LOGGER.info("Items {}", items);Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_")).collect(Collectors.toMap(Item::getId, Item::getColor));Map<Integer, TagListing> tagsMap = tagListingRepository.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags).stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));LOGGER.info("Items color map {}", itemsColorMap);JSONArray response = new JSONArray();itemsColorMap.keySet().stream().forEach(x -> {response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));});model.addAttribute("response", response.toString());return "response";}@RequestMapping(value = "/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.getCatalogId(), 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;Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();while (iterator.hasNext()) {TagListing tagListing = iterator.next();Item item = itemRepository.selectById(tagListing.getItemId());// itemRepository.select// catalogTagListingMapif (roleManager.isAdmin(roleIds)) {if (item.getBrand() == null || item.getCategoryId() != 10006) {iterator.remove();continue;}} else {if (!(itemCisMap.containsKey(tagListing.getItemId())|| itemStockAllocationMap.containsKey(tagListing.getItemId()))) {iterator.remove();continue;}}int catalogId = item.getCatalogItemId();CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);if (!catalogListingMap.containsKey(catalogId)) {catalogListingModel = new CatalogListingModel();catalogListingModel.setCatalogId(catalogId);catalogListingModel.setDp(tagListing.getSellingPrice());catalogListingModel.setMop(tagListing.getMop());catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(item.getCatalogItemId());int stockAllocationQuantity = stockAllocationModel == null ? 0 : stockAllocationModel.getQuantity();catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);catalogListingModel.setToBeOrdered(stockAllocationQuantity);catalogListingModel.setBrand(item.getBrand());if (item.getCategoryId() == 10006) {catalogListingModel.setCategoryId(item.getCategoryId());}catalogListingMap.put(catalogId, catalogListingModel);}ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());int itemAvailability = itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability();catalogListingModel.setStockInHand(catalogListingModel.getStockInHand() + itemAvailability);Integer inTransitQuantity = itemsInTransit.get(item.getId());int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);if (catalogListingModel.getAllocatedQuantity() > 0) {toBeOrdered = Math.max(catalogListingModel.getToBeOrdered() - inTransitQty - itemAvailability, 0);catalogListingModel.setToBeOrdered(toBeOrdered);}}List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());Map<Boolean, List<CatalogListingModel>> performanceMap = catalogModelList.stream().collect(Collectors.groupingBy(x -> x.getCategoryId() == 10006));List<CatalogListingModel> mobileListing = performanceMap.get(true) == null ? new ArrayList<>(): performanceMap.get(true);List<CatalogListingModel> accsListing = performanceMap.get(false) == null ? new ArrayList<>(): performanceMap.get(false);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);// Lits<CatalogTagListing> catalogComparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getToBeOrdered,Comparator.reverseOrder());model.addAttribute("catalogTagListings",catalogModelList.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", method = RequestMethod.POST)public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)throws Exception {JSONArray jsonArray = new JSONArray(jsonArrayString);for (int i = 0; i < jsonArray.length(); i++) {JSONObject obj = jsonArray.getJSONObject(i);TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));if (tl == null) {continue;} else {tl.setActive(obj.getBoolean("active"));tagListingRepository.persist(tl);}}model.addAttribute("response", true);return "response";}@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)public String raisePO(HttpServletRequest request, Model model) throws Exception {boolean success = false;LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);int fofoId = loginDetails.getFofoId();List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);Client userClient = new UserClient().getClient();double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();if (totalAmount > 0) {userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);User user = userRepository.selectById(loginDetails.getFofoId());userClient = new UserClient().getClient();LOGGER.info("Setting wallet amount in cart");long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),7890, OrderSource.WEBSITE.getValue(), true);LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);createPayment(user, totalAmount, transactionId);TransactionService.Client transactionClient = new TransactionClient().getClient();transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);transactionClient = new TransactionClient().getClient();transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));try {transactionClient.enqueueTransactionInfoEmail(transactionId);} catch (Exception e1) {e1.printStackTrace();LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);}resetCart(transactionClient.getTransaction(transactionId));}model.addAttribute("response", mvcResponseSender.createResponseString(success));return "response";}private void createPayment(User user, double totalAmount, long transactionId)throws NumberFormatException, PaymentException, TException {List<Attribute> paymentAttributes = new ArrayList<Attribute>();in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();paymentAttributes.add(new Attribute("payMethod", "7890"));long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,false);paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,PaymentStatus.SUCCESS, null, paymentAttributes);}private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {List<ItemPriceQuantity> itemQuantities = new ArrayList<>();/** Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>* currentInventorySnapshots = currentInventorySnapshotRepository* .selectItemsStock(fofoId); itemCisMap =* currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)* .collect(Collectors.toMap(x -> x.getItemId(), x -> x));* List<StockAllocationModel> stockAllocationList =* stockAllocationService.getStockAllocation(fofoId, true);** Map<Integer, StockAllocationModel> itemStockAllocationMap =* stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x* -> x)); Map<Integer, Integer> itemsInTransit = null;* LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);* List<TagListing> tagListings = tagListingRepository.selectAll(false);* List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,* validOrderStatusList); inTransitOrders =* this.filterValidOrders(inTransitOrders); itemsInTransit =* inTransitOrders.stream().collect(Collectors.groupingBy(x ->* x.getLineItem().getItemId(), Collectors.summingInt(x ->* x.getLineItem().getQuantity())));** Iterator<TagListing> iterator = tagListings.iterator();** int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =* iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",* tagListing.getAllocatedQuantity()); if* (!itemCisMap.containsKey(tagListing.getItemId()) &&* !itemStockAllocationMap.containsKey(tagListing.getItemId())) {* iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =* itemCisMap.get(tagListing.getItemId());* tagListing.setStockInHand(itemIdAvailability == null ? 0 :* itemIdAvailability.getAvailability()); StockAllocationModel* stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());** if (itemsInTransit.containsKey(tagListing.getItemId())) {* tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));* } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=* null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());* toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -* tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if* (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();* ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);* ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }*/return itemQuantities;}private long resetCart(Transaction transaction) {long sum = 0;Map<Long, Double> items = new HashMap<Long, Double>();for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {sum += order.getGvAmount();for (LineItem lineitem : order.getLineitems()) {Long itemId = lineitem.getItem_id();Double quantity = items.get(itemId);if (quantity == null) {quantity = lineitem.getQuantity();} else {quantity = quantity + lineitem.getQuantity();}items.put(itemId, quantity);}}LOGGER.debug("Items to reset in cart are: " + items);try {Client userClient = new UserClient().getClient();userClient.resetCart(transaction.getShoppingCartid(), items);} catch (TException e) {LOGGER.error("Error while updating information in payment database.", e);} catch (ShoppingCartException e) {LOGGER.error("Error while reseting the cart in cart database.", e);} catch (Exception e) {LOGGER.error("Unexpected exception", e);}return sum;}}