Subversion Repositories SmartDukaan

Rev

Rev 23798 | Rev 24231 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
23405 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import java.time.LocalDate;
4
import java.time.LocalDateTime;
5
import java.time.LocalTime;
23785 amit.gupta 6
import java.util.ArrayList;
23405 amit.gupta 7
import java.util.Arrays;
23796 amit.gupta 8
import java.util.Collections;
9
import java.util.Comparator;
23785 amit.gupta 10
import java.util.DoubleSummaryStatistics;
23796 amit.gupta 11
import java.util.HashMap;
23405 amit.gupta 12
import java.util.HashSet;
23785 amit.gupta 13
import java.util.Iterator;
23405 amit.gupta 14
import java.util.List;
15
import java.util.Map;
23785 amit.gupta 16
import java.util.Set;
23405 amit.gupta 17
import java.util.stream.Collectors;
18
 
19
import javax.servlet.http.HttpServletRequest;
20
 
23717 amit.gupta 21
import org.apache.logging.log4j.LogManager;
23568 govind 22
import org.apache.logging.log4j.Logger;
23796 amit.gupta 23
import org.apache.thrift.TException;
23779 amit.gupta 24
import org.json.JSONObject;
23405 amit.gupta 25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.stereotype.Controller;
27
import org.springframework.transaction.annotation.Transactional;
28
import org.springframework.ui.Model;
23855 amit.gupta 29
import org.springframework.web.bind.annotation.PathVariable;
23405 amit.gupta 30
import org.springframework.web.bind.annotation.RequestBody;
31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
23779 amit.gupta 33
import org.springframework.web.bind.annotation.RequestParam;
23405 amit.gupta 34
 
23785 amit.gupta 35
import com.spice.profitmandi.common.enumuration.CounterSize;
23405 amit.gupta 36
import com.spice.profitmandi.common.enumuration.IndentStatus;
37
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23785 amit.gupta 38
import com.spice.profitmandi.common.model.BrandPerformance;
39
import com.spice.profitmandi.common.model.CustomRetailer;
23786 amit.gupta 40
import com.spice.profitmandi.common.model.ItemIdAvailability;
23779 amit.gupta 41
import com.spice.profitmandi.common.model.StockAllocationModel;
23785 amit.gupta 42
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 43
import com.spice.profitmandi.dao.entity.catalog.TagListing;
44
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
45
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 46
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
23405 amit.gupta 47
import com.spice.profitmandi.dao.entity.fofo.IndentItem;
23796 amit.gupta 48
import com.spice.profitmandi.dao.entity.transaction.Order;
49
import com.spice.profitmandi.dao.entity.user.User;
23405 amit.gupta 50
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
51
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23779 amit.gupta 52
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23405 amit.gupta 53
import com.spice.profitmandi.dao.repository.dtr.IndentItemRepository;
54
import com.spice.profitmandi.dao.repository.dtr.IndentRepository;
55
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
56
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
23796 amit.gupta 57
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
58
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
59
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
60
import com.spice.profitmandi.dao.repository.user.UserRepository;
23798 amit.gupta 61
import com.spice.profitmandi.service.authentication.RoleManager;
23779 amit.gupta 62
import com.spice.profitmandi.service.inventory.StockAllocationService;
63
import com.spice.profitmandi.service.user.RetailerService;
23796 amit.gupta 64
import com.spice.profitmandi.thrift.clients.PaymentClient;
65
import com.spice.profitmandi.thrift.clients.TransactionClient;
66
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 67
import com.spice.profitmandi.web.model.LoginDetails;
68
import com.spice.profitmandi.web.util.CookiesProcessor;
69
import com.spice.profitmandi.web.util.MVCResponseSender;
70
 
23796 amit.gupta 71
import in.shop2020.logistics.PickUpType;
72
import in.shop2020.model.v1.order.LineItem;
73
import in.shop2020.model.v1.order.OrderSource;
74
import in.shop2020.model.v1.order.OrderStatus;
75
import in.shop2020.model.v1.order.OrderType;
76
import in.shop2020.model.v1.order.Transaction;
77
import in.shop2020.model.v1.order.TransactionService;
78
import in.shop2020.model.v1.order.TransactionStatus;
79
import in.shop2020.model.v1.user.ItemPriceQuantity;
80
import in.shop2020.model.v1.user.ShoppingCartException;
81
import in.shop2020.model.v1.user.UserContextService.Client;
82
import in.shop2020.payments.Attribute;
83
import in.shop2020.payments.PaymentException;
84
import in.shop2020.payments.PaymentStatus;
85
 
