Subversion Repositories SmartDukaan

Rev

Rev 24232 | Rev 24234 | 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);
24233 amit.gupta 246
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 247
					catalogListingModel.setBrand(item.getBrand());
248
					catalogListingModel.setModelName(item.getModelName());
249
					catalogListingModel.setModelNumber(item.getModelNumber());
250
					catalogListingModel.setCategoryId(item.getCategoryId());
251
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 252
				}
253
			}
24231 amit.gupta 254
			List<List<Object>> listOfRows = new ArrayList<>();
255
			for (CatalogListingModel clm : catalogListingMap.values()) {
256
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
257
				listOfRows
24233 amit.gupta 258
						.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(), clm.getBrand(),
259
								clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(), clm.getAllocatedQuantity(),
24231 amit.gupta 260
								clm.getInTransitQuantity(), clm.getStockInHand(), clm.getToBeOrdered()));
261
			}
24232 amit.gupta 262
			ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("StoreId", "StoreName", "Catalog Id",
24233 amit.gupta 263
//					"Brand", "Model Name", "Model Number", "DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
24232 amit.gupta 264
					listOfRows);
24231 amit.gupta 265
			HttpHeaders headers = new HttpHeaders();
266
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
267
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 268
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
269
					HttpStatus.OK);
23405 amit.gupta 270
		}
24231 amit.gupta 271
		return null;
24232 amit.gupta 272
 
23405 amit.gupta 273
	}
274
 
