Subversion Repositories SmartDukaan

Rev

Rev 25797 | Rev 25799 | 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
473
					.selectItems(CurrentInventorySnapshot.class, "itemId", equalsMap, notEqualsMap, equalsStockJoinMap,
474
							notEqualsJoinMap, "availability")
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
484
						.selectItems(CurrentInventorySnapshot.class, "itemId", equalsMap, notEqualsMap,
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
494
						.selectItems(CurrentInventorySnapshot.class, "itemId", equalsMap, notEqualsMap,
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
 
25721 tejbeer 523
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
524
				LocalDate.now().withDayOfMonth(1));
25797 tejbeer 525
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25721 tejbeer 526
		Map<Integer, Integer> plannedDetailMap = null;
527
		if (monthlyPlanned != null) {
528
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
529
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
530
 
531
		}
25797 tejbeer 532
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
25796 tejbeer 533
		List<Integer> fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
534
				LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
535
				.collect(Collectors.toList());
536
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
537
		Map<String, Object> equalsJoinMap = new HashMap<>();
538
		equalsJoinMap.put("orderId", fofoOrderIds);
24231 amit.gupta 539
 
25796 tejbeer 540
		Map<Integer, Integer> last15daysMap = itemRepository
541
				.selectItems(FofoOrderItem.class, "itemId", equalsMap, notEqualsMap, equalsJoinMap, notEqualsJoinMap,
542
						"quantity")
543
				.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 544
		LOGGER.info("last15daysMap");
25796 tejbeer 545
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 546
 
25796 tejbeer 547
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
548
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
549
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
550
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
551
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 552
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 553
 
25796 tejbeer 554
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 555
		equalsItemJoinMap.put("active", 1);
25796 tejbeer 556
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "itemId",
557
				equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 558
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 559
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
560
			int catalogId = catalogIdAggregateValue.getCatalogId();
561
			Item item = catalogIdItemMap.get(catalogId).get(0);
562
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 563
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
564
			if (!catalogListingMap.containsKey(catalogId)) {
565
				catalogListingModel = new CatalogListingModel();
566
				catalogListingModel.setCatalogId(catalogId);
567
				catalogListingModel.setDp(tagListing.getSellingPrice());
568
				catalogListingModel.setMop(tagListing.getMop());
569
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 570
				if (plannedDetailMap != null) {
571
 
572
					Integer quantity = plannedDetailMap.get(catalogId);
573
					if (quantity != null) {
574
						catalogListingModel.setAllocatedQuantity(quantity);
575
					}
576
				}
577
 
25796 tejbeer 578
				if (last15daysMap != null) {
579
					Integer last15DaysSale = last15daysMap.get(catalogId);
580
 
25721 tejbeer 581
					if (last15DaysSale != null) {
582
						catalogListingModel.setLast15DaysSale(last15DaysSale);
583
					} else {
584
						catalogListingModel.setLast15DaysSale(0);
585
					}
586
				} else {
587
					catalogListingModel.setLast15DaysSale(0);
588
				}
589
 
24231 amit.gupta 590
				catalogListingModel.setBrand(item.getBrand());
591
				if (item.getCategoryId() == 10006) {
592
					catalogListingModel.setCategoryId(item.getCategoryId());
593
				}
25721 tejbeer 594
 
595
				FocusedModel fm = focusedModelMap.get(catalogId);
596
				if (fm != null) {
597
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
598
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
599
 
600
				} else {
601
					catalogListingModel.setRecommendedQty(0);
602
					catalogListingModel.setMinimumQty(0);
603
				}
604
 
24231 amit.gupta 605
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 606
 
24231 amit.gupta 607
			}
25736 tejbeer 608
			int itemAvailability = 0;
25796 tejbeer 609
			if (currentStockMap != null) {
610
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 611
				itemAvailability = qty == null ? 0 : qty;
612
				catalogListingModel.setStockInHand(itemAvailability);
613
			} else {
614
				catalogListingModel.setStockInHand(0);
615
			}
24231 amit.gupta 616
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
617
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
618
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
619
 
23786 amit.gupta 620
		}
25721 tejbeer 621
 