23405 amit.gupta 86
@Controller
87
@Transactional(rollbackFor = Throwable.class)
88
public class IndentController {
89
 
23568 govind 90
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 91
	private static final int WALLET_GATEWAY_ID = 8;
23405 amit.gupta 92
 
23796 amit.gupta 93
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
94
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
95
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
96
			OrderStatus.REACHED_DESTINATION_CITY);
97
 
23405 amit.gupta 98
	@Autowired
99
	private CookiesProcessor cookiesProcessor;
23796 amit.gupta 100
 
101
	@Autowired
102
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 103
 
23779 amit.gupta 104
	@Autowired
23796 amit.gupta 105
	private UserRepository userRepository;
106
 
107
	@Autowired
23779 amit.gupta 108
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 109
 
110
	@Autowired
23796 amit.gupta 111
	private OrderRepository orderRepository;
112
 
113
	@Autowired
23405 amit.gupta 114
	private ItemRepository itemRepository;
115
 
116
	@Autowired
117
	private IndentRepository indentRepository;
118
 
119
	@Autowired
23779 amit.gupta 120
	private StockAllocationService stockAllocationService;
121
 
122
	@Autowired
23405 amit.gupta 123
	private IndentItemRepository indentItemRepository;
23785 amit.gupta 124
 
23779 amit.gupta 125
	@Autowired
126
	private RetailerService retailerService;
23405 amit.gupta 127
 
128
	@Autowired
129
	private TagListingRepository tagListingRepository;
130
 
131
	@Autowired
132
	private FofoOrderRepository fofoOrderRepository;
133
 
134
	@Autowired
135
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
136
 
137
	@Autowired
23796 amit.gupta 138
	private PurchaseRepository purchaseRepository;
139
 
140
	@Autowired
23405 amit.gupta 141
	private MVCResponseSender mvcResponseSender;
142
 
23785 amit.gupta 143
	@Autowired
144
	RoleManager roleManager;
23405 amit.gupta 145
 
23779 amit.gupta 146
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
23785 amit.gupta 147
	public String saveOpenIndent(HttpServletRequest request, Model model,
23786 amit.gupta 148
			@RequestBody List<StockAllocationModel> stockAllocationModelList, @RequestParam int fofoId,
149
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
23405 amit.gupta 150
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23779 amit.gupta 151
		boolean response = false;
23785 amit.gupta 152
		if (fofoId > 0) {
153
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
23786 amit.gupta 154
			stockAllocationModelList.forEach(x -> {
155
				x.setFofoId(fofoId);
156
				x.setCounterSize(fs.getCounterSize());
157
			});
158
		} else {
159
			stockAllocationModelList.forEach(x -> {
160
				x.setFofoId(fofoId);
161
				x.setCounterSize(counterSize);
162
			});
23785 amit.gupta 163
		}
164
		if (roleManager.isAdmin(loginDetails.getRoleIds())) {
165
			response = stockAllocationService.addToAllocation(stockAllocationModelList);
166
			model.addAttribute("response", mvcResponseSender.createResponseString(response));
167
		}
23405 amit.gupta 168
		return "response";
169
	}
170
 
23415 amit.gupta 171
	@RequestMapping(value = "/migrate", method = RequestMethod.PUT)
172
	public String migrate(HttpServletRequest request, Model model) throws Exception {
173
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
174
		int fofoId = loginDetails.getFofoId();
23855 amit.gupta 175
		List<TagListing> tagListings = tagListingRepository.selectAll(false);
23779 amit.gupta 176
		for (TagListing tagListing : tagListings) {
23415 amit.gupta 177
			int itemId = tagListing.getItemId();
178
		}
179
		return "";
180
	}
181
 
23405 amit.gupta 182
	@RequestMapping(value = "/indent/inProcess")
