Subversion Repositories SmartDukaan

Rev

Rev 23786 | Rev 23798 | 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;
29
import org.springframework.web.bind.annotation.RequestBody;
30
import org.springframework.web.bind.annotation.RequestMapping;
31
import org.springframework.web.bind.annotation.RequestMethod;
23779 amit.gupta 32
import org.springframework.web.bind.annotation.RequestParam;
23405 amit.gupta 33
 
23785 amit.gupta 34
import com.spice.profitmandi.common.enumuration.CounterSize;
23405 amit.gupta 35
import com.spice.profitmandi.common.enumuration.IndentStatus;
36
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23785 amit.gupta 37
import com.spice.profitmandi.common.model.BrandPerformance;
38
import com.spice.profitmandi.common.model.CustomRetailer;
23786 amit.gupta 39
import com.spice.profitmandi.common.model.ItemIdAvailability;
23779 amit.gupta 40
import com.spice.profitmandi.common.model.StockAllocationModel;
23785 amit.gupta 41
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 42
import com.spice.profitmandi.dao.entity.catalog.TagListing;
43
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
44
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 45
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
23405 amit.gupta 46
import com.spice.profitmandi.dao.entity.fofo.IndentItem;
23796 amit.gupta 47
import com.spice.profitmandi.dao.entity.transaction.Order;
48
import com.spice.profitmandi.dao.entity.user.User;
23405 amit.gupta 49
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
50
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23779 amit.gupta 51
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23405 amit.gupta 52
import com.spice.profitmandi.dao.repository.dtr.IndentItemRepository;
53
import com.spice.profitmandi.dao.repository.dtr.IndentRepository;
54
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
55
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
23796 amit.gupta 56
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
57
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
58
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
59
import com.spice.profitmandi.dao.repository.user.UserRepository;
23779 amit.gupta 60
import com.spice.profitmandi.service.inventory.StockAllocationService;
61
import com.spice.profitmandi.service.user.RetailerService;
23796 amit.gupta 62
import com.spice.profitmandi.thrift.clients.PaymentClient;
63
import com.spice.profitmandi.thrift.clients.TransactionClient;
64
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 65
import com.spice.profitmandi.web.model.LoginDetails;
66
import com.spice.profitmandi.web.util.CookiesProcessor;
67
import com.spice.profitmandi.web.util.MVCResponseSender;
23785 amit.gupta 68
import com.spice.profitmandi.web.util.RoleManager;
23405 amit.gupta 69
 
23796 amit.gupta 70
import in.shop2020.logistics.PickUpType;
71
import in.shop2020.model.v1.order.LineItem;
72
import in.shop2020.model.v1.order.OrderSource;
73
import in.shop2020.model.v1.order.OrderStatus;
74
import in.shop2020.model.v1.order.OrderType;
75
import in.shop2020.model.v1.order.Transaction;
76
import in.shop2020.model.v1.order.TransactionService;
77
import in.shop2020.model.v1.order.TransactionStatus;
78
import in.shop2020.model.v1.user.ItemPriceQuantity;
79
import in.shop2020.model.v1.user.ItemQuantity;
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();
175
		List<TagListing> tagListings = tagListingRepository.selectAll();
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);
267
		List<TagListing> tagListings = tagListingRepository.selectAll();
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
 
403
	@RequestMapping(value = "/indent/create-po", method=RequestMethod.POST)
404
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
405
		boolean success = false;
406
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
407
		int fofoId = loginDetails.getFofoId();
408
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
409
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
410
		Client userClient = new UserClient().getClient();
411
		double totalAmount = itemQuantities.stream().mapToDouble(x->x.getQty()*x.getPrice()).sum();
412
 
413
		if(totalAmount > 0) {
414
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
415
			User user = userRepository.selectById(loginDetails.getFofoId());
416
			userClient = new UserClient().getClient();
417
			LOGGER.info("Setting wallet amount in cart");
418
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(), 7890,
419
					OrderSource.WEBSITE.getValue(), true);
420
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
421
			createPayment(user, totalAmount, transactionId);
422
			TransactionService.Client  transactionClient = new TransactionClient().getClient();
