Subversion Repositories SmartDukaan

Rev

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