Subversion Repositories SmartDukaan

Rev

Rev 26179 | Rev 26721 | 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<>();
26618 tejbeer 607
 
25796 tejbeer 608
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 609
		Map<Integer, Integer> last15daysMap = null;
610
		if (!fofoOrderIds.isEmpty()) {
24231 amit.gupta 611
 
26618 tejbeer 612
			last15daysMap = itemRepository
613
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
614
							notEqualsJoinMap, "quantity")
615
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
616
		}
25796 tejbeer 617
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 618
 
25796 tejbeer 619
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
620
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
621
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
622
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
623
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 624
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 625
 
25796 tejbeer 626
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 627
		equalsItemJoinMap.put("active", 1);
25800 tejbeer 628
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
629
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 630
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 631
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
632
			int catalogId = catalogIdAggregateValue.getCatalogId();
633
			Item item = catalogIdItemMap.get(catalogId).get(0);
634
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 635
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
636
			if (!catalogListingMap.containsKey(catalogId)) {
637
				catalogListingModel = new CatalogListingModel();
638
				catalogListingModel.setCatalogId(catalogId);
639
				catalogListingModel.setDp(tagListing.getSellingPrice());
640
				catalogListingModel.setMop(tagListing.getMop());
641
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 642
				if (plannedDetailMap != null) {
643
 
644
					Integer quantity = plannedDetailMap.get(catalogId);
645
					if (quantity != null) {
646
						catalogListingModel.setAllocatedQuantity(quantity);
647
					}
648
				}
649
 
25796 tejbeer 650
				if (last15daysMap != null) {
651
					Integer last15DaysSale = last15daysMap.get(catalogId);
652
 
25721 tejbeer 653
					if (last15DaysSale != null) {
654
						catalogListingModel.setLast15DaysSale(last15DaysSale);
655
					} else {
656
						catalogListingModel.setLast15DaysSale(0);
657
					}
658
				} else {
659
					catalogListingModel.setLast15DaysSale(0);
660
				}
661
 
24231 amit.gupta 662
				catalogListingModel.setBrand(item.getBrand());
663
				if (item.getCategoryId() == 10006) {
664
					catalogListingModel.setCategoryId(item.getCategoryId());
665
				}
25721 tejbeer 666
 
667
				FocusedModel fm = focusedModelMap.get(catalogId);
668
				if (fm != null) {
669
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
670
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
671
 
672
				} else {
673
					catalogListingModel.setRecommendedQty(0);
674
					catalogListingModel.setMinimumQty(0);
675
				}
676
 
24231 amit.gupta 677
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 678
 
24231 amit.gupta 679
			}
25736 tejbeer 680
			int itemAvailability = 0;
25796 tejbeer 681
			if (currentStockMap != null) {
682
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 683
				itemAvailability = qty == null ? 0 : qty;
684
				catalogListingModel.setStockInHand(itemAvailability);
685
			} else {
686
				catalogListingModel.setStockInHand(0);
687
			}
24231 amit.gupta 688
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
689
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
690
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 691
			if (plannedDetailMap != null) {
26177 tejbeer 692
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 693
 
26177 tejbeer 694
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
695
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
696
					LOGGER.info("remaning" + remaining);
26176 tejbeer 697
 
26177 tejbeer 698
					if (remaining != 0) {
699
						catalogListingModel.setRemaining(remaining);
700
					} else {
701
						catalogListingModel.setRemaining(0);
702
					}
26176 tejbeer 703
				}
704
			}
23786 amit.gupta 705
		}
25721 tejbeer 706
 
25702 amit.gupta 707
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 708
		if (fofoId > 0) {
709
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
710
			model.addAttribute("retailerName",
711
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
712
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
713
			model.addAttribute("retailerId", customRetailer.getPartnerId());
714
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 715
		} else {
23786 amit.gupta 716
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 717
		}
23786 amit.gupta 718
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 719
 
720
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
721
 
25721 tejbeer 722
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 723
				Comparator.reverseOrder());
