Subversion Repositories SmartDukaan

Rev

Rev 25800 | Rev 25853 | 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;
25721 tejbeer 4
import java.time.LocalDate;
5
import java.time.LocalDateTime;
23785 amit.gupta 6
import java.util.ArrayList;
23405 amit.gupta 7
import java.util.Arrays;
23796 amit.gupta 8
import java.util.Collections;
9
import java.util.Comparator;
10
import java.util.HashMap;
24406 amit.gupta 11
import java.util.HashSet;
23785 amit.gupta 12
import java.util.Iterator;
23405 amit.gupta 13
import java.util.List;
14
import java.util.Map;
23785 amit.gupta 15
import java.util.Set;
25721 tejbeer 16
import java.util.function.Function;
23405 amit.gupta 17
import java.util.stream.Collectors;
18
 
19
import javax.servlet.http.HttpServletRequest;
20
 
24231 amit.gupta 21
import org.apache.commons.io.output.ByteArrayOutputStream;
23717 amit.gupta 22
import org.apache.logging.log4j.LogManager;
23568 govind 23
import org.apache.logging.log4j.Logger;
23796 amit.gupta 24
import org.apache.thrift.TException;
24349 amit.gupta 25
import org.json.JSONArray;
23779 amit.gupta 26
import org.json.JSONObject;
23405 amit.gupta 27
import org.springframework.beans.factory.annotation.Autowired;
24231 amit.gupta 28
import org.springframework.core.io.ByteArrayResource;
29
import org.springframework.http.HttpHeaders;
30
import org.springframework.http.HttpStatus;
31
import org.springframework.http.ResponseEntity;
25721 tejbeer 32
import org.springframework.mail.javamail.JavaMailSender;
23405 amit.gupta 33
import org.springframework.stereotype.Controller;
34
import org.springframework.transaction.annotation.Transactional;
35
import org.springframework.ui.Model;
36
import org.springframework.web.bind.annotation.RequestBody;
37
import org.springframework.web.bind.annotation.RequestMapping;
38
import org.springframework.web.bind.annotation.RequestMethod;
23779 amit.gupta 39
import org.springframework.web.bind.annotation.RequestParam;
23405 amit.gupta 40
 
25736 tejbeer 41
import com.mongodb.DBObject;
23785 amit.gupta 42
import com.spice.profitmandi.common.enumuration.CounterSize;
23405 amit.gupta 43
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25798 tejbeer 44
import com.spice.profitmandi.common.model.BrandStockPrice;
25796 tejbeer 45
import com.spice.profitmandi.common.model.CatalogIdAggregateValue;
24231 amit.gupta 46
import com.spice.profitmandi.common.model.CatalogListingModel;
23785 amit.gupta 47
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 48
import com.spice.profitmandi.common.model.PlannedModel;
23779 amit.gupta 49
import com.spice.profitmandi.common.model.StockAllocationModel;
24231 amit.gupta 50
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 51
import com.spice.profitmandi.common.util.Utils;
52
import com.spice.profitmandi.common.util.Utils.Attachment;
53
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 54
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 55
import com.spice.profitmandi.dao.entity.catalog.TagListing;
25796 tejbeer 56
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
57
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 58
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25721 tejbeer 59
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
60
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
23796 amit.gupta 61
import com.spice.profitmandi.dao.entity.transaction.Order;
62
import com.spice.profitmandi.dao.entity.user.User;
25721 tejbeer 63
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 64
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
65
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 66
import com.spice.profitmandi.dao.repository.cs.CsService;
23779 amit.gupta 67
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 68
import com.spice.profitmandi.dao.repository.dtr.Mongo;
23405 amit.gupta 69
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
25732 tejbeer 70
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
25721 tejbeer 71
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
72
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
73
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
23796 amit.gupta 74
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
75
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
76
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
77
import com.spice.profitmandi.dao.repository.user.UserRepository;
23798 amit.gupta 78
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 79
import com.spice.profitmandi.service.inventory.InventoryService;
23779 amit.gupta 80
import com.spice.profitmandi.service.inventory.StockAllocationService;
81
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 82
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 83
import com.spice.profitmandi.thrift.clients.PaymentClient;
84
import com.spice.profitmandi.thrift.clients.TransactionClient;
85
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 86
import com.spice.profitmandi.web.model.LoginDetails;
87
import com.spice.profitmandi.web.util.CookiesProcessor;
88
import com.spice.profitmandi.web.util.MVCResponseSender;
89
 