23779 amit.gupta 183
	public String loadInProcessIndents(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
23405 amit.gupta 184
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
185
		int fofoId = loginDetails.getFofoId();
186
 
23779 amit.gupta 187
		List<Integer> pendingIndentIds = indentRepository.selectIndentByStatus(fofoId, IndentStatus.PENDING).stream()
188
				.map(x -> x.getId()).collect(Collectors.toList());
189
		List<Integer> allocatedIndentIds = indentRepository.selectIndentByStatus(fofoId, IndentStatus.ALLOCATED)
190
				.stream().map(x -> x.getId()).collect(Collectors.toList());
23405 amit.gupta 191
		pendingIndentIds.addAll(allocatedIndentIds);
23779 amit.gupta 192
 
193
		if (pendingIndentIds.size() > 0) {
194
			Map<Integer, IndentItem> pendingIndentItemIdMap = indentItemRepository.selectIndentItems(pendingIndentIds)
195
					.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
196
			List<TagListing> tagListings = tagListingRepository
197
					.selectByItemIdsAndTagIds(pendingIndentItemIdMap.keySet(), new HashSet<>(Arrays.asList(4)));
198
 
199
			List<FofoOrderItem> fofoOrderItems = fofoOrderRepository.selectByFofoItemIds(fofoId, pendingIndentIds,
200
					LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT).minusDays(30), LocalDateTime.now());
23405 amit.gupta 201
			Map<Integer, Integer> itemQuantity = fofoOrderItems.stream().collect(
202
					Collectors.groupingBy(FofoOrderItem::getItemId, Collectors.summingInt(FofoOrderItem::getQuantity)));
23779 amit.gupta 203
 
23405 amit.gupta 204
			List<CurrentInventorySnapshot> cis = currentInventorySnapshotRepository.selectByFofoId(fofoId);
23779 amit.gupta 205
			Map<Integer, CurrentInventorySnapshot> itemIdSnapshotMap = cis.stream()
206
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
207
 
208
			for (TagListing tagListing : tagListings) {
23405 amit.gupta 209
				Integer itemId = tagListing.getItemId();
210
				tagListing.setItemDescription(itemRepository.selectById(itemId).getItemDescription());
23779 amit.gupta 211
				if (itemQuantity.containsKey(itemId)) {
23405 amit.gupta 212
					tagListing.setLast30DaysSale(itemQuantity.get(itemId));
213
				}
23779 amit.gupta 214
				if (itemIdSnapshotMap.containsKey(itemId)) {
23405 amit.gupta 215
					tagListing.setStockInHand(itemIdSnapshotMap.get(itemId).getAvailability());
216
				}
217
			}
23779 amit.gupta 218
 
23405 amit.gupta 219
			model.addAttribute("pendingIndentItemIdMap", pendingIndentItemIdMap);
220
			model.addAttribute("tagListings", tagListings);
221
		}
222
		return "pending-indent";
223
	}
224
 
