Subversion Repositories SmartDukaan

Rev

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