Subversion Repositories SmartDukaan

Rev

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