23796 amit.gupta 90
import in.shop2020.logistics.PickUpType;
91
import in.shop2020.model.v1.order.LineItem;
92
import in.shop2020.model.v1.order.OrderSource;
93
import in.shop2020.model.v1.order.OrderStatus;
94
import in.shop2020.model.v1.order.OrderType;
95
import in.shop2020.model.v1.order.Transaction;
96
import in.shop2020.model.v1.order.TransactionService;
97
import in.shop2020.model.v1.order.TransactionStatus;
98
import in.shop2020.model.v1.user.ItemPriceQuantity;
99
import in.shop2020.model.v1.user.ShoppingCartException;
100
import in.shop2020.model.v1.user.UserContextService.Client;
101
import in.shop2020.payments.Attribute;
102
import in.shop2020.payments.PaymentException;
103
import in.shop2020.payments.PaymentStatus;
104
 
23405 amit.gupta 105
@Controller
106
@Transactional(rollbackFor = Throwable.class)
107
public class IndentController {
108
 
23568 govind 109
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 110
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 111
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 112
 
23796 amit.gupta 113
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
114
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
115
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
116
			OrderStatus.REACHED_DESTINATION_CITY);
117
 
24231 amit.gupta 118
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
119
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
120
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
121
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 122
 
25547 amit.gupta 123
	@Autowired
124
	WalletService walletService;
24231 amit.gupta 125
 
23405 amit.gupta 126
	@Autowired
25721 tejbeer 127
	private JavaMailSender googleMailSender;
128
 
129
	@Autowired
23405 amit.gupta 130
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 131
 
23796 amit.gupta 132
	@Autowired
133
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 134
 
23779 amit.gupta 135
	@Autowired
23796 amit.gupta 136
	private UserRepository userRepository;
137
 
138
	@Autowired
23779 amit.gupta 139
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 140
 
141
	@Autowired
23796 amit.gupta 142
	private OrderRepository orderRepository;
143
 
144
	@Autowired
23405 amit.gupta 145
	private ItemRepository itemRepository;
146
 
147
	@Autowired
23779 amit.gupta 148
	private StockAllocationService stockAllocationService;
149
 
150
	@Autowired
151
	private RetailerService retailerService;
23405 amit.gupta 152
 
153
	@Autowired
154
	private TagListingRepository tagListingRepository;
155
 
156
	@Autowired
157
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
158
 
159
	@Autowired
23796 amit.gupta 160
	private PurchaseRepository purchaseRepository;
161
 
162
	@Autowired
23405 amit.gupta 163
	private MVCResponseSender mvcResponseSender;
164
 
23785 amit.gupta 165
	@Autowired
25721 tejbeer 166
	private FocusedModelRepository focusedModelRepository;
167
 
168
	@Autowired
169
	private MonthlyPlannedRepository monthlyPlannedRepository;
170
 
171
	@Autowired
172
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 173
 
25721 tejbeer 174
	@Autowired
25732 tejbeer 175
	private FofoOrderItemRepository fofoOrderItemRepository;
176
 
177
	@Autowired
25721 tejbeer 178
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 179
 
25721 tejbeer 180
	@Autowired
23785 amit.gupta 181
	RoleManager roleManager;
23405 amit.gupta 182
 
25721 tejbeer 183
	@Autowired
25736 tejbeer 184
	private Mongo mongoClient;
185
 
186
	@Autowired
187
	private InventoryService inventoryService;
188
 
189
	@Autowired
25721 tejbeer 190
	CsService csService;
191
 
