Subversion Repositories SmartDukaan

Rev

Rev 25732 | Rev 25796 | 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;
25736 tejbeer 44
import com.spice.profitmandi.common.model.BrandStockPrice;
24231 amit.gupta 45
import com.spice.profitmandi.common.model.CatalogListingModel;
23785 amit.gupta 46
import com.spice.profitmandi.common.model.CustomRetailer;
23786 amit.gupta 47
import com.spice.profitmandi.common.model.ItemIdAvailability;
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;
23785 amit.gupta 56
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25721 tejbeer 57
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
58
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
23796 amit.gupta 59
import com.spice.profitmandi.dao.entity.transaction.Order;
60
import com.spice.profitmandi.dao.entity.user.User;
25721 tejbeer 61
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 62
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
63
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 64
import com.spice.profitmandi.dao.repository.cs.CsService;
23779 amit.gupta 65
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 66
import com.spice.profitmandi.dao.repository.dtr.Mongo;
23405 amit.gupta 67
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
25732 tejbeer 68
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
25721 tejbeer 69
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
70
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
71
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
23796 amit.gupta 72
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
73
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
74
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
75
import com.spice.profitmandi.dao.repository.user.UserRepository;
23798 amit.gupta 76
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 77
import com.spice.profitmandi.service.inventory.InventoryService;
23779 amit.gupta 78
import com.spice.profitmandi.service.inventory.StockAllocationService;
79
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 80
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 81
import com.spice.profitmandi.thrift.clients.PaymentClient;
82
import com.spice.profitmandi.thrift.clients.TransactionClient;
83
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 84
import com.spice.profitmandi.web.model.LoginDetails;
85
import com.spice.profitmandi.web.util.CookiesProcessor;
86
import com.spice.profitmandi.web.util.MVCResponseSender;
87
 
23796 amit.gupta 88
import in.shop2020.logistics.PickUpType;
89
import in.shop2020.model.v1.order.LineItem;
90
import in.shop2020.model.v1.order.OrderSource;
91
import in.shop2020.model.v1.order.OrderStatus;
92
import in.shop2020.model.v1.order.OrderType;
93
import in.shop2020.model.v1.order.Transaction;
94
import in.shop2020.model.v1.order.TransactionService;
95
import in.shop2020.model.v1.order.TransactionStatus;
96
import in.shop2020.model.v1.user.ItemPriceQuantity;
97
import in.shop2020.model.v1.user.ShoppingCartException;
98
import in.shop2020.model.v1.user.UserContextService.Client;
99
import in.shop2020.payments.Attribute;
100
import in.shop2020.payments.PaymentException;
101
import in.shop2020.payments.PaymentStatus;
102
 
23405 amit.gupta 103
@Controller
104
@Transactional(rollbackFor = Throwable.class)
105
public class IndentController {
106
 
23568 govind 107
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 108
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 109
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 110
 
23796 amit.gupta 111
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
112
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
113
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
114
			OrderStatus.REACHED_DESTINATION_CITY);
115
 
24231 amit.gupta 116
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
117
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
118
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
119
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 120
 
25547 amit.gupta 121
	@Autowired
122
	WalletService walletService;
24231 amit.gupta 123
 
23405 amit.gupta 124
	@Autowired
25721 tejbeer 125
	private JavaMailSender googleMailSender;
126
 
127
	@Autowired
23405 amit.gupta 128
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 129
 
23796 amit.gupta 130
	@Autowired
131
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 132
 
23779 amit.gupta 133
	@Autowired
23796 amit.gupta 134
	private UserRepository userRepository;
135
 
136
	@Autowired
23779 amit.gupta 137
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 138
 
139
	@Autowired
23796 amit.gupta 140
	private OrderRepository orderRepository;
141
 
142
	@Autowired
23405 amit.gupta 143
	private ItemRepository itemRepository;
144
 
145
	@Autowired
23779 amit.gupta 146
	private StockAllocationService stockAllocationService;
147
 
148
	@Autowired
149
	private RetailerService retailerService;
23405 amit.gupta 150
 
151
	@Autowired