25702 amit.gupta 622
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 623
		if (fofoId > 0) {
624
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
625
			model.addAttribute("retailerName",
626
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
627
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
628
			model.addAttribute("retailerId", customRetailer.getPartnerId());
629
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 630
		} else {
23786 amit.gupta 631
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 632
		}
23786 amit.gupta 633
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 634
 
635
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
636
 
25721 tejbeer 637
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 638
				Comparator.reverseOrder());
25721 tejbeer 639
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 640
		model.addAttribute("catalogTagListings",
641
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 642
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
25798 tejbeer 643
	    model.addAttribute("brandStockPrices",this.getBrandStockPrices(loginDetails.getFofoId()));
23786 amit.gupta 644
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 645
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 646
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 647
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 648
		return "open-indent";
25796 tejbeer 649
 
23405 amit.gupta 650
	}
23796 amit.gupta 651
 
652
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
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();
660
					continue;
661
				} catch (Exception e) {
662
 
663
				}
664
			}
665
		}
666
		return lastOrdersList;
667
	}
668
 
24406 amit.gupta 669
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 670
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
671
			throws Exception {
24406 amit.gupta 672
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 673
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 674
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 675
 
24406 amit.gupta 676
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 677
			if (tl == null) {
678
				continue;
679
			} else {
680
				tl.setActive(obj.getBoolean("active"));
681
				tagListingRepository.persist(tl);
682
			}
24406 amit.gupta 683
		}
24410 amit.gupta 684
		model.addAttribute("response", true);
23855 amit.gupta 685
		return "response";
686
	}
24231 amit.gupta 687
 
688
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 689
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
690
		boolean success = false;
691
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
692
		int fofoId = loginDetails.getFofoId();
693
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
694
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
695
		Client userClient = new UserClient().getClient();
24231 amit.gupta 696
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 697
 
24231 amit.gupta 698
		if (totalAmount > 0) {
23796 amit.gupta 699
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
700
			User user = userRepository.selectById(loginDetails.getFofoId());
701
			userClient = new UserClient().getClient();
702
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 703
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
704
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 705
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
706
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 707
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 708
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 709
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 710
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 711
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 712
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
713
			transactionClient = new TransactionClient().getClient();
714
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
715
			try {
716
				transactionClient.enqueueTransactionInfoEmail(transactionId);
717
			} catch (Exception e1) {
718
				e1.printStackTrace();
719
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
720
			}
721
			resetCart(transactionClient.getTransaction(transactionId));
722
		}
723
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
724
		return "response";
725
	}
24231 amit.gupta 726
 
727
	private void createPayment(User user, double totalAmount, long transactionId)
728
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 729
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
730
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
731
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 732
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
733
				false);
734
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
735
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 736
	}
24231 amit.gupta 737
 
23796 amit.gupta 738
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
739
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 740
		/*
741
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
742
		 * currentInventorySnapshots = currentInventorySnapshotRepository
743
		 * .selectItemsStock(fofoId); itemCisMap =
744
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
745
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
746
		 * List<StockAllocationModel> stockAllocationList =
747
		 * stockAllocationService.getStockAllocation(fofoId, true);
748
		 * 
749
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
750
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
751
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
752
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
753
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
754
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
755
		 * validOrderStatusList); inTransitOrders =
756
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
757
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
758
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
759
		 * x.getLineItem().getQuantity())));
760
		 * 
761
		 * Iterator<TagListing> iterator = tagListings.iterator();
762
		 * 
763
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
764
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
765
		 * tagListing.getAllocatedQuantity()); if
766
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
767
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
768
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
769
		 * itemCisMap.get(tagListing.getItemId());
770
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
771
		 * itemIdAvailability.getAvailability()); StockAllocationModel
772
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
773
		 * 
774
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
775
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
776
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
777
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
778
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
779
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
780
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
781
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
782
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
783
		 */
23796 amit.gupta 784
		return itemQuantities;
785
 
786
	}
24231 amit.gupta 787
 
23796 amit.gupta 788
	private long resetCart(Transaction transaction) {
789
		long sum = 0;
790
		Map<Long, Double> items = new HashMap<Long, Double>();
791
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
792
			sum += order.getGvAmount();
793
			for (LineItem lineitem : order.getLineitems()) {
794
				Long itemId = lineitem.getItem_id();
795
				Double quantity = items.get(itemId);
796
				if (quantity == null) {
797
					quantity = lineitem.getQuantity();
798
				} else {
799
					quantity = quantity + lineitem.getQuantity();
800
				}
801
				items.put(itemId, quantity);
802
			}
803
		}
