Subversion Repositories SmartDukaan

Rev

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