152
	private TagListingRepository tagListingRepository;
153
 
154
	@Autowired
155
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
156
 
157
	@Autowired
23796 amit.gupta 158
	private PurchaseRepository purchaseRepository;
159
 
160
	@Autowired
23405 amit.gupta 161
	private MVCResponseSender mvcResponseSender;
162
 
23785 amit.gupta 163
	@Autowired
25721 tejbeer 164
	private FocusedModelRepository focusedModelRepository;
165
 
166
	@Autowired
167
	private MonthlyPlannedRepository monthlyPlannedRepository;
168
 
169
	@Autowired
170
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 171
 
25721 tejbeer 172
	@Autowired
25732 tejbeer 173
	private FofoOrderItemRepository fofoOrderItemRepository;
174
 
175
	@Autowired
25721 tejbeer 176
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 177
 
25721 tejbeer 178
	@Autowired
23785 amit.gupta 179
	RoleManager roleManager;
23405 amit.gupta 180
 
25721 tejbeer 181
	@Autowired
25736 tejbeer 182
	private Mongo mongoClient;
183
 
184
	@Autowired
185
	private InventoryService inventoryService;
186
 
187
	@Autowired
25721 tejbeer 188
	CsService csService;
189
 
190
	/*
191
	 * @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
192
	 * public String saveOpenIndent(HttpServletRequest request, Model model,
193
	 * 
194
	 * @RequestBody List<StockAllocationModel>
195
	 * stockAllocationModelList, @RequestParam int fofoId,
196
	 * 
197
	 * @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws
198
	 * Exception { LoginDetails loginDetails =
199
	 * cookiesProcessor.getCookiesObject(request); boolean response = false; if
200
	 * (fofoId > 0) { FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
201
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
202
	 * x.setCounterSize(fs.getCounterSize()); }); } else {
203
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
204
	 * x.setCounterSize(counterSize); }); } if
205
	 * (roleManager.isAdmin(loginDetails.getRoleIds())) { response =
206
	 * stockAllocationService.addToAllocation(stockAllocationModelList);
207
	 * model.addAttribute("response",
208
	 * mvcResponseSender.createResponseString(response)); } return "response"; }
209
	 */
23779 amit.gupta 210
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 211
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
212
			@RequestParam int itemQty) throws Exception {
23405 amit.gupta 213
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
25721 tejbeer 214
		LocalDate currentMonthdate = LocalDate.now().withDayOfMonth(1);
215
		LOGGER.info("currentMonthdate" + currentMonthdate);
216
		LOGGER.info("catalogId" + catalogId);
217
		LOGGER.info("itemQty" + itemQty);
218
 
219
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
220
				currentMonthdate);
221
 
222
		if (monthlyPlanned == null) {
223
			monthlyPlanned = new MonthlyPlanned();
224
			monthlyPlanned.setFofoId(loginDetails.getFofoId());
225
			monthlyPlanned.setYearMonth(currentMonthdate);
226
			monthlyPlannedRepository.persist(monthlyPlanned);
227
			PlannedDetail pd = new PlannedDetail();
228
			pd.setCatalogId(catalogId);
229
			pd.setPlannedId(monthlyPlanned.getId());
230
			pd.setQuantity(itemQty);
231
			pd.setUpdatedTimestamp(LocalDateTime.now());
232
			plannedDetailRepository.persist(pd);
233
 
23786 amit.gupta 234
		} else {
25721 tejbeer 235
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
236
					catalogId);
237
			if (plannedDetail == null) {
238
				plannedDetail = new PlannedDetail();
239
				plannedDetail.setCatalogId(catalogId);
240
				plannedDetail.setPlannedId(monthlyPlanned.getId());
241
				plannedDetail.setQuantity(itemQty);
242
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
243
				plannedDetailRepository.persist(plannedDetail);
244
			} else if (itemQty == 0) {
245
				plannedDetailRepository.delete(plannedDetail);
246
 
247
			} else {
248
				plannedDetail.setCatalogId(catalogId);
249
				plannedDetail.setQuantity(itemQty);
250
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
251
			}