25721 tejbeer 724
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 725
		model.addAttribute("catalogTagListings",
726
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 727
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 728
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 729
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
730
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
731
 
23786 amit.gupta 732
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 733
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 734
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 735
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 736
		return "open-indent";
25796 tejbeer 737
 
23405 amit.gupta 738
	}
23796 amit.gupta 739
 
26131 tejbeer 740
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
741
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
742
			@RequestParam(required = false, defaultValue = "0") int fofoId,
743
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
744
 
745
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
746
		Set<Integer> roleIds = loginDetails.getRoleIds();
747
		LOGGER.info("Counter size is {}", counterSize);
748
		LOGGER.info("Fofo Id is {}", fofoId);
749
		boolean isAdmin = roleManager.isAdmin(roleIds);
750
 
751
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
752
				.collect(Collectors.toList());
753
 
754
		Map<String, Object> equalsMap = new HashMap<>();
755
		equalsMap.put("categoryId", 10006);
756
		equalsMap.put("brand", brands);
757
		Map<String, List<?>> notEqualsMap = new HashMap<>();
758
 
759
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
760
		Map<Integer, Integer> currentStockMap;
761
 
762
		if (!isAdmin && fofoId == 0) {
763
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
764
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
765
			equalsStockJoinMap.put("fofoId", fofoId);
766
			currentStockMap = itemRepository
767
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
768
							equalsStockJoinMap, notEqualsJoinMap, "availability")
769
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
770
			LOGGER.info("currentStock");
771
		} else {
772
			if (fofoId == 0) {
773
 
774
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
775
				equalsStockJoinMap.put("fofoId", fofoId);
776
 
777
				currentStockMap = itemRepository
778
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
779
								equalsStockJoinMap, notEqualsJoinMap, "availability")
780
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
781
 
782
			} else {
783
 
784
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
785
				equalsStockJoinMap.put("fofoId", fofoId);
786
 
787
				currentStockMap = itemRepository
788
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
789
								equalsStockJoinMap, notEqualsJoinMap, "availability")
790
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
791
 
792
			}
793
		}
794
 
795
		LOGGER.info("currentStock" + currentStockMap);
796
 
797
		Map<Integer, Integer> itemsInTransit = null;
798
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
799
		if (!isAdmin) {
800
			tagListings = new ArrayList<>(tagListings);
801
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
802
			inTransitOrders = this.filterValidOrders(inTransitOrders);
803
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
804
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
805
		} else {
806
			itemsInTransit = new HashMap<>();
807
		}
808
 
809
		int totalPcs = 0;
810
 
811
		float totalAmount = 0;
812
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
813
 
814
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
815
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
816
 
817
		LocalDate currentMonthDate = LocalDate.now().minusMonths(1).withDayOfMonth(1);
818
		MonthlyPlanned monthlyPlanned = null;
819
		monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
820
		LOGGER.info("monthlyPlanned2" + monthlyPlanned);
821
		model.addAttribute("planningMonth", LocalDate.now().minusMonths(1).getMonth());
822
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
823
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
824
 
825
		Map<Integer, Integer> plannedDetailMap = null;
826
		if (monthlyPlanned != null) {
827
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
828
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
829
 
830
		}
831
 
832
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
833
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
834
		List<Integer> fofoOrderIds = fofoOrderRepository
835
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
836
						curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1))
837
				.stream().map(x -> x.getId()).collect(Collectors.toList());
838
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
839
		Map<String, Object> equalsJoinMap = new HashMap<>();
840
		equalsJoinMap.put("orderId", fofoOrderIds);
841
 
842
		Map<Integer, Integer> lastMonthSaleMap = itemRepository
843
				.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
844
						notEqualsJoinMap, "quantity")
845
				.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
846
 
847
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
848
 
849
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
850
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
851
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
852
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
853
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
854
		LOGGER.info("catalogIdItemMap");
855
 
856
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
857
		equalsItemJoinMap.put("active", 1);