423
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
424
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B,
425
					OrderSource.WEBSITE);
426
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
427
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B,
428
					OrderSource.WEBSITE);
429
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
430
			transactionClient = new TransactionClient().getClient();
431
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
432
			try {
433
				transactionClient.enqueueTransactionInfoEmail(transactionId);
434
			} catch (Exception e1) {
435
				e1.printStackTrace();
436
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
437
			}
438
			resetCart(transactionClient.getTransaction(transactionId));
439
		}
440
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
441
		return "response";
442
	}
443
 
444
	private void createPayment(User user, double totalAmount, long transactionId) throws NumberFormatException, PaymentException, TException {
445
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
446
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
447
		paymentAttributes.add(new Attribute("payMethod", "7890"));
448
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId, false);
449
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null, PaymentStatus.SUCCESS, null,
450
				paymentAttributes);
451
	}
452
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
453
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
454
		Map<Integer, ItemIdAvailability> itemCisMap = null;
455
		List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
456
				.selectItemsStock(fofoId);
457
		itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
458
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
459
		List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
460
 
461
		Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
462
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
463
		Map<Integer, Integer> itemsInTransit = null;
464
		LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
465
		List<TagListing> tagListings = tagListingRepository.selectAll();
466
		List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
467
		inTransitOrders = this.filterValidOrders(inTransitOrders);
468
		itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
469
				Collectors.summingInt(x -> x.getLineItem().getQuantity())));
470
 
471
		Iterator<TagListing> iterator = tagListings.iterator();
472
 
473
		int toBeOrdered = 0;
474
		while (iterator.hasNext()) {
475
			TagListing tagListing = iterator.next();
476
			LOGGER.info(" tagListing.setAllocatedQuantity {}", tagListing.getAllocatedQuantity());
477
			if (!itemCisMap.containsKey(tagListing.getItemId())
478
					&& !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
479
				iterator.remove();
480
				continue;
481
			}
482
			ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
483
			tagListing.setStockInHand(itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability());
484
			StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
485
 
486
			if (itemsInTransit.containsKey(tagListing.getItemId())) {
487
				tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
488
			} else {
489
				tagListing.setInTransitQuantity(0);
490
			}
491
			if (stockAllocationModel != null) {
492
				tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
493
				toBeOrdered = Math.max(tagListing.getAllocatedQuantity() - tagListing.getInTransitQuantity()
494
						- tagListing.getStockInHand(), 0);
495
				if (toBeOrdered > 0) {
496
					ItemPriceQuantity ipq = new ItemPriceQuantity();
497
					ipq.setItemId(tagListing.getItemId());
498
					ipq.setQty((long)toBeOrdered);
499
					ipq.setPrice(tagListing.getSellingPrice());
500
					itemQuantities.add(ipq);
501
				}
502
			}
503
		}
504
		return itemQuantities;
505
 
506
	}
507
 
508
	private long resetCart(Transaction transaction) {
509
		long sum = 0;
510
		Map<Long, Double> items = new HashMap<Long, Double>();
511
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
512
			sum += order.getGvAmount();
513
			for (LineItem lineitem : order.getLineitems()) {
514
				Long itemId = lineitem.getItem_id();
515
				Double quantity = items.get(itemId);
516
				if (quantity == null) {
517
					quantity = lineitem.getQuantity();
518
				} else {
519
					quantity = quantity + lineitem.getQuantity();
520
				}
521
				items.put(itemId, quantity);
522
			}
523
		}
524
 
525
		LOGGER.debug("Items to reset in cart are: " + items);
526
 
527
		try {
528
			Client userClient = new UserClient().getClient();
529
			userClient.resetCart(transaction.getShoppingCartid(), items);
530
		} catch (TException e) {
531
			LOGGER.error("Error while updating information in payment database.", e);
532
		} catch (ShoppingCartException e) {
533
			LOGGER.error("Error while reseting the cart in cart database.", e);
534
		} catch (Exception e) {
535
			LOGGER.error("Unexpected exception", e);
536
		}
537
		return sum;
538
	}
539
 
23405 amit.gupta 540
}