192
	/*
193
	 * @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
194
	 * public String saveOpenIndent(HttpServletRequest request, Model model,
195
	 * 
196
	 * @RequestBody List<StockAllocationModel>
197
	 * stockAllocationModelList, @RequestParam int fofoId,
198
	 * 
199
	 * @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws
200
	 * Exception { LoginDetails loginDetails =
201
	 * cookiesProcessor.getCookiesObject(request); boolean response = false; if
202
	 * (fofoId > 0) { FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
203
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
204
	 * x.setCounterSize(fs.getCounterSize()); }); } else {
205
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
206
	 * x.setCounterSize(counterSize); }); } if
207
	 * (roleManager.isAdmin(loginDetails.getRoleIds())) { response =
208
	 * stockAllocationService.addToAllocation(stockAllocationModelList);
209
	 * model.addAttribute("response",
210
	 * mvcResponseSender.createResponseString(response)); } return "response"; }
211
	 */
23779 amit.gupta 212
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 213
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
214
			@RequestParam int itemQty) throws Exception {
23405 amit.gupta 215
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
25721 tejbeer 216
		LocalDate currentMonthdate = LocalDate.now().withDayOfMonth(1);
217
		LOGGER.info("currentMonthdate" + currentMonthdate);
218
		LOGGER.info("catalogId" + catalogId);
219
		LOGGER.info("itemQty" + itemQty);
220
 
221
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
222
				currentMonthdate);
223
 
224
		if (monthlyPlanned == null) {
225
			monthlyPlanned = new MonthlyPlanned();
226
			monthlyPlanned.setFofoId(loginDetails.getFofoId());
227
			monthlyPlanned.setYearMonth(currentMonthdate);
228
			monthlyPlannedRepository.persist(monthlyPlanned);
229
			PlannedDetail pd = new PlannedDetail();
230
			pd.setCatalogId(catalogId);
231
			pd.setPlannedId(monthlyPlanned.getId());
232
			pd.setQuantity(itemQty);
233
			pd.setUpdatedTimestamp(LocalDateTime.now());
234
			plannedDetailRepository.persist(pd);
235
 
23786 amit.gupta 236
		} else {
25721 tejbeer 237
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
238
					catalogId);
239
			if (plannedDetail == null) {
240
				plannedDetail = new PlannedDetail();
241
				plannedDetail.setCatalogId(catalogId);
242
				plannedDetail.setPlannedId(monthlyPlanned.getId());
243
				plannedDetail.setQuantity(itemQty);
244
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
245
				plannedDetailRepository.persist(plannedDetail);
246
			} else if (itemQty == 0) {
247
				plannedDetailRepository.delete(plannedDetail);
248
 
249
			} else {
250
				plannedDetail.setCatalogId(catalogId);
251
				plannedDetail.setQuantity(itemQty);
252
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
253
			}
254
 
23785 amit.gupta 255
		}
25721 tejbeer 256
 
257
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
258
 
259
		return "response";
260
	}
261
 
262
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
263
	public String confirmOpenIndent(HttpServletRequest request, Model model) throws Exception {
264
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
265
		int fofoId = loginDetails.getFofoId();
266
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
267
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoId(fofoId);
268
 
269
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
270
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
271
 
272
		List<PlannedModel> plannedModel = new ArrayList<>();
273
		for (PlannedDetail plannedDetail : plannedDetails) {
274
 
275
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
276
			String itemDesription = items.get(0).getItemDescriptionNoColor();
277
			PlannedModel pm = new PlannedModel();
278
			pm.setItemDescription(itemDesription);
279
			pm.setStoreName(customRetailer.getBusinessName());
280
			pm.setQty(plannedDetail.getQuantity());
281
			pm.setFofoId(loginDetails.getFofoId());
282
			plannedModel.add(pm);
283
			LOGGER.info("plannedModel" + plannedModel);
284
 
23785 amit.gupta 285
		}
25732 tejbeer 286
		List<String> emails = csService.getAuthUserByPartnerId(fofoId);
287
		emails.add(customRetailer.getEmail());
25727 tejbeer 288
 
25732 tejbeer 289
		/*
290
		 * List<String> emails = new ArrayList<>(); emails.add("tejbeer1710@gmail.com");
291
		 */
25721 tejbeer 292
		LOGGER.info("emails" + emails);
293
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
294
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
295
				plannedModel.stream()
296
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
297
						.collect(Collectors.toList()));