804
 
805
		LOGGER.debug("Items to reset in cart are: " + items);
806
 
807
		try {
808
			Client userClient = new UserClient().getClient();
809
			userClient.resetCart(transaction.getShoppingCartid(), items);
810
		} catch (TException e) {
811
			LOGGER.error("Error while updating information in payment database.", e);
812
		} catch (ShoppingCartException e) {
813
			LOGGER.error("Error while reseting the cart in cart database.", e);
814
		} catch (Exception e) {
815
			LOGGER.error("Unexpected exception", e);
816
		}
817
		return sum;
818
	}
819
 
25721 tejbeer 820
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
821
	public String getFocusedModel(HttpServletRequest request,
822
			@RequestParam(name = "offset", defaultValue = "0") int offset,
823
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
824
			throws ProfitMandiBusinessException {
25736 tejbeer 825
 
826
		long size = 0;
25721 tejbeer 827
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 828
		size = focusedModelRepository.selectAllCount();
25721 tejbeer 829
 
25736 tejbeer 830
		if (!focusedModels.isEmpty()) {
831
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
25721 tejbeer 832
 
25736 tejbeer 833
			model.addAttribute("focusedModels", focusedModels);
834
			model.addAttribute("itemMap", itemMap);
25721 tejbeer 835
 
25736 tejbeer 836
			model.addAttribute("start", offset + 1);
837
			model.addAttribute("size", size);
838
			model.addAttribute("url", "/getPaginatedFocusedModel");
839
 
840
			if (focusedModels.size() < limit) {
841
				model.addAttribute("end", offset + focusedModels.size());
842
			} else {
843
				model.addAttribute("end", offset + limit);
844
			}
845
		} else {
846
 
847
			model.addAttribute("walletRequest", focusedModels);
848
			model.addAttribute("size", size);
849
 
850
		}
851
 
25721 tejbeer 852
		return "focused_model";
853
	}
854
 
25736 tejbeer 855
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
856
	public String getPaginatedFocusedModel(HttpServletRequest request,
857
			@RequestParam(name = "offset", defaultValue = "0") int offset,
858
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
859
			throws ProfitMandiBusinessException {
860
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
861
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
862
 
863
		if (!focusedModels.isEmpty()) {
864
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
865
 
866
			model.addAttribute("focusedModels", focusedModels);
867
			model.addAttribute("itemMap", itemMap);
868
 
869
			model.addAttribute("url", "/getPaginatedFocusedModel");
870
		} else {
871
			model.addAttribute("focusedModels", focusedModels);
872
 
873
		}
874
		return "focused-model-paginated";
875
	}
876
 
25721 tejbeer 877
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
878
		Map<Integer, Item> itemMap = new HashMap<>();
879
		for (FocusedModel focusedModel : focusedModels) {
880
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
881
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
882
		}
883
 
884
		return itemMap;
885
	}
886
 
887
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
888
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
889
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
890
 
891
		FocusedModel fm = new FocusedModel();
892
		fm.setCatalogId(catalogId);
893
		fm.setMinimumQty(minimumQty);
894
		fm.setRecommendedQty(recommended);
895
		fm.setCreatedTimestamp(LocalDateTime.now());
896
		focusedModelRepository.persist(fm);
897
		return "focused_model";
898
	}
899
 
900
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
901
	public String removeFocusedModelItem(HttpServletRequest request,
902
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
903
 
904
		focusedModelRepository.deleteById(catalogId);
905
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
906
		return "response";
907
	}
25736 tejbeer 908
 
25798 tejbeer 909
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
910
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 911
 
25798 tejbeer 912
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
913
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
914
 
915
		mobileBrands.stream().forEach(x -> {
916
			String brand = (String) x.get("name");
917
			if (brandStockPricesMap.containsKey(brand)) {
918
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
919
				brandStockPrice.setBrandUrl((String) x.get("url"));
920
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
921
				brandStockPrices.add(brandStockPrice);
922
			}
923
		});
924
 
925
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
926
				.collect(Collectors.toList());
927
	}
928
 
25721 tejbeer 929
}