Subversion Repositories SmartDukaan

Rev

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