858
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
859
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
860
		LOGGER.info("tagListingCatalogIds");
861
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
862
			int catalogId = catalogIdAggregateValue.getCatalogId();
863
			Item item = catalogIdItemMap.get(catalogId).get(0);
864
			TagListing tagListing = taglistingMap.get(item.getId());
865
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
866
			if (!catalogListingMap.containsKey(catalogId)) {
867
				catalogListingModel = new CatalogListingModel();
868
				catalogListingModel.setCatalogId(catalogId);
869
				catalogListingModel.setDp(tagListing.getSellingPrice());
870
				catalogListingModel.setMop(tagListing.getMop());
871
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
872
				if (plannedDetailMap != null) {
873
 
874
					Integer quantity = plannedDetailMap.get(catalogId);
875
					if (quantity != null) {
876
						catalogListingModel.setAllocatedQuantity(quantity);
877
					}
878
				}
879
 
880
				if (lastMonthSaleMap != null) {
881
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
882
 
883
					if (lastMonthSale != null) {
884
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
885
					} else {
886
						catalogListingModel.setLastMonthSaleMap(0);
887
					}
888
				} else {
889
					catalogListingModel.setLast15DaysSale(0);
890
				}
891
 
892
				catalogListingModel.setBrand(item.getBrand());
893
				if (item.getCategoryId() == 10006) {
894
					catalogListingModel.setCategoryId(item.getCategoryId());
895
				}
896
 
897
				FocusedModel fm = focusedModelMap.get(catalogId);
898
				if (fm != null) {
899
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
900
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
901
 
902
				} else {
903
					catalogListingModel.setRecommendedQty(0);
904
					catalogListingModel.setMinimumQty(0);
905
				}
906
 
907
				catalogListingMap.put(catalogId, catalogListingModel);
908
 
909
			}
910
			int itemAvailability = 0;
911
			if (currentStockMap != null) {
912
				Integer qty = currentStockMap.get(catalogId);
913
				itemAvailability = qty == null ? 0 : qty;
914
				catalogListingModel.setStockInHand(itemAvailability);
915
			} else {
916
				catalogListingModel.setStockInHand(0);
917
			}
918
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
919
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
920
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
921
 
922
		}
923
 
924
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
925
		if (fofoId > 0) {
926
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
927
			model.addAttribute("retailerName",
928
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
929
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
930
			model.addAttribute("retailerId", customRetailer.getPartnerId());
931
			model.addAttribute("counterSize", fs.getCounterSize().toString());
932
		} else {
933
			model.addAttribute("counterSize", counterSize.toString());
934
		}
935
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
936
 
937
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
938
 
939
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
940
				Comparator.reverseOrder());
941
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
942
		model.addAttribute("catalogTagListings",
943
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
944
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
945
		model.addAttribute("previousMonth", true);
946
		model.addAttribute("freezed", true);
26177 tejbeer 947
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 948
		model.addAttribute("customRetailers", customRetailers);
949
		model.addAttribute("totalAmount", totalAmount);
950
		model.addAttribute("monthlyPlanned", monthlyPlanned);
951
		model.addAttribute("totalPcs", totalPcs);
952
		return "open-indent";
953
 
954
	}
955
 
23796 amit.gupta 956
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 957
		int orderRemovedCount = 0;
23796 amit.gupta 958
		Iterator<Order> orderIterator = lastOrdersList.iterator();
959
		while (orderIterator.hasNext()) {
960
			Order o = orderIterator.next();
961
			if (o.getInvoiceNumber() != null) {
962
				try {
963
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
964
					orderIterator.remove();
25812 amit.gupta 965
					orderRemovedCount++;
23796 amit.gupta 966
				} catch (Exception e) {
967
 
968
				}
969
			}
970
		}
25812 amit.gupta 971
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 972
		return lastOrdersList;
973
	}
974
 