298
		LOGGER.info("baos" + baos);
299
		Utils.sendMailWithAttachments(googleMailSender, emails.toArray(new String[emails.size()]), null,
300
				"Planned Indent", "PFA",
301
				new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });
302
 
303
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
23405 amit.gupta 304
		return "response";
305
	}
306
 
24231 amit.gupta 307
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
308
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
309
			@RequestParam(required = false, defaultValue = "0") int fofoId,
310
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 311
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
312
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 313
		LOGGER.info("Counter size is {}", counterSize);
314
		LOGGER.info("Fofo Id is {}", fofoId);
25721 tejbeer 315
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 316
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
317
					.collect(Collectors.toList());
318
			Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
23415 amit.gupta 319
 
24232 amit.gupta 320
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
321
					true);
322
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
323
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 324
 
24232 amit.gupta 325
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 326
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 327
				int retailerId = x.getFofoId();
328
				int catalogId;
329
				try {
330
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
331
					String key = catalogId + "-" + retailerId;
332
					if (!catalogUserQtyMap.containsKey(key)) {
333
						catalogUserQtyMap.put(key, 0);
334
					}
335
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
336
				} catch (ProfitMandiBusinessException e) {
337
					// TODO Auto-generated catch block
338
					throw new RuntimeException(e);
24231 amit.gupta 339
				}
340
			});
23779 amit.gupta 341
 
24231 amit.gupta 342
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 343
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
344
				try {
345
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
346
							+ x.getRetailerId();
347
				} catch (ProfitMandiBusinessException e) {
348
					// TODO Auto-generated catch block
349
					return "";
350
				}
351
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 352
 
24232 amit.gupta 353
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
354
 
355
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
356
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 357
			while (iterator.hasNext()) {
358
				TagListing tagListing = iterator.next();
359
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 360
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 361
				if (item.getCategoryId() != 10006) {
362
					continue;
363
				}
23779 amit.gupta 364
 
24232 amit.gupta 365
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
366
						? modelStockAllocationMap.get(catalogId)
367
						: 0;
368
				for (int retailerId : fofoIds) {
369
					String key = catalogId + "-" + retailerId;
370
					if (catalogListingMap.containsKey(key)) {
371
						continue;
24231 amit.gupta 372
					}
24232 amit.gupta 373
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
374
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
375
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
376
						continue;
377
					}
378
					CatalogListingModel catalogListingModel = new CatalogListingModel();
379
					catalogListingModel.setFofoId(retailerId);
380
					catalogListingModel.setModelName(item.getModelName());
381
					catalogListingModel.setModelNumber(item.getModelNumber());
382
					catalogListingModel.setCatalogId(catalogId);
383
					catalogListingModel.setDp(tagListing.getSellingPrice());
384
					catalogListingModel.setMop(tagListing.getMop());
385
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
386
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
387
					catalogListingModel.setInTransitQuantity(catalogInTransit);
388
					catalogListingModel
389
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 390
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 391
					catalogListingModel.setBrand(item.getBrand());
392
					catalogListingModel.setModelName(item.getModelName());
393
					catalogListingModel.setModelNumber(item.getModelNumber());
394
					catalogListingModel.setCategoryId(item.getCategoryId());
395
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 396
				}
397
			}
24824 govind 398
			List<List<? extends Serializable>> listOfRows = new ArrayList<>();
24231 amit.gupta 399
			for (CatalogListingModel clm : catalogListingMap.values()) {
400
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
24349 amit.gupta 401
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
402
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
403
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
404
						clm.getToBeOrdered()));
24231 amit.gupta 405
			}
24349 amit.gupta 406
			ByteArrayOutputStream baos = FileUtil
407
					.getCSVByteStream(
408
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
409
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
410
							listOfRows);