252
 
23785 amit.gupta 253
		}
25721 tejbeer 254
 
255
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
256
 
257
		return "response";
258
	}
259
 
260
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
261
	public String confirmOpenIndent(HttpServletRequest request, Model model) throws Exception {
262
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
263
		int fofoId = loginDetails.getFofoId();
264
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
265
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoId(fofoId);
266
 
267
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
268
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
269
 
270
		List<PlannedModel> plannedModel = new ArrayList<>();
271
		for (PlannedDetail plannedDetail : plannedDetails) {
272
 
273
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
274
			String itemDesription = items.get(0).getItemDescriptionNoColor();
275
			PlannedModel pm = new PlannedModel();
276
			pm.setItemDescription(itemDesription);
277
			pm.setStoreName(customRetailer.getBusinessName());
278
			pm.setQty(plannedDetail.getQuantity());
279
			pm.setFofoId(loginDetails.getFofoId());
280
			plannedModel.add(pm);
281
			LOGGER.info("plannedModel" + plannedModel);
282
 
23785 amit.gupta 283
		}
25732 tejbeer 284
		List<String> emails = csService.getAuthUserByPartnerId(fofoId);
285
		emails.add(customRetailer.getEmail());
25727 tejbeer 286
 
25732 tejbeer 287
		/*
288
		 * List<String> emails = new ArrayList<>(); emails.add("tejbeer1710@gmail.com");
289
		 */
25721 tejbeer 290
		LOGGER.info("emails" + emails);
291
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
292
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
293
				plannedModel.stream()
294
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
295
						.collect(Collectors.toList()));
296
		LOGGER.info("baos" + baos);
297
		Utils.sendMailWithAttachments(googleMailSender, emails.toArray(new String[emails.size()]), null,
298
				"Planned Indent", "PFA",
299
				new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });
300
 
301
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
23405 amit.gupta 302
		return "response";
303
	}
304
 
24231 amit.gupta 305
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
306
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
307
			@RequestParam(required = false, defaultValue = "0") int fofoId,
308
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 309
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
310
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 311
		LOGGER.info("Counter size is {}", counterSize);
312
		LOGGER.info("Fofo Id is {}", fofoId);
25721 tejbeer 313
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 314
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
315
					.collect(Collectors.toList());
316
			Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
23415 amit.gupta 317
 
24232 amit.gupta 318
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
319
					true);
320
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
321
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 322
 
24232 amit.gupta 323
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 324
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 325
				int retailerId = x.getFofoId();
326
				int catalogId;
327
				try {
328
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
329
					String key = catalogId + "-" + retailerId;
330
					if (!catalogUserQtyMap.containsKey(key)) {
331
						catalogUserQtyMap.put(key, 0);
332
					}
333
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
334
				} catch (ProfitMandiBusinessException e) {
335
					// TODO Auto-generated catch block
336
					throw new RuntimeException(e);
24231 amit.gupta 337
				}
338
			});
23779 amit.gupta 339
 
24231 amit.gupta 340
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 341
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
342
				try {
343
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
344
							+ x.getRetailerId();
345
				} catch (ProfitMandiBusinessException e) {
346
					// TODO Auto-generated catch block
347
					return "";
348
				}
349
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 350
 
24232 amit.gupta 351
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
352
 
353
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
354
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 355
			while (iterator.hasNext()) {
356
				TagListing tagListing = iterator.next();
357
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 358
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 359
				if (item.getCategoryId() != 10006) {
360
					continue;
361
				}
23779 amit.gupta 362
 
24232 amit.gupta 363
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
364
						? modelStockAllocationMap.get(catalogId)
365
						: 0;
366
				for (int retailerId : fofoIds) {
367
					String key = catalogId + "-" + retailerId;
368
					if (catalogListingMap.containsKey(key)) {
369
						continue;
24231 amit.gupta 370
					}
24232 amit.gupta 371
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
372
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
373
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
374
						continue;
375
					}
376
					CatalogListingModel catalogListingModel = new CatalogListingModel();
377
					catalogListingModel.setFofoId(retailerId);
378
					catalogListingModel.setModelName(item.getModelName());
379
					catalogListingModel.setModelNumber(item.getModelNumber());
380
					catalogListingModel.setCatalogId(catalogId);
381
					catalogListingModel.setDp(tagListing.getSellingPrice());
382
					catalogListingModel.setMop(tagListing.getMop());
383
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
384
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
385
					catalogListingModel.setInTransitQuantity(catalogInTransit);
386
					catalogListingModel
387
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 388
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 389
					catalogListingModel.setBrand(item.getBrand());
390
					catalogListingModel.setModelName(item.getModelName());
391
					catalogListingModel.setModelNumber(item.getModelNumber());
392
					catalogListingModel.setCategoryId(item.getCategoryId());
393
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 394
				}