24406 amit.gupta 975
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 976
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
977
			throws Exception {
24406 amit.gupta 978
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 979
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 980
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 981
 
24406 amit.gupta 982
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 983
			if (tl == null) {
984
				continue;
985
			} else {
986
				tl.setActive(obj.getBoolean("active"));
987
				tagListingRepository.persist(tl);
988
			}
24406 amit.gupta 989
		}
24410 amit.gupta 990
		model.addAttribute("response", true);
23855 amit.gupta 991
		return "response";
992
	}
24231 amit.gupta 993
 
994
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 995
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
996
		boolean success = false;
997
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
998
		int fofoId = loginDetails.getFofoId();
999
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
1000
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
1001
		Client userClient = new UserClient().getClient();
24231 amit.gupta 1002
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 1003
 
24231 amit.gupta 1004
		if (totalAmount > 0) {
23796 amit.gupta 1005
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
1006
			User user = userRepository.selectById(loginDetails.getFofoId());
1007
			userClient = new UserClient().getClient();
1008
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 1009
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
1010
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 1011
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
1012
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 1013
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 1014
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 1015
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1016
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 1017
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1018
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
1019
			transactionClient = new TransactionClient().getClient();
1020
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
1021
			try {
1022
				transactionClient.enqueueTransactionInfoEmail(transactionId);
1023
			} catch (Exception e1) {
1024
				e1.printStackTrace();
1025
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
1026
			}
1027
			resetCart(transactionClient.getTransaction(transactionId));
1028
		}
1029
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
1030
		return "response";
1031
	}
24231 amit.gupta 1032
 
1033
	private void createPayment(User user, double totalAmount, long transactionId)
1034
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 1035
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
1036
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
1037
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 1038
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
1039
				false);
1040
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
1041
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 1042
	}
24231 amit.gupta 1043
 
23796 amit.gupta 1044
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
1045
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 1046
		/*
1047
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
1048
		 * currentInventorySnapshots = currentInventorySnapshotRepository
1049
		 * .selectItemsStock(fofoId); itemCisMap =
1050
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
1051
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1052
		 * List<StockAllocationModel> stockAllocationList =
1053
		 * stockAllocationService.getStockAllocation(fofoId, true);
1054
		 * 
1055
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
1056
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
1057
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
1058
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
1059
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
1060
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
1061
		 * validOrderStatusList); inTransitOrders =
1062
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
1063
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
1064
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
1065
		 * x.getLineItem().getQuantity())));
1066
		 * 
1067
		 * Iterator<TagListing> iterator = tagListings.iterator();
1068
		 * 
1069
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
1070
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
1071
		 * tagListing.getAllocatedQuantity()); if
1072
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
1073
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
1074
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
1075
		 * itemCisMap.get(tagListing.getItemId());
1076
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
1077
		 * itemIdAvailability.getAvailability()); StockAllocationModel
1078
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
1079
		 * 
1080
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
1081
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
1082
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
1083
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
1084
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
1085
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
1086
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
1087
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
1088
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
1089
		 */
23796 amit.gupta 1090
		return itemQuantities;
1091
 
1092
	}
24231 amit.gupta 1093
 
23796 amit.gupta 1094
	private long resetCart(Transaction transaction) {
1095
		long sum = 0;
1096
		Map<Long, Double> items = new HashMap<Long, Double>();
1097
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
1098
			sum += order.getGvAmount();
1099
			for (LineItem lineitem : order.getLineitems()) {
1100
				Long itemId = lineitem.getItem_id();
1101
				Double quantity = items.get(itemId);
1102
				if (quantity == null) {
1103
					quantity = lineitem.getQuantity();
1104
				} else {
1105
					quantity = quantity + lineitem.getQuantity();
1106
				}
1107
				items.put(itemId, quantity);
1108
			}
1109
		}
1110
 
1111
		LOGGER.debug("Items to reset in cart are: " + items);
1112
 