24231 amit.gupta 411
			HttpHeaders headers = new HttpHeaders();
412
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
413
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 414
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
415
					HttpStatus.OK);
23405 amit.gupta 416
		}
24231 amit.gupta 417
		return null;
24232 amit.gupta 418
 
23405 amit.gupta 419
	}
420
 
24349 amit.gupta 421
	@RequestMapping(value = "/itemsByCatalogId")
422
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
24410 amit.gupta 423
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 424
			throws ProfitMandiBusinessException {
24410 amit.gupta 425
		if (catalogId == 0) {
426
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
427
		}
24349 amit.gupta 428
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 429
		LOGGER.info("Items {}", items);
25378 tejbeer 430
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
431
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 432
		Map<Integer, TagListing> tagsMap = tagListingRepository
433
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 434
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 435
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 436
		JSONArray response = new JSONArray();
24413 amit.gupta 437
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 438
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
439
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 440
		});
441
		model.addAttribute("response", response.toString());
442
		return "response";
24410 amit.gupta 443
 
24349 amit.gupta 444
	}
445
 
23405 amit.gupta 446
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 447
	public String loadOpenIndent(HttpServletRequest request, Model model,
448
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 449
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 450
 
451
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
452
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 453
		LOGGER.info("Counter size is {}", counterSize);
454
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 455
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 456
 
25797 tejbeer 457
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
458
				.collect(Collectors.toList());
459
 
25796 tejbeer 460
		Map<String, Object> equalsMap = new HashMap<>();
461
		equalsMap.put("categoryId", 10006);
25797 tejbeer 462
		equalsMap.put("brand", brands);
25796 tejbeer 463
		Map<String, List<?>> notEqualsMap = new HashMap<>();
464
 
465
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
466
		Map<Integer, Integer> currentStockMap;
467
 
25721 tejbeer 468
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 469
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 470
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
471
			equalsStockJoinMap.put("fofoId", fofoId);
472
			currentStockMap = itemRepository
25800 tejbeer 473
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
474
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 475
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 476
			LOGGER.info("currentStock");
23786 amit.gupta 477
		} else {
478
			if (fofoId == 0) {
25796 tejbeer 479
 
480
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
481
				equalsStockJoinMap.put("fofoId", fofoId);
482
 
483
				currentStockMap = itemRepository
25800 tejbeer 484
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 485
								equalsStockJoinMap, notEqualsJoinMap, "availability")
486
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
487
 
23779 amit.gupta 488
			} else {
25796 tejbeer 489
 
490
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
491
				equalsStockJoinMap.put("fofoId", fofoId);
492
 
493
				currentStockMap = itemRepository
25800 tejbeer 494
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 495
								equalsStockJoinMap, notEqualsJoinMap, "availability")
496
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
497
 
23405 amit.gupta 498
			}
23786 amit.gupta 499
		}
25796 tejbeer 500
 
501
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 502
 
23796 amit.gupta 503
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 504
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 505
		if (!isAdmin) {
23786 amit.gupta 506
			tagListings = new ArrayList<>(tagListings);
25797 tejbeer 507
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
23796 amit.gupta 508
			inTransitOrders = this.filterValidOrders(inTransitOrders);
509
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
510
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
511
		} else {
512
			itemsInTransit = new HashMap<>();
23786 amit.gupta 513
		}
25797 tejbeer 514
 
23796 amit.gupta 515
		int totalPcs = 0;
25797 tejbeer 516
 
23796 amit.gupta 517
		float totalAmount = 0;
24231 amit.gupta 518
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
25796 tejbeer 519
 
25721 tejbeer 520
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
521
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
25728 tejbeer 522
 
25799 tejbeer 523
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoId(loginDetails.getFofoId());
25797 tejbeer 524
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25721 tejbeer 525
		Map<Integer, Integer> plannedDetailMap = null;
526
		if (monthlyPlanned != null) {
527
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
528
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
529
 
530
		}
25797 tejbeer 531
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
25796 tejbeer 532
		List<Integer> fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
533
				LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