225
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 226
	public String loadOpenIndent(HttpServletRequest request, Model model,
227
			@RequestParam(required = false, defaultValue = "0") int fofoId,
23786 amit.gupta 228
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws ProfitMandiBusinessException {
23785 amit.gupta 229
		Set<Integer> roleIds = cookiesProcessor.getCookiesObject(request).getRoleIds();
230
		LOGGER.info("Counter size is {}", counterSize);
231
		LOGGER.info("Fofo Id is {}", fofoId);
23786 amit.gupta 232
 
233
		Map<Integer, ItemIdAvailability> itemCisMap = null;
234
		if (!roleManager.isAdmin(roleIds)) {
235
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
23796 amit.gupta 236
			List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
237
					.selectItemsStock(fofoId);
238
			itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
239
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23786 amit.gupta 240
		} else {
241
			if (fofoId == 0) {
23796 amit.gupta 242
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
243
						.selectItemsStock();
244
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
245
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23779 amit.gupta 246
			} else {
23796 amit.gupta 247
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
248
						.selectItemsStock(fofoId);
249
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
250
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23405 amit.gupta 251
			}
23786 amit.gupta 252
		}
253
		List<BrandPerformance> brandPerformanceList = new ArrayList<>();
254
		List<BrandPerformance> accsBrandPerformanceList = new ArrayList<>();
255
		List<StockAllocationModel> stockAllocationList;
256
		if (fofoId > 0) {
257
			stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
258
		} else {
259
			stockAllocationList = stockAllocationService.getStockAllocation(counterSize, true);
260
		}
261
		LOGGER.info("Stock Allocation list  is {}", stockAllocationList);
23405 amit.gupta 262
 
23786 amit.gupta 263
		Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
264
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23796 amit.gupta 265
		Map<Integer, Integer> itemsInTransit = null;
23786 amit.gupta 266
		LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
23855 amit.gupta 267
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
23796 amit.gupta 268
		if (!roleManager.isAdmin(roleIds)) {
23786 amit.gupta 269
			tagListings = new ArrayList<>(tagListings);
23796 amit.gupta 270
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
271
			inTransitOrders = this.filterValidOrders(inTransitOrders);
272
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
273
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
274
		} else {
275
			itemsInTransit = new HashMap<>();
23786 amit.gupta 276
		}
277
		Iterator<TagListing> iterator = tagListings.iterator();
23796 amit.gupta 278
		int totalPcs = 0;
279
		int toBeOrdered = 0;
280
		float totalAmount = 0;
23786 amit.gupta 281
		while (iterator.hasNext()) {
282
			TagListing tagListing = iterator.next();
283
			LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
284
			Item item = itemRepository.selectById(tagListing.getItemId());
285
			if (roleManager.isAdmin(roleIds)) {
286
				if (item.getBrand() == null || item.getCategoryId() == 0) {
23785 amit.gupta 287
					iterator.remove();
288
					continue;
289
				}
23786 amit.gupta 290
			} else {
23796 amit.gupta 291
				if (!itemCisMap.containsKey(tagListing.getItemId())
292
						&& !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
23786 amit.gupta 293
					iterator.remove();
294
					continue;
23779 amit.gupta 295
				}
296
			}
23796 amit.gupta 297
			ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
298
			tagListing.setStockInHand(itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability());
23786 amit.gupta 299
			StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
23796 amit.gupta 300
 
301
			if (itemsInTransit.containsKey(tagListing.getItemId())) {
302
				tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
303
			} else {
304
				tagListing.setInTransitQuantity(0);
305
			}
23786 amit.gupta 306
			if (stockAllocationModel != null) {
307
				tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
23796 amit.gupta 308
				toBeOrdered = Math.max(tagListing.getAllocatedQuantity() - tagListing.getInTransitQuantity()
309
						- tagListing.getStockInHand(), 0);
310
				totalPcs += toBeOrdered;
311
				totalAmount += toBeOrdered * tagListing.getSellingPrice();
312
				tagListing.setToBeOrdered(toBeOrdered);
23786 amit.gupta 313
			} else {
314
				tagListing.setAllocatedQuantity(0);
315
			}
316
			tagListing.setBrand(item.getBrand());
317
			tagListing.setItemDescription(item.getItemDescription());
318
			if (item.getCategoryId() == 10006) {
319
				tagListing.setCategoryId(item.getCategoryId());
320
			}
23796 amit.gupta 321
			// LOGGER.info(" tagListing.setAllocatedQuantity {}",
322
			// tagListing.getAllocatedQuantity());
23786 amit.gupta 323
		}
23405 amit.gupta 324
 
23786 amit.gupta 325
		Map<Integer, List<TagListing>> performanceMap = tagListings.stream()
326
				.collect(Collectors.groupingBy(x -> x.getCategoryId()));
327
		List<TagListing> accsListing = performanceMap.get(0);
328
		List<TagListing> mobileListing = performanceMap.get(10006);
23785 amit.gupta 329
 
23786 amit.gupta 330
		Map<String, DoubleSummaryStatistics> accsStats = accsListing.stream().collect(Collectors.groupingBy(
331
				x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));
332
		Map<String, DoubleSummaryStatistics> mobStats = mobileListing.stream().collect(Collectors.groupingBy(
333
				x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));
23785 amit.gupta 334
 
23786 amit.gupta 335
		for (Map.Entry<String, DoubleSummaryStatistics> entry : mobStats.entrySet()) {
336
			DoubleSummaryStatistics dss = entry.getValue();
337
			BrandPerformance bp = new BrandPerformance();
338
			bp.setTarget((float) dss.getSum());
339
			bp.setBrandName(entry.getKey());
340
			brandPerformanceList.add(bp);
341
		}
342
		for (Map.Entry<String, DoubleSummaryStatistics> entry : accsStats.entrySet()) {
343
			DoubleSummaryStatistics dss = entry.getValue();
344
			BrandPerformance bp = new BrandPerformance();
345
			bp.setTarget((float) dss.getSum());
346
			bp.setBrandName(entry.getKey());
347
			accsBrandPerformanceList.add(bp);
348
		}
349
		brandPerformanceList = brandPerformanceList.stream().filter(x -> x.getTarget() > 0)
23796 amit.gupta 350
				.sorted(Comparator.comparing(x -> x.getTarget())).collect(Collectors.toList());
23786 amit.gupta 351
		accsBrandPerformanceList = accsBrandPerformanceList.stream().filter(x -> x.getTarget() > 0)
23796 amit.gupta 352
				.sorted(Comparator.comparing(x -> x.getTarget())).collect(Collectors.toList());
23785 amit.gupta 353
 
23786 amit.gupta 354
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
355
				.collect(Collectors.toList());
356
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
357
		if (fofoId > 0) {
358
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
359
			model.addAttribute("retailerName",
360
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
361
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
362
			model.addAttribute("retailerId", customRetailer.getPartnerId());
363
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 364
		} else {
23786 amit.gupta 365
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 366
		}
23786 amit.gupta 367
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
368
		LOGGER.info("Custom retailers {}", customRetailers);
23796 amit.gupta 369
		Comparator<TagListing> firstCmp = Comparator
370
				.comparing(x -> ((x.getAllocatedQuantity() - x.getStockInHand() - x.getInTransitQuantity() == 0)
371
						? Integer.MIN_VALUE
372
						: (x.getAllocatedQuantity() - x.getStockInHand())), Comparator.reverseOrder());
373
		model.addAttribute("tagListings", tagListings.stream().sorted(firstCmp).collect(Collectors.toList()));
23786 amit.gupta 374
		model.addAttribute("customRetailers", customRetailers);
375
		model.addAttribute("brandPerformanceList", brandPerformanceList);
376
		model.addAttribute("accsBrandPerformanceList", accsBrandPerformanceList);
377
		model.addAttribute("counterSizes", CounterSize.values());
23796 amit.gupta 378
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
379
		model.addAttribute("totalAmount", totalAmount);
380
		model.addAttribute("totalPcs", totalPcs);
381
		model.addAttribute("walletAmount", userWalletRepository.selectByRetailerId(fofoId).getAmount());
382
		// model.addAttribute("itemCisMap", itemCisMap);
23786 amit.gupta 383
		return "open-indent";
23405 amit.gupta 384
	}
23796 amit.gupta 385
 
386
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
387
		Iterator<Order> orderIterator = lastOrdersList.iterator();
388
		while (orderIterator.hasNext()) {
389
			Order o = orderIterator.next();
390
			if (o.getInvoiceNumber() != null) {
391
				try {
392
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
393
					orderIterator.remove();
394
					continue;
395
				} catch (Exception e) {
396
 
397
				}
398
			}
399
		}
400
		return lastOrdersList;
401
	}
402
 
23855 amit.gupta 403
	@RequestMapping(value = "/indent/confirm-pause/{tagId}", method=RequestMethod.POST)
404
	public String raisePO(HttpServletRequest request, Model model, @PathVariable int tagId) throws Exception {
405
		tagListingRepository.updateActiveById(tagId, false);
406
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
407
		return "response";
408
	}
409
		@RequestMapping(value = "/indent/create-po", method=RequestMethod.POST)
23796 amit.gupta 410
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
411
		boolean success = false;
412
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
413
		int fofoId = loginDetails.getFofoId();
414
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
415
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
416
		Client userClient = new UserClient().getClient();
417
		double totalAmount = itemQuantities.stream().mapToDouble(x->x.getQty()*x.getPrice()).sum();
418
 
419
		if(totalAmount > 0) {
420
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
421
			User user = userRepository.selectById(loginDetails.getFofoId());
422
			userClient = new UserClient().getClient();
423
			LOGGER.info("Setting wallet amount in cart");
424
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(), 7890,
425
					OrderSource.WEBSITE.getValue(), true);
426
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
427
			createPayment(user, totalAmount, transactionId);
428
			TransactionService.Client  transactionClient = new TransactionClient().getClient();
429
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
430
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B,
431
					OrderSource.WEBSITE);