1113
		try {
1114
			Client userClient = new UserClient().getClient();
1115
			userClient.resetCart(transaction.getShoppingCartid(), items);
1116
		} catch (TException e) {
1117
			LOGGER.error("Error while updating information in payment database.", e);
1118
		} catch (ShoppingCartException e) {
1119
			LOGGER.error("Error while reseting the cart in cart database.", e);
1120
		} catch (Exception e) {
1121
			LOGGER.error("Unexpected exception", e);
1122
		}
1123
		return sum;
1124
	}
1125
 
25721 tejbeer 1126
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1127
	public String getFocusedModel(HttpServletRequest request,
1128
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1129
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1130
			throws ProfitMandiBusinessException {
25736 tejbeer 1131
 
1132
		long size = 0;
25721 tejbeer 1133
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 1134
		size = focusedModelRepository.selectAllCount();
25721 tejbeer 1135
 
25736 tejbeer 1136
		if (!focusedModels.isEmpty()) {
1137
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
25721 tejbeer 1138
 
25736 tejbeer 1139
			model.addAttribute("focusedModels", focusedModels);
1140
			model.addAttribute("itemMap", itemMap);
25721 tejbeer 1141
 
25736 tejbeer 1142
			model.addAttribute("start", offset + 1);
1143
			model.addAttribute("size", size);
1144
			model.addAttribute("url", "/getPaginatedFocusedModel");
1145
 
1146
			if (focusedModels.size() < limit) {
1147
				model.addAttribute("end", offset + focusedModels.size());
1148
			} else {
1149
				model.addAttribute("end", offset + limit);
1150
			}
1151
		} else {
1152
 
1153
			model.addAttribute("walletRequest", focusedModels);
1154
			model.addAttribute("size", size);
1155
 
1156
		}
1157
 
25721 tejbeer 1158
		return "focused_model";
1159
	}
1160
 
25736 tejbeer 1161
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1162
	public String getPaginatedFocusedModel(HttpServletRequest request,
1163
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1164
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1165
			throws ProfitMandiBusinessException {
1166
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1167
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1168
 
1169
		if (!focusedModels.isEmpty()) {
1170
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1171
 
1172
			model.addAttribute("focusedModels", focusedModels);
1173
			model.addAttribute("itemMap", itemMap);
1174
 
1175
			model.addAttribute("url", "/getPaginatedFocusedModel");
1176
		} else {
1177
			model.addAttribute("focusedModels", focusedModels);
1178
 
1179
		}
1180
		return "focused-model-paginated";
1181
	}
1182
 
25721 tejbeer 1183
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1184
		Map<Integer, Item> itemMap = new HashMap<>();
1185
		for (FocusedModel focusedModel : focusedModels) {
1186
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1187
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1188
		}
1189
 
1190
		return itemMap;
1191
	}
1192
 
1193
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1194
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
1195
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
1196
 
1197
		FocusedModel fm = new FocusedModel();
1198
		fm.setCatalogId(catalogId);
1199
		fm.setMinimumQty(minimumQty);
1200
		fm.setRecommendedQty(recommended);
1201
		fm.setCreatedTimestamp(LocalDateTime.now());
1202
		focusedModelRepository.persist(fm);
1203
		return "focused_model";
1204
	}
1205
 
1206
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1207
	public String removeFocusedModelItem(HttpServletRequest request,
1208
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
1209
 
1210
		focusedModelRepository.deleteById(catalogId);
1211
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1212
		return "response";
1213
	}
25736 tejbeer 1214
 
25798 tejbeer 1215
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1216
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1217
 
25798 tejbeer 1218
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1219
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1220
 
1221
		mobileBrands.stream().forEach(x -> {
1222
			String brand = (String) x.get("name");
1223
			if (brandStockPricesMap.containsKey(brand)) {
1224
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1225
				brandStockPrice.setBrandUrl((String) x.get("url"));
1226
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1227
				brandStockPrices.add(brandStockPrice);
1228
			}
1229
		});
1230
 
1231
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1232
				.collect(Collectors.toList());
1233
	}
1234
 
25721 tejbeer 1235
}