534
				.collect(Collectors.toList());
535
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
536
		Map<String, Object> equalsJoinMap = new HashMap<>();
537
		equalsJoinMap.put("orderId", fofoOrderIds);
24231 amit.gupta 538
 
25796 tejbeer 539
		Map<Integer, Integer> last15daysMap = itemRepository
25800 tejbeer 540
				.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
541
						notEqualsJoinMap, "quantity")
25796 tejbeer 542
				.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 543
		LOGGER.info("last15daysMap");
25796 tejbeer 544
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 545
 
25796 tejbeer 546
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
547
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
548
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
549
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
550
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 551
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 552
 
25796 tejbeer 553
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 554
		equalsItemJoinMap.put("active", 1);
25800 tejbeer 555
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
556
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 557
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 558
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
559
			int catalogId = catalogIdAggregateValue.getCatalogId();
560
			Item item = catalogIdItemMap.get(catalogId).get(0);
561
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 562
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
563
			if (!catalogListingMap.containsKey(catalogId)) {
564
				catalogListingModel = new CatalogListingModel();
565
				catalogListingModel.setCatalogId(catalogId);
566
				catalogListingModel.setDp(tagListing.getSellingPrice());
567
				catalogListingModel.setMop(tagListing.getMop());
568
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 569
				if (plannedDetailMap != null) {
570
 
571
					Integer quantity = plannedDetailMap.get(catalogId);
572
					if (quantity != null) {
573
						catalogListingModel.setAllocatedQuantity(quantity);
574
					}
575
				}
576
 
25796 tejbeer 577
				if (last15daysMap != null) {
578
					Integer last15DaysSale = last15daysMap.get(catalogId);
579
 
25721 tejbeer 580
					if (last15DaysSale != null) {
581
						catalogListingModel.setLast15DaysSale(last15DaysSale);
582
					} else {
583
						catalogListingModel.setLast15DaysSale(0);
584
					}
585
				} else {
586
					catalogListingModel.setLast15DaysSale(0);
587
				}
588
 
24231 amit.gupta 589
				catalogListingModel.setBrand(item.getBrand());
590
				if (item.getCategoryId() == 10006) {
591
					catalogListingModel.setCategoryId(item.getCategoryId());
592
				}
25721 tejbeer 593
 
594
				FocusedModel fm = focusedModelMap.get(catalogId);
595
				if (fm != null) {
596
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
597
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
598
 
599
				} else {
600
					catalogListingModel.setRecommendedQty(0);
601
					catalogListingModel.setMinimumQty(0);
602
				}
603
 
24231 amit.gupta 604
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 605
 
24231 amit.gupta 606
			}
25736 tejbeer 607
			int itemAvailability = 0;
25796 tejbeer 608
			if (currentStockMap != null) {
609
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 610
				itemAvailability = qty == null ? 0 : qty;
611
				catalogListingModel.setStockInHand(itemAvailability);
612
			} else {
613
				catalogListingModel.setStockInHand(0);
614
			}
24231 amit.gupta 615
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
616
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
617
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
618
 
23786 amit.gupta 619
		}
25721 tejbeer 620
 
25702 amit.gupta 621
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 622
		if (fofoId > 0) {
623
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
624
			model.addAttribute("retailerName",
625
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
626
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
627
			model.addAttribute("retailerId", customRetailer.getPartnerId());
628
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 629
		} else {
23786 amit.gupta 630
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 631
		}
23786 amit.gupta 632
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 633
 
634
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
635
 
25721 tejbeer 636
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 637
				Comparator.reverseOrder());
25721 tejbeer 638
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 639
		model.addAttribute("catalogTagListings",
640
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 641
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
25799 tejbeer 642
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
23786 amit.gupta 643
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 644
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 645
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 646
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 647
		return "open-indent";
25796 tejbeer 648
 
23405 amit.gupta 649
	}
23796 amit.gupta 650
 
651
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 652
		int orderRemovedCount = 0;
23796 amit.gupta 653
		Iterator<Order> orderIterator = lastOrdersList.iterator();