432
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
433
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B,
434
					OrderSource.WEBSITE);
435
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
436
			transactionClient = new TransactionClient().getClient();
437
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
438
			try {
439
				transactionClient.enqueueTransactionInfoEmail(transactionId);
440
			} catch (Exception e1) {
441
				e1.printStackTrace();
442
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
443
			}
444
			resetCart(transactionClient.getTransaction(transactionId));
445
		}
446
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
447
		return "response";
448
	}
449
 
450
	private void createPayment(User user, double totalAmount, long transactionId) throws NumberFormatException, PaymentException, TException {
451
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
452
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
453
		paymentAttributes.add(new Attribute("payMethod", "7890"));
454
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId, false);
455
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null,
456
				paymentAttributes);
457
	}
458
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
459
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
460
		Map<Integer, ItemIdAvailability> itemCisMap = null;
461
		List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
462
				.selectItemsStock(fofoId);
463
		itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
464
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
465
		List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
466
 
467
		Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
468
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
469
		Map<Integer, Integer> itemsInTransit = null;
470
		LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
23855 amit.gupta 471
		List<TagListing> tagListings = tagListingRepository.selectAll(false);
23796 amit.gupta 472
		List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
473
		inTransitOrders = this.filterValidOrders(inTransitOrders);
474
		itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