275
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 276
	public String loadOpenIndent(HttpServletRequest request, Model model,
277
			@RequestParam(required = false, defaultValue = "0") int fofoId,
23786 amit.gupta 278
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws ProfitMandiBusinessException {
23785 amit.gupta 279
		Set<Integer> roleIds = cookiesProcessor.getCookiesObject(request).getRoleIds();
280
		LOGGER.info("Counter size is {}", counterSize);
281
		LOGGER.info("Fofo Id is {}", fofoId);
23786 amit.gupta 282
 
283
		Map<Integer, ItemIdAvailability> itemCisMap = null;
284
		if (!roleManager.isAdmin(roleIds)) {
285
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
23796 amit.gupta 286
			List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
287
					.selectItemsStock(fofoId);
288
			itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
289
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23786 amit.gupta 290
		} else {
291
			if (fofoId == 0) {
23796 amit.gupta 292
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
293
						.selectItemsStock();
294
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
295
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23779 amit.gupta 296
			} else {
23796 amit.gupta 297
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
298
						.selectItemsStock(fofoId);
299
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
300
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
23405 amit.gupta 301
			}
23786 amit.gupta 302
		}
303
		List<BrandPerformance> brandPerformanceList = new ArrayList<>();
304
		List<BrandPerformance> accsBrandPerformanceList = new ArrayList<>();
305
		List<StockAllocationModel> stockAllocationList;
306
		if (fofoId > 0) {
307
			stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
308
		} else {
309
			stockAllocationList = stockAllocationService.getStockAllocation(counterSize, true);
310
		}
311
		LOGGER.info("Stock Allocation list  is {}", stockAllocationList);
23405 amit.gupta 312
 
23786 amit.gupta 313
		Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
24231 amit.gupta 314
				.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
23796 amit.gupta 315
		Map<Integer, Integer> itemsInTransit = null;
23786 amit.gupta 316
		LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
23855 amit.gupta 317
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
23796 amit.gupta 318
		if (!roleManager.isAdmin(roleIds)) {
23786 amit.gupta 319
			tagListings = new ArrayList<>(tagListings);
23796 amit.gupta 320
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
321
			inTransitOrders = this.filterValidOrders(inTransitOrders);
322
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
323
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
324
		} else {
325
			itemsInTransit = new HashMap<>();
23786 amit.gupta 326
		}
327
		Iterator<TagListing> iterator = tagListings.iterator();
23796 amit.gupta 328
		int totalPcs = 0;
329
		int toBeOrdered = 0;
330
		float totalAmount = 0;
24231 amit.gupta 331
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
23786 amit.gupta 332
		while (iterator.hasNext()) {
333
			TagListing tagListing = iterator.next();
24231 amit.gupta 334
 
23786 amit.gupta 335
			Item item = itemRepository.selectById(tagListing.getItemId());
24231 amit.gupta 336
			// itemRepository.select
337
			// catalogTagListingMap
23786 amit.gupta 338
			if (roleManager.isAdmin(roleIds)) {
24231 amit.gupta 339
				if (item.getBrand() == null || item.getCategoryId() != 10006) {
23785 amit.gupta 340
					iterator.remove();
341
					continue;
342
				}
23786 amit.gupta 343
			} else {
24231 amit.gupta 344
				if (!(itemCisMap.containsKey(tagListing.getItemId())
24232 amit.gupta 345
						|| itemStockAllocationMap.containsKey(tagListing.getItemId()))) {
23786 amit.gupta 346
					iterator.remove();
347
					continue;
23779 amit.gupta 348
				}
349
			}
24231 amit.gupta 350
			int catalogId = item.getCatalogItemId();
351
 
352
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
353
			if (!catalogListingMap.containsKey(catalogId)) {
354
				catalogListingModel = new CatalogListingModel();
355
				catalogListingModel.setCatalogId(catalogId);
356
				catalogListingModel.setDp(tagListing.getSellingPrice());
357
				catalogListingModel.setMop(tagListing.getMop());
358
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
359
				StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(item.getCatalogItemId());
360
				int stockAllocationQuantity = stockAllocationModel == null ? 0 : stockAllocationModel.getQuantity();
361
				catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);
362
				catalogListingModel.setToBeOrdered(stockAllocationQuantity);
363
				catalogListingModel.setBrand(item.getBrand());
364
				if (item.getCategoryId() == 10006) {
365
					catalogListingModel.setCategoryId(item.getCategoryId());
366
				}
367
				catalogListingMap.put(catalogId, catalogListingModel);
368
			}
369
 
23796 amit.gupta 370
			ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
24231 amit.gupta 371
			int itemAvailability = itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability();
372
			catalogListingModel.setStockInHand(catalogListingModel.getStockInHand() + itemAvailability);
23796 amit.gupta 373
 
24231 amit.gupta 374
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
375
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
376
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
377
 
378
			if (catalogListingModel.getAllocatedQuantity() > 0) {
379
				toBeOrdered = Math.max(catalogListingModel.getToBeOrdered() - inTransitQty - itemAvailability, 0);
380
				catalogListingModel.setToBeOrdered(toBeOrdered);
23796 amit.gupta 381
			}
23786 amit.gupta 382
		}
24231 amit.gupta 383
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
23405 amit.gupta 384
 
24231 amit.gupta 385
		Map<Boolean, List<CatalogListingModel>> performanceMap = catalogModelList.stream()
386
				.collect(Collectors.groupingBy(x -> x.getCategoryId() == 10006));
387
		List<CatalogListingModel> mobileListing = performanceMap.get(true) == null ? new ArrayList<>()
388
				: performanceMap.get(true);
389
		List<CatalogListingModel> accsListing = performanceMap.get(false) == null ? new ArrayList<>()
390
				: performanceMap.get(false);
23785 amit.gupta 391
 
23786 amit.gupta 392
		Map<String, DoubleSummaryStatistics> accsStats = accsListing.stream().collect(Collectors.groupingBy(
393
				x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));
394
		Map<String, DoubleSummaryStatistics> mobStats = mobileListing.stream().collect(Collectors.groupingBy(
395
				x -> x.getBrand(), Collectors.summarizingDouble(x -> x.getAllocatedQuantity() * x.getMop())));
23785 amit.gupta 396
 
23786 amit.gupta 397
		for (Map.Entry<String, DoubleSummaryStatistics> entry : mobStats.entrySet()) {
398
			DoubleSummaryStatistics dss = entry.getValue();
399
			BrandPerformance bp = new BrandPerformance();
400
			bp.setTarget((float) dss.getSum());
401
			bp.setBrandName(entry.getKey());
402
			brandPerformanceList.add(bp);
403
		}
404
		for (Map.Entry<String, DoubleSummaryStatistics> entry : accsStats.entrySet()) {
405
			DoubleSummaryStatistics dss = entry.getValue();
406
			BrandPerformance bp = new BrandPerformance();
407
			bp.setTarget((float) dss.getSum());
408
			bp.setBrandName(entry.getKey());
409
			accsBrandPerformanceList.add(bp);
410
		}
411
		brandPerformanceList = brandPerformanceList.stream().filter(x -> x.getTarget() > 0)
23796 amit.gupta 412
				.sorted(Comparator.comparing(x -> x.getTarget())).collect(Collectors.toList());
23786 amit.gupta 413
		accsBrandPerformanceList = accsBrandPerformanceList.stream().filter(x -> x.getTarget() > 0)
23796 amit.gupta 414
				.sorted(Comparator.comparing(x -> x.getTarget())).collect(Collectors.toList());
23785 amit.gupta 415
 
23786 amit.gupta 416
		List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
417
				.collect(Collectors.toList());
418
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
419
		if (fofoId > 0) {
420
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
421
			model.addAttribute("retailerName",
422
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
423
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
424
			model.addAttribute("retailerId", customRetailer.getPartnerId());
425
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 426
		} else {
23786 amit.gupta 427
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 428
		}
23786 amit.gupta 429
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
430
		LOGGER.info("Custom retailers {}", customRetailers);
24231 amit.gupta 431
		// Lits<CatalogTagListing> catalog
432
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getToBeOrdered,
433
				Comparator.reverseOrder());
434
		model.addAttribute("catalogTagListings",
435
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
23786 amit.gupta 436
		model.addAttribute("customRetailers", customRetailers);
437
		model.addAttribute("brandPerformanceList", brandPerformanceList);
438
		model.addAttribute("accsBrandPerformanceList", accsBrandPerformanceList);
439
		model.addAttribute("counterSizes", CounterSize.values());
23796 amit.gupta 440
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
441
		model.addAttribute("totalAmount", totalAmount);
442
		model.addAttribute("totalPcs", totalPcs);
443
		model.addAttribute("walletAmount", userWalletRepository.selectByRetailerId(fofoId).getAmount());
444
		// model.addAttribute("itemCisMap", itemCisMap);
23786 amit.gupta 445
		return "open-indent";
23405 amit.gupta 446
	}
23796 amit.gupta 447
 
448
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
449
		Iterator<Order> orderIterator = lastOrdersList.iterator();
450
		while (orderIterator.hasNext()) {
451
			Order o = orderIterator.next();
452
			if (o.getInvoiceNumber() != null) {
453
				try {
454
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
455
					orderIterator.remove();
456
					continue;
457
				} catch (Exception e) {
458
 
459
				}
460
			}
461
		}
462
		return lastOrdersList;
463
	}