395
			}
24824 govind 396
			List<List<? extends Serializable>> listOfRows = new ArrayList<>();
24231 amit.gupta 397
			for (CatalogListingModel clm : catalogListingMap.values()) {
398
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
24349 amit.gupta 399
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
400
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
401
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
402
						clm.getToBeOrdered()));
24231 amit.gupta 403
			}
24349 amit.gupta 404
			ByteArrayOutputStream baos = FileUtil
405
					.getCSVByteStream(
406
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
407
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
408
							listOfRows);
24231 amit.gupta 409
			HttpHeaders headers = new HttpHeaders();
410
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
411
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 412
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
413
					HttpStatus.OK);
23405 amit.gupta 414
		}
24231 amit.gupta 415
		return null;
24232 amit.gupta 416
 
23405 amit.gupta 417
	}
418
 
24349 amit.gupta 419
	@RequestMapping(value = "/itemsByCatalogId")
420
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
24410 amit.gupta 421
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 422
			throws ProfitMandiBusinessException {
24410 amit.gupta 423
		if (catalogId == 0) {
424
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
425
		}
24349 amit.gupta 426
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 427
		LOGGER.info("Items {}", items);
25378 tejbeer 428
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
429
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 430
		Map<Integer, TagListing> tagsMap = tagListingRepository
431
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 432
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 433
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 434
		JSONArray response = new JSONArray();
24413 amit.gupta 435
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 436
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
437
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 438
		});
439
		model.addAttribute("response", response.toString());
440
		return "response";
24410 amit.gupta 441
 
24349 amit.gupta 442
	}
443
 
23405 amit.gupta 444
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 445
	public String loadOpenIndent(HttpServletRequest request, Model model,
446
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 447
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 448
 
449
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
450
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 451
		LOGGER.info("Counter size is {}", counterSize);
452
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 453
		boolean isAdmin = roleManager.isAdmin(roleIds);
454
		Map<Integer, Integer> itemCisMap;
25721 tejbeer 455
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 456
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
23796 amit.gupta 457
			List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
458
					.selectItemsStock(fofoId);
25736 tejbeer 459
			LOGGER.info("currentInventorySnapshots" + currentInventorySnapshots);
23796 amit.gupta 460
			itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
25736 tejbeer 461
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
462
 
23786 amit.gupta 463
		} else {
464
			if (fofoId == 0) {
23796 amit.gupta 465
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
466
						.selectItemsStock();
25736 tejbeer 467
				LOGGER.info("currentInventorySnapshots2" + currentInventorySnapshots);
23796 amit.gupta 468
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
25736 tejbeer 469
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
23779 amit.gupta 470
			} else {
23796 amit.gupta 471
				List<ItemIdAvailability> currentInventorySnapshots = currentInventorySnapshotRepository
472
						.selectItemsStock(fofoId);
25736 tejbeer 473
				LOGGER.info("currentInventorySnapshots3" + currentInventorySnapshots);
23796 amit.gupta 474
				itemCisMap = currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
25736 tejbeer 475
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
23405 amit.gupta 476
			}
23786 amit.gupta 477
		}
25736 tejbeer 478
		Map<Integer, Integer> currentStock = null;