475
				Collectors.summingInt(x -> x.getLineItem().getQuantity())));
476
 
477
		Iterator<TagListing> iterator = tagListings.iterator();
478
 
479
		int toBeOrdered = 0;
480
		while (iterator.hasNext()) {
481
			TagListing tagListing = iterator.next();
482
			LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
483
			if (!itemCisMap.containsKey(tagListing.getItemId())
484
					&& !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
485
				iterator.remove();
486
				continue;
487
			}
488
			ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
489
			tagListing.setStockInHand(itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability());
490
			StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
491
 
492
			if (itemsInTransit.containsKey(tagListing.getItemId())) {
493
				tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
494
			} else {
495
				tagListing.setInTransitQuantity(0);
496
			}
497
			if (stockAllocationModel != null) {
498
				tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
499
				toBeOrdered = Math.max(tagListing.getAllocatedQuantity() - tagListing.getInTransitQuantity()
500
						- tagListing.getStockInHand(), 0);
501
				if (toBeOrdered > 0) {
502
					ItemPriceQuantity ipq = new ItemPriceQuantity();
503
					ipq.setItemId(tagListing.getItemId());
504
					ipq.setQty((long)toBeOrdered);
505
					ipq.setPrice(tagListing.getSellingPrice());
506
					itemQuantities.add(ipq);
507
				}
508
			}
509
		}
510
		return itemQuantities;
511
 
512
	}
513
 
514
	private long resetCart(Transaction transaction) {
515
		long sum = 0;
516
		Map<Long, Double> items = new HashMap<Long, Double>();
517
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
518
			sum += order.getGvAmount();
519
			for (LineItem lineitem : order.getLineitems()) {
520
				Long itemId = lineitem.getItem_id();
521
				Double quantity = items.get(itemId);
522
				if (quantity == null) {
523
					quantity = lineitem.getQuantity();
524
				} else {
525
					quantity = quantity + lineitem.getQuantity();
526
				}
527
				items.put(itemId, quantity);
528
			}
529
		}
530
 
531
		LOGGER.debug("Items to reset in cart are: " + items);
532
 
533
		try {
534
			Client userClient = new UserClient().getClient();
535
			userClient.resetCart(transaction.getShoppingCartid(), items);
536
		} catch (TException e) {
537
			LOGGER.error("Error while updating information in payment database.", e);
538
		} catch (ShoppingCartException e) {
539
			LOGGER.error("Error while reseting the cart in cart database.", e);
540
		} catch (Exception e) {
541
			LOGGER.error("Unexpected exception", e);
542
		}
543
		return sum;
544
	}
545
 
23405 amit.gupta 546
}