654
		while (orderIterator.hasNext()) {
655
			Order o = orderIterator.next();
656
			if (o.getInvoiceNumber() != null) {
657
				try {
658
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
659
					orderIterator.remove();
25812 amit.gupta 660
					orderRemovedCount++;
23796 amit.gupta 661
				} catch (Exception e) {
662
 
663
				}
664
			}
665
		}
25812 amit.gupta 666
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 667
		return lastOrdersList;
668
	}
669
 
24406 amit.gupta 670
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 671
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
672
			throws Exception {
24406 amit.gupta 673
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 674
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 675
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 676
 
24406 amit.gupta 677
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 678
			if (tl == null) {
679
				continue;
680
			} else {
681
				tl.setActive(obj.getBoolean("active"));
682
				tagListingRepository.persist(tl);
683
			}
24406 amit.gupta 684
		}
24410 amit.gupta 685
		model.addAttribute("response", true);
23855 amit.gupta 686
		return "response";
687
	}
24231 amit.gupta 688
 
689
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 690
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
691
		boolean success = false;
692
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
693
		int fofoId = loginDetails.getFofoId();
694
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
695
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
696
		Client userClient = new UserClient().getClient();
24231 amit.gupta 697
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 698
 
24231 amit.gupta 699
		if (totalAmount > 0) {
23796 amit.gupta 700
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
701
			User user = userRepository.selectById(loginDetails.getFofoId());
702
			userClient = new UserClient().getClient();
703
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 704
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
705
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 706
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
707
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 708
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 709
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 710
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 711
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 712
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 713
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
714
			transactionClient = new TransactionClient().getClient();
715
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
716
			try {
717
				transactionClient.enqueueTransactionInfoEmail(transactionId);
718
			} catch (Exception e1) {
719
				e1.printStackTrace();
720
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
721
			}
722
			resetCart(transactionClient.getTransaction(transactionId));
723
		}
724
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
725
		return "response";
726
	}
24231 amit.gupta 727
 
728
	private void createPayment(User user, double totalAmount, long transactionId)
729
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 730
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
731
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
732
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 733
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
734
				false);
735
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
736
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 737
	}
24231 amit.gupta 738
 
23796 amit.gupta 739
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
740
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 741
		/*
742
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
743
		 * currentInventorySnapshots = currentInventorySnapshotRepository
744
		 * .selectItemsStock(fofoId); itemCisMap =
745
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
746
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
747
		 * List<StockAllocationModel> stockAllocationList =
748
		 * stockAllocationService.getStockAllocation(fofoId, true);
749
		 * 
750
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
751
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
752
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
753
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
754
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
755
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
756
		 * validOrderStatusList); inTransitOrders =
757
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
758
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
759
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
760
		 * x.getLineItem().getQuantity())));
761
		 * 
762
		 * Iterator<TagListing> iterator = tagListings.iterator();
763
		 * 
764
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
765
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
766
		 * tagListing.getAllocatedQuantity()); if
767
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
768
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
769
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
770
		 * itemCisMap.get(tagListing.getItemId());
771
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
772
		 * itemIdAvailability.getAvailability()); StockAllocationModel
773
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
774
		 * 
775
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
776
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
777
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
778
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
779
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
780
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
781
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
782
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
783
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
784
		 */
23796 amit.gupta 785
		return itemQuantities;
786
 
787
	}
24231 amit.gupta 788
 
23796 amit.gupta 789
	private long resetCart(Transaction transaction) {
790
		long sum = 0;
791
		Map<Long, Double> items = new HashMap<Long, Double>();
792
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
793
			sum += order.getGvAmount();
794
			for (LineItem lineitem : order.getLineitems()) {
795
				Long itemId = lineitem.getItem_id();
796
				Double quantity = items.get(itemId);
797
				if (quantity == null) {
798
					quantity = lineitem.getQuantity();
799
				} else {
800
					quantity = quantity + lineitem.getQuantity();
801
				}
802
				items.put(itemId, quantity);
803
			}
804
		}
805
 