479
		if (!itemCisMap.isEmpty()) {
480
			currentStock = itemRepository.selectByIds(itemCisMap.keySet()).stream().collect(Collectors
481
					.groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> itemCisMap.get(x.getId()))));
482
		}
23786 amit.gupta 483
		List<StockAllocationModel> stockAllocationList;
484
		if (fofoId > 0) {
485
			stockAllocationList = stockAllocationService.getStockAllocation(fofoId, true);
486
		} else {
487
			stockAllocationList = stockAllocationService.getStockAllocation(counterSize, true);
488
		}
489
		LOGGER.info("Stock Allocation list  is {}", stockAllocationList);
23405 amit.gupta 490
 
23786 amit.gupta 491
		Map<Integer, StockAllocationModel> itemStockAllocationMap = stockAllocationList.stream()
24231 amit.gupta 492
				.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
23796 amit.gupta 493
		Map<Integer, Integer> itemsInTransit = null;
23786 amit.gupta 494
		LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
23855 amit.gupta 495
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 496
		if (!isAdmin) {
23786 amit.gupta 497
			tagListings = new ArrayList<>(tagListings);
23796 amit.gupta 498
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoId, validOrderStatusList);
499
			inTransitOrders = this.filterValidOrders(inTransitOrders);
500
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
501
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
502
		} else {
503
			itemsInTransit = new HashMap<>();
23786 amit.gupta 504
		}
505
		Iterator<TagListing> iterator = tagListings.iterator();
23796 amit.gupta 506
		int totalPcs = 0;
507
		int toBeOrdered = 0;
508
		float totalAmount = 0;
24231 amit.gupta 509
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
25721 tejbeer 510
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
511
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
25727 tejbeer 512
		LOGGER.info("fofoId" + loginDetails.getFofoId());
25721 tejbeer 513
		Map<Integer, Item> items = itemRepository
514
				.selectByIds(tagListings.stream().map(x -> x.getItemId()).collect(Collectors.toSet())).stream()
515
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
25728 tejbeer 516
 
25732 tejbeer 517
		List<Integer> fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
518
				LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
519
				.collect(Collectors.toList());
520
 
521
		Map<Integer, Integer> fofoOrderMap = fofoOrderItemRepository.selectByOrderIds(fofoOrderIds).stream()
522
				.collect(Collectors.groupingBy(y -> y.getItemId(), Collectors.summingInt(y -> y.getQuantity())));
25728 tejbeer 523
		LOGGER.info("fofoOrderMap" + fofoOrderMap);
25721 tejbeer 524
		Map<Integer, Integer> last15DaysMap = null;
25732 tejbeer 525
		if (!fofoOrderMap.isEmpty()) {
25721 tejbeer 526
			last15DaysMap = itemRepository.selectByIds(fofoOrderMap.keySet()).stream().collect(Collectors
527
					.groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> fofoOrderMap.get(x.getId()))));
25732 tejbeer 528
		}
529
		LOGGER.info("last15DaysMap" + last15DaysMap);
25721 tejbeer 530
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
531
				LocalDate.now().withDayOfMonth(1));
532
		Map<Integer, Integer> plannedDetailMap = null;
533
		if (monthlyPlanned != null) {
534
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
535
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
536
 
537
		}
538
 
23786 amit.gupta 539
		while (iterator.hasNext()) {
540
			TagListing tagListing = iterator.next();
24231 amit.gupta 541
 
25702 amit.gupta 542
			Item item = items.get(tagListing.getItemId());
24231 amit.gupta 543
			// itemRepository.select
544
			// catalogTagListingMap
25736 tejbeer 545
 
546
			if (item.getBrand() == null || item.getCategoryId() != 10006) {
547
				iterator.remove();
548
				continue;
23779 amit.gupta 549
			}
25721 tejbeer 550
 
24231 amit.gupta 551
			int catalogId = item.getCatalogItemId();
552
 
553
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
554
			if (!catalogListingMap.containsKey(catalogId)) {
555
				catalogListingModel = new CatalogListingModel();
556
				catalogListingModel.setCatalogId(catalogId);
557
				catalogListingModel.setDp(tagListing.getSellingPrice());
558
				catalogListingModel.setMop(tagListing.getMop());
559
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
560
				StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(item.getCatalogItemId());
561
				int stockAllocationQuantity = stockAllocationModel == null ? 0 : stockAllocationModel.getQuantity();
25721 tejbeer 562
				if (plannedDetailMap != null) {
563
 
564
					Integer quantity = plannedDetailMap.get(catalogId);
565
					if (quantity != null) {
566
						catalogListingModel.setAllocatedQuantity(quantity);
567
					} else {
568
 
569
						catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);
570
					}
571
				} else {
572
					catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);
573
				}