464
 
24231 amit.gupta 465
	@RequestMapping(value = "/indent/confirm-pause/{tagId}", method = RequestMethod.POST)
23855 amit.gupta 466
	public String raisePO(HttpServletRequest request, Model model, @PathVariable int tagId) throws Exception {
467
		tagListingRepository.updateActiveById(tagId, false);
468
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
469
		return "response";
470
	}
24231 amit.gupta 471
 
472
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 473
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
474
		boolean success = false;
475
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
476
		int fofoId = loginDetails.getFofoId();
477
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
478
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
479
		Client userClient = new UserClient().getClient();
24231 amit.gupta 480
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 481
 
24231 amit.gupta 482
		if (totalAmount > 0) {
23796 amit.gupta 483
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
484
			User user = userRepository.selectById(loginDetails.getFofoId());
485
			userClient = new UserClient().getClient();
486
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 487
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
488
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 489
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
490
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 491
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 492
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 493
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 494
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 495
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 496
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
497
			transactionClient = new TransactionClient().getClient();
498
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
499
			try {
500
				transactionClient.enqueueTransactionInfoEmail(transactionId);
501
			} catch (Exception e1) {
502
				e1.printStackTrace();
503
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
504
			}
505
			resetCart(transactionClient.getTransaction(transactionId));
506
		}
507
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
508
		return "response";
509
	}
24231 amit.gupta 510
 
511
	private void createPayment(User user, double totalAmount, long transactionId)
512
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 513
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
514
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
515
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 516
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
517
				false);
518
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
519
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 520
	}
24231 amit.gupta 521
 
23796 amit.gupta 522
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
523
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 524
		/*
525
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
526
		 * currentInventorySnapshots = currentInventorySnapshotRepository
527
		 * .selectItemsStock(fofoId); itemCisMap =
528
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
529
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
530
		 * List<StockAllocationModel> stockAllocationList =
531
		 * stockAllocationService.getStockAllocation(fofoId, true);
532
		 * 
533
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
534
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
535
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
536
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
537
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
538
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
539
		 * validOrderStatusList); inTransitOrders =
540
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
541
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
542
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
543
		 * x.getLineItem().getQuantity())));
544
		 * 
545
		 * Iterator<TagListing> iterator = tagListings.iterator();
546
		 * 
547
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
548
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
549
		 * tagListing.getAllocatedQuantity()); if
550
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
551
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
552
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
553
		 * itemCisMap.get(tagListing.getItemId());
554
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
555
		 * itemIdAvailability.getAvailability()); StockAllocationModel
556
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
557
		 * 
558
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
559
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
560
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
561
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
562
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
563
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
564
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
565
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
566
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
567
		 */
23796 amit.gupta 568
		return itemQuantities;
569
 
570
	}
24231 amit.gupta 571
 
23796 amit.gupta 572
	private long resetCart(Transaction transaction) {
573
		long sum = 0;
574
		Map<Long, Double> items = new HashMap<Long, Double>();
575
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
576
			sum += order.getGvAmount();
577
			for (LineItem lineitem : order.getLineitems()) {
578
				Long itemId = lineitem.getItem_id();
579
				Double quantity = items.get(itemId);
580
				if (quantity == null) {
581
					quantity = lineitem.getQuantity();
582
				} else {
583
					quantity = quantity + lineitem.getQuantity();
584
				}
585
				items.put(itemId, quantity);
586
			}
587
		}
588
 
589
		LOGGER.debug("Items to reset in cart are: " + items);
590
 
591
		try {
592
			Client userClient = new UserClient().getClient();
593
			userClient.resetCart(transaction.getShoppingCartid(), items);
594
		} catch (TException e) {
595
			LOGGER.error("Error while updating information in payment database.", e);
596
		} catch (ShoppingCartException e) {
597
			LOGGER.error("Error while reseting the cart in cart database.", e);
598
		} catch (Exception e) {
599
			LOGGER.error("Unexpected exception", e);
600
		}
601
		return sum;
602
	}
603
 
23405 amit.gupta 604
}