Subversion Repositories SmartDukaan

Rev

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