806
		LOGGER.debug("Items to reset in cart are: " + items);
807
 
808
		try {
809
			Client userClient = new UserClient().getClient();
810
			userClient.resetCart(transaction.getShoppingCartid(), items);
811
		} catch (TException e) {
812
			LOGGER.error("Error while updating information in payment database.", e);
813
		} catch (ShoppingCartException e) {
814
			LOGGER.error("Error while reseting the cart in cart database.", e);
815
		} catch (Exception e) {
816
			LOGGER.error("Unexpected exception", e);
817
		}
818
		return sum;
819
	}
820
 
25721 tejbeer 821
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
822
	public String getFocusedModel(HttpServletRequest request,
823
			@RequestParam(name = "offset", defaultValue = "0") int offset,
824
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
825
			throws ProfitMandiBusinessException {
25736 tejbeer 826
 
827
		long size = 0;
25721 tejbeer 828
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 829
		size = focusedModelRepository.selectAllCount();
25721 tejbeer 830
 
25736 tejbeer 831
		if (!focusedModels.isEmpty()) {
832
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
25721 tejbeer 833
 
25736 tejbeer 834
			model.addAttribute("focusedModels", focusedModels);
835
			model.addAttribute("itemMap", itemMap);
25721 tejbeer 836
 
25736 tejbeer 837
			model.addAttribute("start", offset + 1);
838
			model.addAttribute("size", size);
839
			model.addAttribute("url", "/getPaginatedFocusedModel");
840
 
841
			if (focusedModels.size() < limit) {
842
				model.addAttribute("end", offset + focusedModels.size());
843
			} else {
844
				model.addAttribute("end", offset + limit);
845
			}
846
		} else {
847
 
848
			model.addAttribute("walletRequest", focusedModels);
849
			model.addAttribute("size", size);
850
 
851
		}
852
 
25721 tejbeer 853
		return "focused_model";
854
	}
855
 
25736 tejbeer 856
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
857
	public String getPaginatedFocusedModel(HttpServletRequest request,
858
			@RequestParam(name = "offset", defaultValue = "0") int offset,
859
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
860
			throws ProfitMandiBusinessException {
861
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
862
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
863
 
864
		if (!focusedModels.isEmpty()) {
865
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
866
 
867
			model.addAttribute("focusedModels", focusedModels);
868
			model.addAttribute("itemMap", itemMap);
869
 
870
			model.addAttribute("url", "/getPaginatedFocusedModel");
871
		} else {
872
			model.addAttribute("focusedModels", focusedModels);
873
 
874
		}
875
		return "focused-model-paginated";
876
	}
877
 
25721 tejbeer 878
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
879
		Map<Integer, Item> itemMap = new HashMap<>();
880
		for (FocusedModel focusedModel : focusedModels) {
881
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
882
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
883
		}
884
 
885
		return itemMap;
886
	}
887
 
888
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
889
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
890
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
891
 
892
		FocusedModel fm = new FocusedModel();
893
		fm.setCatalogId(catalogId);
894
		fm.setMinimumQty(minimumQty);
895
		fm.setRecommendedQty(recommended);
896
		fm.setCreatedTimestamp(LocalDateTime.now());
897
		focusedModelRepository.persist(fm);
898
		return "focused_model";
899
	}
900
 
901
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
902
	public String removeFocusedModelItem(HttpServletRequest request,
903
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
904
 
905
		focusedModelRepository.deleteById(catalogId);
906
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
907
		return "response";
908
	}
25736 tejbeer 909
 
25798 tejbeer 910
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
911
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 912
 
25798 tejbeer 913
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
914
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
915
 
916
		mobileBrands.stream().forEach(x -> {
917
			String brand = (String) x.get("name");
918
			if (brandStockPricesMap.containsKey(brand)) {
919
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
920
				brandStockPrice.setBrandUrl((String) x.get("url"));
921
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
922
				brandStockPrices.add(brandStockPrice);
923
			}
924
		});
925
 
926
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
927
				.collect(Collectors.toList());
928
	}
929
 
25721 tejbeer 930
}