574
				if (last15DaysMap != null) {
575
					Integer last15DaysSale = last15DaysMap.get(catalogId);
576
 
577
					if (last15DaysSale != null) {
578
						catalogListingModel.setLast15DaysSale(last15DaysSale);
579
					} else {
580
						catalogListingModel.setLast15DaysSale(0);
581
					}
582
				} else {
583
					catalogListingModel.setLast15DaysSale(0);
584
				}
585
 
24231 amit.gupta 586
				catalogListingModel.setToBeOrdered(stockAllocationQuantity);
587
				catalogListingModel.setBrand(item.getBrand());
588
				if (item.getCategoryId() == 10006) {
589
					catalogListingModel.setCategoryId(item.getCategoryId());
590
				}
25721 tejbeer 591
 
592
				FocusedModel fm = focusedModelMap.get(catalogId);
593
				if (fm != null) {
594
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
595
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
596
 
597
				} else {
598
					catalogListingModel.setRecommendedQty(0);
599
					catalogListingModel.setMinimumQty(0);
600
				}
601
 
24231 amit.gupta 602
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 603
 
24231 amit.gupta 604
			}
25736 tejbeer 605
			int itemAvailability = 0;
606
			if (currentStock != null) {
607
				Integer qty = currentStock.get(catalogId);
608
				itemAvailability = qty == null ? 0 : qty;
609
				catalogListingModel.setStockInHand(itemAvailability);
610
			} else {
611
				catalogListingModel.setStockInHand(0);
612
			}
24231 amit.gupta 613
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
614
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
615
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
616
 
617
			if (catalogListingModel.getAllocatedQuantity() > 0) {
618
				toBeOrdered = Math.max(catalogListingModel.getToBeOrdered() - inTransitQty - itemAvailability, 0);
619
				catalogListingModel.setToBeOrdered(toBeOrdered);
23796 amit.gupta 620
			}
23786 amit.gupta 621
		}
25721 tejbeer 622
 
25702 amit.gupta 623
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 624
		if (fofoId > 0) {
625
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
626
			model.addAttribute("retailerName",
627
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
628
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
629
			model.addAttribute("retailerId", customRetailer.getPartnerId());
630
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 631
		} else {
23786 amit.gupta 632
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 633
		}
23786 amit.gupta 634
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 635
 
636
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
25721 tejbeer 637
		List<CatalogListingModel> catalogModel = catalogModelList.stream()
638
				.filter(x -> !(x.getBrand().equals("Live Demo"))).collect(Collectors.toList());
25702 amit.gupta 639
 
25721 tejbeer 640
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 641
				Comparator.reverseOrder());
25721 tejbeer 642
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
643
		model.addAttribute("catalogTagListings", catalogModel.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 644
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
25736 tejbeer 645
		model.addAttribute("brandStockPrices",this.getBrandStockPrices(loginDetails.getFofoId()));
23786 amit.gupta 646
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 647
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 648
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 649
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 650
		return "open-indent";
23405 amit.gupta 651
	}
23796 amit.gupta 652
 
653
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
654
		Iterator<Order> orderIterator = lastOrdersList.iterator();
655
		while (orderIterator.hasNext()) {
656
			Order o = orderIterator.next();
657
			if (o.getInvoiceNumber() != null) {
658
				try {
659
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
660
					orderIterator.remove();
661
					continue;
662
				} catch (Exception e) {
663
 
664
				}
665
			}
666
		}
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
 
910
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
911
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
912
 
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
}