Subversion Repositories SmartDukaan

Rev

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