Subversion Repositories SmartDukaan

Rev

Rev 30664 | Rev 31238 | 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
 
25736 tejbeer 3
import com.mongodb.DBObject;
30046 tejbeer 4
import com.spice.profitmandi.common.enumuration.ActivationType;
23785 amit.gupta 5
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 6
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 7
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 8
import com.spice.profitmandi.common.model.*;
24231 amit.gupta 9
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 10
import com.spice.profitmandi.common.util.Utils;
11
import com.spice.profitmandi.common.util.Utils.Attachment;
26721 tejbeer 12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30003 tejbeer 13
import com.spice.profitmandi.dao.entity.catalog.Category;
25721 tejbeer 14
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 15
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 16
import com.spice.profitmandi.dao.entity.catalog.TagListing;
27088 tejbeer 17
import com.spice.profitmandi.dao.entity.cs.Region;
30017 amit.gupta 18
import com.spice.profitmandi.dao.entity.fofo.*;
30664 amit.gupta 19
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
30003 tejbeer 20
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
23796 amit.gupta 21
import com.spice.profitmandi.dao.entity.transaction.Order;
26846 tejbeer 22
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
23796 amit.gupta 23
import com.spice.profitmandi.dao.entity.user.User;
30017 amit.gupta 24
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
26978 tejbeer 25
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
30003 tejbeer 26
import com.spice.profitmandi.dao.model.FofoReportingModel;
27
import com.spice.profitmandi.dao.model.InStockAccessoriesTvFofoIdModel;
28
import com.spice.profitmandi.dao.model.InStockBrandFofoIdModel;
26721 tejbeer 29
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
30003 tejbeer 30
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
25721 tejbeer 31
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 32
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
33
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 34
import com.spice.profitmandi.dao.repository.cs.CsService;
27088 tejbeer 35
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
30003 tejbeer 36
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
27088 tejbeer 37
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
30044 tejbeer 38
import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;
23779 amit.gupta 39
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 40
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 41
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
30017 amit.gupta 42
import com.spice.profitmandi.dao.repository.fofo.*;
30664 amit.gupta 43
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
27768 tejbeer 44
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
30017 amit.gupta 45
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
23796 amit.gupta 46
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
47
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
48
import com.spice.profitmandi.dao.repository.user.UserRepository;
30017 amit.gupta 49
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
26846 tejbeer 50
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 51
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 52
import com.spice.profitmandi.service.inventory.InventoryService;
27768 tejbeer 53
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
23779 amit.gupta 54
import com.spice.profitmandi.service.inventory.StockAllocationService;
55
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 56
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 57
import com.spice.profitmandi.thrift.clients.PaymentClient;
58
import com.spice.profitmandi.thrift.clients.TransactionClient;
59
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 60
import com.spice.profitmandi.web.model.LoginDetails;
61
import com.spice.profitmandi.web.util.CookiesProcessor;
62
import com.spice.profitmandi.web.util.MVCResponseSender;
23796 amit.gupta 63
import in.shop2020.logistics.PickUpType;
30017 amit.gupta 64
import in.shop2020.model.v1.order.*;
23796 amit.gupta 65
import in.shop2020.model.v1.user.ItemPriceQuantity;
66
import in.shop2020.model.v1.user.ShoppingCartException;
67
import in.shop2020.model.v1.user.UserContextService.Client;
68
import in.shop2020.payments.Attribute;
69
import in.shop2020.payments.PaymentException;
70
import in.shop2020.payments.PaymentStatus;
30017 amit.gupta 71
import org.apache.commons.io.output.ByteArrayOutputStream;
72
import org.apache.logging.log4j.LogManager;
73
import org.apache.logging.log4j.Logger;
74
import org.apache.thrift.TException;
75
import org.json.JSONArray;
76
import org.json.JSONObject;
77
import org.springframework.beans.factory.annotation.Autowired;
78
import org.springframework.core.io.ByteArrayResource;
79
import org.springframework.http.HttpHeaders;
80
import org.springframework.http.HttpStatus;
81
import org.springframework.http.ResponseEntity;
82
import org.springframework.mail.javamail.JavaMailSender;
83
import org.springframework.stereotype.Controller;
84
import org.springframework.transaction.annotation.Transactional;
85
import org.springframework.ui.Model;
86
import org.springframework.web.bind.annotation.RequestBody;
87
import org.springframework.web.bind.annotation.RequestMapping;
88
import org.springframework.web.bind.annotation.RequestMethod;
89
import org.springframework.web.bind.annotation.RequestParam;
23796 amit.gupta 90
 
30017 amit.gupta 91
import javax.servlet.http.HttpServletRequest;
92
import java.time.LocalDate;
93
import java.time.LocalDateTime;
94
import java.time.LocalTime;
95
import java.util.*;
96
import java.util.Map.Entry;
97
import java.util.function.Function;
98
import java.util.stream.Collectors;
99
 
23405 amit.gupta 100
@Controller
101
@Transactional(rollbackFor = Throwable.class)
102
public class IndentController {
103
 
23568 govind 104
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 105
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 106
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 107
 
24231 amit.gupta 108
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
109
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
110
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
111
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 112
 
26951 amit.gupta 113
	private static final int PLANNING_OPEN_DAY = 20;
114
	private static final int PLANNING_CLOSE_DAY = 1;
115
 
30017 amit.gupta 116
	private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";
117
 
25547 amit.gupta 118
	@Autowired
119
	WalletService walletService;
24231 amit.gupta 120
 
23405 amit.gupta 121
	@Autowired
30017 amit.gupta 122
	BrandRegionMappingRepository brandRegionMappingRepository;
123
 
124
	@Autowired
25721 tejbeer 125
	private JavaMailSender googleMailSender;
126
 
127
	@Autowired
23405 amit.gupta 128
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 129
 
23796 amit.gupta 130
	@Autowired
131
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 132
 
23779 amit.gupta 133
	@Autowired
23796 amit.gupta 134
	private UserRepository userRepository;
135
 
136
	@Autowired
23779 amit.gupta 137
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 138
 
139
	@Autowired
23796 amit.gupta 140
	private OrderRepository orderRepository;
141
 
142
	@Autowired
26846 tejbeer 143
	private UserAccountRepository userAccountRepository;
144
 
145
	@Autowired
23405 amit.gupta 146
	private ItemRepository itemRepository;
147
 
148
	@Autowired
23779 amit.gupta 149
	private StockAllocationService stockAllocationService;
150
 
151
	@Autowired
152
	private RetailerService retailerService;
23405 amit.gupta 153
 
154
	@Autowired
155
	private TagListingRepository tagListingRepository;
156
 
157
	@Autowired
158
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
159
 
160
	@Autowired
23796 amit.gupta 161
	private PurchaseRepository purchaseRepository;
162
 
163
	@Autowired
23405 amit.gupta 164
	private MVCResponseSender mvcResponseSender;
165
 
23785 amit.gupta 166
	@Autowired
25721 tejbeer 167
	private FocusedModelRepository focusedModelRepository;
168
 
169
	@Autowired
170
	private MonthlyPlannedRepository monthlyPlannedRepository;
171
 
172
	@Autowired
173
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 174
 
25721 tejbeer 175
	@Autowired
25732 tejbeer 176
	private FofoOrderItemRepository fofoOrderItemRepository;
177
 
178
	@Autowired
25721 tejbeer 179
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 180
 
25721 tejbeer 181
	@Autowired
23785 amit.gupta 182
	RoleManager roleManager;
23405 amit.gupta 183
 
25721 tejbeer 184
	@Autowired
27081 tejbeer 185
	PartnerTypeChangeRepository partnerTypeChangeRepository;
186
 
187
	@Autowired
25736 tejbeer 188
	private Mongo mongoClient;
189
 
190
	@Autowired
191
	private InventoryService inventoryService;
192
 
193
	@Autowired
26721 tejbeer 194
	private CsService csService;
25721 tejbeer 195
 
26721 tejbeer 196
	@Autowired
197
	private AuthRepository authRepository;
26846 tejbeer 198
	@Autowired
30017 amit.gupta 199
	WarehouseRepository warehouseRepository;
26846 tejbeer 200
	@Autowired
30017 amit.gupta 201
	private SuggestedPoRepository suggestedPoRepository;
26846 tejbeer 202
 
203
	@Autowired
204
	private NotificationService notificationService;
205
 
27088 tejbeer 206
	@Autowired
207
	private RegionRepository regionRepository;
208
 
209
	@Autowired
210
	private PartnerRegionRepository partnerRegionRepository;
211
 
27768 tejbeer 212
	@Autowired
213
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
214
 
215
	@Autowired
216
	private SaholicInventoryService saholicInventoryService;
217
 
30003 tejbeer 218
	@Autowired
219
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
30017 amit.gupta 220
	@Autowired
221
	private SuggestedPoDetailRepository suggestedPoDetailRepository;
30003 tejbeer 222
 
30664 amit.gupta 223
	@Autowired
224
	SaholicCISTableRepository saholicCISTableRepository;
225
 
23779 amit.gupta 226
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 227
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
30664 amit.gupta 228
								 @RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
27088 tejbeer 229
		if (fofoId == 0) {
230
 
231
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
232
			fofoId = loginDetails.getFofoId();
233
 
26990 tejbeer 234
		}
27088 tejbeer 235
 
26082 tejbeer 236
		LocalDate currentMonthDate = LocalDate.now();
237
		MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 238
 
26951 amit.gupta 239
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26082 tejbeer 240
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
26978 tejbeer 241
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
242
			LOGGER.info("monthlyPlanned" + monthlyPlanned);
243
			saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
26082 tejbeer 244
		}
245
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
246
		return "response";
247
	}
248
 
249
	private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
30664 amit.gupta 250
									int catalogId, int itemQty) {
25721 tejbeer 251
		if (monthlyPlanned == null) {
252
			monthlyPlanned = new MonthlyPlanned();
26082 tejbeer 253
			monthlyPlanned.setFofoId(fofoId);
254
			monthlyPlanned.setYearMonth(currentMonthDate);
25721 tejbeer 255
			monthlyPlannedRepository.persist(monthlyPlanned);
256
			PlannedDetail pd = new PlannedDetail();
257
			pd.setCatalogId(catalogId);
258
			pd.setPlannedId(monthlyPlanned.getId());
259
			pd.setQuantity(itemQty);
260
			pd.setUpdatedTimestamp(LocalDateTime.now());
261
			plannedDetailRepository.persist(pd);
262
 
23786 amit.gupta 263
		} else {
25721 tejbeer 264
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
265
					catalogId);
266
			if (plannedDetail == null) {
267
				plannedDetail = new PlannedDetail();
268
				plannedDetail.setCatalogId(catalogId);
269
				plannedDetail.setPlannedId(monthlyPlanned.getId());
270
				plannedDetail.setQuantity(itemQty);
271
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
272
				plannedDetailRepository.persist(plannedDetail);
273
			} else if (itemQty == 0) {
274
				plannedDetailRepository.delete(plannedDetail);
275
 
276
			} else {
277
				plannedDetail.setCatalogId(catalogId);
278
				plannedDetail.setQuantity(itemQty);
279
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
280
			}
281
 
23785 amit.gupta 282
		}
25721 tejbeer 283
 
284
	}
285
 
286
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
26748 tejbeer 287
	public String confirmOpenIndent(HttpServletRequest request,
30664 amit.gupta 288
									@RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
26748 tejbeer 289
 
290
		if (fofoId == 0) {
291
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
292
			fofoId = loginDetails.getFofoId();
293
		}
25721 tejbeer 294
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 295
 
26951 amit.gupta 296
		LocalDate currentDate = LocalDate.now();
297
		LocalDate planningMonthDate = null;
26082 tejbeer 298
		MonthlyPlanned monthlyPlanned = null;
26951 amit.gupta 299
		if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
300
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
301
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 302
 
26082 tejbeer 303
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
304
		}
305
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
306
 
307
		return "response";
308
	}
309
 
310
	private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
311
			throws Exception {
25721 tejbeer 312
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
313
 
314
		List<PlannedModel> plannedModel = new ArrayList<>();
315
		for (PlannedDetail plannedDetail : plannedDetails) {
316
 
317
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
318
			String itemDesription = items.get(0).getItemDescriptionNoColor();
319
			PlannedModel pm = new PlannedModel();
320
			pm.setItemDescription(itemDesription);
321
			pm.setStoreName(customRetailer.getBusinessName());
322
			pm.setQty(plannedDetail.getQuantity());
26082 tejbeer 323
			pm.setFofoId(fofoId);
25721 tejbeer 324
			plannedModel.add(pm);
325
			LOGGER.info("plannedModel" + plannedModel);
326
 
23785 amit.gupta 327
		}
26978 tejbeer 328
		List<String> ccemails = new ArrayList<>();
329
		LOGGER.info("ccemails" + ccemails);
330
		Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
331
		LOGGER.info("emailEsclationType" + emailEsclationType);
332
		ccemails.add(emailEsclationType.get(EscalationType.L1));
333
		ccemails.add(emailEsclationType.get(EscalationType.L2));
334
		LOGGER.info("ccemails" + ccemails);
335
		List<String> bccemails = new ArrayList<>();
336
		bccemails.add(emailEsclationType.get(EscalationType.L3));
337
		LOGGER.info("bccemails" + bccemails);
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);
30664 amit.gupta 344
		Utils.sendMailWithAttachments(googleMailSender, new String[]{customRetailer.getEmail()},
26978 tejbeer 345
				ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
25721 tejbeer 346
				"Planned Indent", "PFA",
30664 amit.gupta 347
				new Attachment[]{new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())),});
25721 tejbeer 348
 
23405 amit.gupta 349
	}
350
 
24231 amit.gupta 351
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
352
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
30664 amit.gupta 353
															@RequestParam(required = false, defaultValue = "0") int fofoId,
354
															@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 355
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
356
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 357
		LOGGER.info("Counter size is {}", counterSize);
358
		LOGGER.info("Fofo Id is {}", fofoId);
30426 tejbeer 359
 
25721 tejbeer 360
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 361
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
362
					.collect(Collectors.toList());
30426 tejbeer 363
			Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
364
			Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x))
365
					.filter(x -> x != null).collect(Collectors.toList()).stream()
366
					.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
24232 amit.gupta 367
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
368
					true);
369
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
370
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 371
 
24232 amit.gupta 372
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 373
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 374
				int retailerId = x.getFofoId();
375
				int catalogId;
376
				try {
377
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
378
					String key = catalogId + "-" + retailerId;
379
					if (!catalogUserQtyMap.containsKey(key)) {
380
						catalogUserQtyMap.put(key, 0);
381
					}
382
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
383
				} catch (ProfitMandiBusinessException e) {
384
					// TODO Auto-generated catch block
385
					throw new RuntimeException(e);
24231 amit.gupta 386
				}
387
			});
23779 amit.gupta 388
 
24231 amit.gupta 389
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 390
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
391
				try {
392
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
393
							+ x.getRetailerId();
394
				} catch (ProfitMandiBusinessException e) {
395
					// TODO Auto-generated catch block
396
					return "";
397
				}
398
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 399
 
24232 amit.gupta 400
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
401
 
402
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
403
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 404
			while (iterator.hasNext()) {
405
				TagListing tagListing = iterator.next();
406
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 407
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 408
				if (item.getCategoryId() != 10006) {
409
					continue;
410
				}
23779 amit.gupta 411
 
24232 amit.gupta 412
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
413
						? modelStockAllocationMap.get(catalogId)
414
						: 0;
415
				for (int retailerId : fofoIds) {
416
					String key = catalogId + "-" + retailerId;
417
					if (catalogListingMap.containsKey(key)) {
418
						continue;
24231 amit.gupta 419
					}
24232 amit.gupta 420
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
421
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
422
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
423
						continue;
424
					}
425
					CatalogListingModel catalogListingModel = new CatalogListingModel();
426
					catalogListingModel.setFofoId(retailerId);
427
					catalogListingModel.setModelName(item.getModelName());
428
					catalogListingModel.setModelNumber(item.getModelNumber());
429
					catalogListingModel.setCatalogId(catalogId);
430
					catalogListingModel.setDp(tagListing.getSellingPrice());
431
					catalogListingModel.setMop(tagListing.getMop());
432
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
433
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
434
					catalogListingModel.setInTransitQuantity(catalogInTransit);
435
					catalogListingModel
436
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 437
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 438
					catalogListingModel.setBrand(item.getBrand());
439
					catalogListingModel.setModelName(item.getModelName());
440
					catalogListingModel.setModelNumber(item.getModelNumber());
441
					catalogListingModel.setCategoryId(item.getCategoryId());
442
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 443
				}
444
			}
25853 amit.gupta 445
			List<List<?>> listOfRows = new ArrayList<>();
24231 amit.gupta 446
			for (CatalogListingModel clm : catalogListingMap.values()) {
30426 tejbeer 447
				CustomRetailer cr = crm.get(clm.getFofoId());
24349 amit.gupta 448
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
449
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
450
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
451
						clm.getToBeOrdered()));
24231 amit.gupta 452
			}
24349 amit.gupta 453
			ByteArrayOutputStream baos = FileUtil
454
					.getCSVByteStream(
455
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
456
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
457
							listOfRows);
24231 amit.gupta 458
			HttpHeaders headers = new HttpHeaders();
459
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
460
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 461
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
462
					HttpStatus.OK);
23405 amit.gupta 463
		}
24231 amit.gupta 464
		return null;
24232 amit.gupta 465
 
23405 amit.gupta 466
	}
467
 
24349 amit.gupta 468
	@RequestMapping(value = "/itemsByCatalogId")
469
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
30664 amit.gupta 470
									  @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 471
			throws ProfitMandiBusinessException {
24410 amit.gupta 472
		if (catalogId == 0) {
473
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
474
		}
24349 amit.gupta 475
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 476
		LOGGER.info("Items {}", items);
25378 tejbeer 477
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
478
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 479
		Map<Integer, TagListing> tagsMap = tagListingRepository
480
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 481
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 482
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 483
		JSONArray response = new JSONArray();
24413 amit.gupta 484
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 485
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
486
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 487
		});
488
		model.addAttribute("response", response.toString());
489
		return "response";
24410 amit.gupta 490
 
24349 amit.gupta 491
	}
492
 
28055 tejbeer 493
	@RequestMapping(value = "/hotdealsitemsByCatalogId")
494
	public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,
30664 amit.gupta 495
											  @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
28055 tejbeer 496
			throws ProfitMandiBusinessException {
497
		if (catalogId == 0) {
498
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
499
		}
500
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
501
		LOGGER.info("Items {}", items);
502
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
503
				.collect(Collectors.toMap(Item::getId, Item::getColor));
504
		Map<Integer, TagListing> tagsMap = tagListingRepository
505
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
506
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
507
		LOGGER.info("Items color map {}", itemsColorMap);
508
		JSONArray response = new JSONArray();
509
		itemsColorMap.keySet().stream().forEach(x -> {
510
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",
511
					tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));
512
		});
513
		model.addAttribute("response", response.toString());
514
		return "response";
515
 
516
	}
517
 
30664 amit.gupta 518
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
519
		int orderRemovedCount = 0;
520
		Iterator<Order> orderIterator = lastOrdersList.iterator();
521
		while (orderIterator.hasNext()) {
522
			Order o = orderIterator.next();
523
			if (o.getInvoiceNumber() != null) {
524
				try {
525
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
526
					orderIterator.remove();
527
					orderRemovedCount++;
528
				} catch (Exception e) {
529
 
530
				}
531
			}
532
		}
533
		LOGGER.info("Order removed count is {}", orderRemovedCount);
534
		return lastOrdersList;
535
	}
536
 
30668 amit.gupta 537
	//Clean up the saholic cis table
30664 amit.gupta 538
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
30668 amit.gupta 539
	public String updateTagListing(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
30664 amit.gupta 540
			throws Exception {
541
		JSONArray jsonArray = new JSONArray(jsonArrayString);
542
		for (int i = 0; i < jsonArray.length(); i++) {
543
			JSONObject obj = jsonArray.getJSONObject(i);
544
 
545
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
546
			if (tl == null) {
547
				continue;
548
			} else {
549
				tl.setActive(obj.getBoolean("active"));
30668 amit.gupta 550
				if (!tl.isActive()) {
551
					saholicCISTableRepository.selectAllByItemId(tl.getItemId()).stream().forEach(x -> saholicCISTableRepository.delete(x));
552
				}
30664 amit.gupta 553
			}
554
		}
555
		model.addAttribute("response", true);
556
		return "response";
557
	}
558
 
559
	@RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)
560
	public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
561
			throws Exception {
562
		JSONArray jsonArray = new JSONArray(jsonArrayString);
563
		for (int i = 0; i < jsonArray.length(); i++) {
564
			JSONObject obj = jsonArray.getJSONObject(i);
565
 
566
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
567
			if (tl == null) {
568
				continue;
569
			} else {
570
				tl.setHotDeals(obj.getBoolean("hotDeals"));
571
				tagListingRepository.persist(tl);
572
			}
573
		}
574
		model.addAttribute("response", true);
575
		return "response";
576
	}
577
 
578
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
579
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
580
		boolean success = false;
581
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
582
		int fofoId = loginDetails.getFofoId();
583
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
584
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
585
		Client userClient = new UserClient().getClient();
586
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
587
 
588
		if (totalAmount > 0) {
589
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
590
			User user = userRepository.selectById(loginDetails.getFofoId());
591
			userClient = new UserClient().getClient();
592
			LOGGER.info("Setting wallet amount in cart");
593
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
594
					7890, OrderSource.WEBSITE.getValue(), true);
595
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
596
			createPayment(user, totalAmount, transactionId);
597
			TransactionService.Client transactionClient = new TransactionClient().getClient();
598
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
599
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
600
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
601
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
602
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
603
			transactionClient = new TransactionClient().getClient();
604
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
605
			try {
606
				transactionClient.enqueueTransactionInfoEmail(transactionId);
607
			} catch (Exception e1) {
608
				e1.printStackTrace();
609
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
610
			}
611
			resetCart(transactionClient.getTransaction(transactionId));
612
		}
613
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
614
		return "response";
615
	}
616
 
617
	private void createPayment(User user, double totalAmount, long transactionId)
618
			throws NumberFormatException, PaymentException, TException {
619
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
620
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
621
		paymentAttributes.add(new Attribute("payMethod", "7890"));
622
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
623
				false);
624
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
625
				PaymentStatus.SUCCESS, null, paymentAttributes);
626
	}
627
 
23405 amit.gupta 628
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 629
	public String loadOpenIndent(HttpServletRequest request, Model model,
30664 amit.gupta 630
								 @RequestParam(required = false, defaultValue = "0") int fofoId,
631
								 @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 632
 
633
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
634
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 635
		LOGGER.info("Counter size is {}", counterSize);
636
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 637
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 638
 
25797 tejbeer 639
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
640
				.collect(Collectors.toList());
641
 
25796 tejbeer 642
		Map<String, Object> equalsMap = new HashMap<>();
643
		equalsMap.put("categoryId", 10006);
25797 tejbeer 644
		equalsMap.put("brand", brands);
25796 tejbeer 645
		Map<String, List<?>> notEqualsMap = new HashMap<>();
646
 
647
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
648
		Map<Integer, Integer> currentStockMap;
649
 
25721 tejbeer 650
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 651
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 652
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
653
			equalsStockJoinMap.put("fofoId", fofoId);
654
			currentStockMap = itemRepository
25800 tejbeer 655
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
656
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 657
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 658
			LOGGER.info("currentStock");
23786 amit.gupta 659
		} else {
660
			if (fofoId == 0) {
25796 tejbeer 661
 
662
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
663
				equalsStockJoinMap.put("fofoId", fofoId);
664
 
665
				currentStockMap = itemRepository
25800 tejbeer 666
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 667
								equalsStockJoinMap, notEqualsJoinMap, "availability")
668
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
669
 
23779 amit.gupta 670
			} else {
25796 tejbeer 671
 
672
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
673
				equalsStockJoinMap.put("fofoId", fofoId);
674
 
675
				currentStockMap = itemRepository
25800 tejbeer 676
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 677
								equalsStockJoinMap, notEqualsJoinMap, "availability")
678
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
679
 
23405 amit.gupta 680
			}
23786 amit.gupta 681
		}
25796 tejbeer 682
 
683
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 684
 
23796 amit.gupta 685
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 686
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 687
		if (!isAdmin) {
23786 amit.gupta 688
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 689
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
690
					OrderRepository.validOrderStatusList);
23796 amit.gupta 691
			inTransitOrders = this.filterValidOrders(inTransitOrders);
692
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
693
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
694
		} else {
695
			itemsInTransit = new HashMap<>();
23786 amit.gupta 696
		}
25797 tejbeer 697
 
23796 amit.gupta 698
		int totalPcs = 0;
25797 tejbeer 699
 
23796 amit.gupta 700
		float totalAmount = 0;
24231 amit.gupta 701
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
27088 tejbeer 702
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
703
				.collect(Collectors.toList());
25796 tejbeer 704
 
27088 tejbeer 705
		LOGGER.info("regionIds" + regionIds);
706
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
707
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
708
		LOGGER.info("focusedModelMap" + focusedModelMap);
26956 amit.gupta 709
		LocalDate planningMonthDate = null;
26082 tejbeer 710
		MonthlyPlanned monthlyPlanned = null;
26176 tejbeer 711
		List<Integer> fofoOrderIds = null;
26082 tejbeer 712
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 713
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26956 amit.gupta 714
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
715
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 716
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
26176 tejbeer 717
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 718
							LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
26176 tejbeer 719
					.collect(Collectors.toList());
26082 tejbeer 720
 
721
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 722
		} else {
26956 amit.gupta 723
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 724
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 725
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
726
			model.addAttribute("planningMonth", planningMonthDate.getMonth());
26176 tejbeer 727
			model.addAttribute("mtd", true);
26131 tejbeer 728
			model.addAttribute("freezed", true);
26176 tejbeer 729
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 730
							curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
26176 tejbeer 731
					.collect(Collectors.toList());
26082 tejbeer 732
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
26978 tejbeer 733
		}
26082 tejbeer 734
 
25721 tejbeer 735
		Map<Integer, Integer> plannedDetailMap = null;
736
		if (monthlyPlanned != null) {
737
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
738
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
739
 
740
		}
25797 tejbeer 741
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 742
 
25796 tejbeer 743
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
744
		Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 745
 
25796 tejbeer 746
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 747
		Map<Integer, Integer> last15daysMap = null;
26748 tejbeer 748
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 749
 
26618 tejbeer 750
			last15daysMap = itemRepository
751
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
752
							notEqualsJoinMap, "quantity")
753
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
754
		}
25796 tejbeer 755
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 756
 
25796 tejbeer 757
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
758
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
759
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
760
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
761
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 762
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 763
 
25796 tejbeer 764
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 765
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 766
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
25800 tejbeer 767
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 768
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 769
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
25796 tejbeer 770
			int catalogId = catalogIdAggregateValue.getCatalogId();
771
			Item item = catalogIdItemMap.get(catalogId).get(0);
772
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 773
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
774
			if (!catalogListingMap.containsKey(catalogId)) {
775
				catalogListingModel = new CatalogListingModel();
776
				catalogListingModel.setCatalogId(catalogId);
777
				catalogListingModel.setDp(tagListing.getSellingPrice());
778
				catalogListingModel.setMop(tagListing.getMop());
779
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 780
				if (plannedDetailMap != null) {
781
 
782
					Integer quantity = plannedDetailMap.get(catalogId);
783
					if (quantity != null) {
784
						catalogListingModel.setAllocatedQuantity(quantity);
785
					}
786
				}
787
 
25796 tejbeer 788
				if (last15daysMap != null) {
789
					Integer last15DaysSale = last15daysMap.get(catalogId);
790
 
25721 tejbeer 791
					if (last15DaysSale != null) {
792
						catalogListingModel.setLast15DaysSale(last15DaysSale);
793
					} else {
794
						catalogListingModel.setLast15DaysSale(0);
795
					}
796
				} else {
797
					catalogListingModel.setLast15DaysSale(0);
798
				}
799
 
24231 amit.gupta 800
				catalogListingModel.setBrand(item.getBrand());
801
				if (item.getCategoryId() == 10006) {
802
					catalogListingModel.setCategoryId(item.getCategoryId());
803
				}
25721 tejbeer 804
 
805
				FocusedModel fm = focusedModelMap.get(catalogId);
806
				if (fm != null) {
807
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
808
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
809
 
810
				} else {
811
					catalogListingModel.setRecommendedQty(0);
812
					catalogListingModel.setMinimumQty(0);
813
				}
814
 
24231 amit.gupta 815
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 816
 
24231 amit.gupta 817
			}
25736 tejbeer 818
			int itemAvailability = 0;
25796 tejbeer 819
			if (currentStockMap != null) {
820
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 821
				itemAvailability = qty == null ? 0 : qty;
822
				catalogListingModel.setStockInHand(itemAvailability);
823
			} else {
824
				catalogListingModel.setStockInHand(0);
825
			}
24231 amit.gupta 826
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
827
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
828
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 829
			if (plannedDetailMap != null) {
26177 tejbeer 830
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 831
 
26177 tejbeer 832
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
833
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
834
					LOGGER.info("remaning" + remaining);
26176 tejbeer 835
 
26177 tejbeer 836
					if (remaining != 0) {
837
						catalogListingModel.setRemaining(remaining);
838
					} else {
839
						catalogListingModel.setRemaining(0);
840
					}
26176 tejbeer 841
				}
842
			}
23786 amit.gupta 843
		}
25721 tejbeer 844
 
26963 amit.gupta 845
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
23786 amit.gupta 846
		if (fofoId > 0) {
847
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
848
			model.addAttribute("retailerName",
849
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
850
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
851
			model.addAttribute("retailerId", customRetailer.getPartnerId());
852
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 853
		} else {
23786 amit.gupta 854
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 855
		}
23786 amit.gupta 856
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 857
 
858
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
859
 
25721 tejbeer 860
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 861
				Comparator.reverseOrder());
25721 tejbeer 862
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 863
		model.addAttribute("catalogTagListings",
864
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 865
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 866
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26956 amit.gupta 867
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
868
		model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 869
 
23786 amit.gupta 870
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 871
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 872
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 873
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 874
		return "open-indent";
25796 tejbeer 875
 
23405 amit.gupta 876
	}
23796 amit.gupta 877
 
30664 amit.gupta 878
	private long resetCart(Transaction transaction) {
879
		long sum = 0;
880
		Map<Long, Double> items = new HashMap<Long, Double>();
881
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
882
			sum += order.getGvAmount();
883
			for (LineItem lineitem : order.getLineitems()) {
884
				Long itemId = lineitem.getItem_id();
885
				Double quantity = items.get(itemId);
886
				if (quantity == null) {
887
					quantity = lineitem.getQuantity();
888
				} else {
889
					quantity = quantity + lineitem.getQuantity();
30017 amit.gupta 890
				}
30664 amit.gupta 891
				items.put(itemId, quantity);
30017 amit.gupta 892
			}
893
		}
894
 
30664 amit.gupta 895
		LOGGER.debug("Items to reset in cart are: " + items);
30017 amit.gupta 896
 
30664 amit.gupta 897
		try {
898
			Client userClient = new UserClient().getClient();
899
			userClient.resetCart(transaction.getShoppingCartid(), items);
900
		} catch (TException e) {
901
			LOGGER.error("Error while updating information in payment database.", e);
902
		} catch (ShoppingCartException e) {
903
			LOGGER.error("Error while reseting the cart in cart database.", e);
904
		} catch (Exception e) {
905
			LOGGER.error("Unexpected exception", e);
30017 amit.gupta 906
		}
30664 amit.gupta 907
		return sum;
30017 amit.gupta 908
	}
909
 
30664 amit.gupta 910
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
911
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
912
		/*
913
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
914
		 * currentInventorySnapshots = currentInventorySnapshotRepository
915
		 * .selectItemsStock(fofoId); itemCisMap =
916
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
917
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
918
		 * List<StockAllocationModel> stockAllocationList =
919
		 * stockAllocationService.getStockAllocation(fofoId, true);
920
		 *
921
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
922
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
923
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
924
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
925
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
926
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
927
		 * validOrderStatusList); inTransitOrders =
928
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
929
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
930
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
931
		 * x.getLineItem().getQuantity())));
932
		 *
933
		 * Iterator<TagListing> iterator = tagListings.iterator();
934
		 *
935
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
936
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
937
		 * tagListing.getAllocatedQuantity()); if
938
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
939
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
940
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
941
		 * itemCisMap.get(tagListing.getItemId());
942
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
943
		 * itemIdAvailability.getAvailability()); StockAllocationModel
944
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
945
		 *
946
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
947
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
948
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
949
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
950
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
951
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
952
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
953
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
954
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
955
		 */
956
		return itemQuantities;
30017 amit.gupta 957
 
958
	}
959
 
26131 tejbeer 960
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
961
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
30664 amit.gupta 962
											  @RequestParam(required = false, defaultValue = "0") int fofoId,
963
											  @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26956 amit.gupta 964
		LocalDate planMonthStart = null;
965
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
966
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
967
		} else {
968
			planMonthStart = LocalDate.now().withDayOfMonth(1);
969
		}
26131 tejbeer 970
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
971
		Set<Integer> roleIds = loginDetails.getRoleIds();
972
		LOGGER.info("Counter size is {}", counterSize);
973
		LOGGER.info("Fofo Id is {}", fofoId);
974
		boolean isAdmin = roleManager.isAdmin(roleIds);
975
 
976
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
977
				.collect(Collectors.toList());
978
 
979
		Map<String, Object> equalsMap = new HashMap<>();
980
		equalsMap.put("categoryId", 10006);
981
		equalsMap.put("brand", brands);
982
		Map<String, List<?>> notEqualsMap = new HashMap<>();
983
 
984
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
985
		Map<Integer, Integer> currentStockMap;
986
 
987
		if (!isAdmin && fofoId == 0) {
988
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
989
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
990
			equalsStockJoinMap.put("fofoId", fofoId);
991
			currentStockMap = itemRepository
992
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
993
							equalsStockJoinMap, notEqualsJoinMap, "availability")
994
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
995
			LOGGER.info("currentStock");
996
		} else {
997
			if (fofoId == 0) {
998
 
999
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1000
				equalsStockJoinMap.put("fofoId", fofoId);
1001
 
1002
				currentStockMap = itemRepository
1003
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1004
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1005
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1006
 
1007
			} else {
1008
 
1009
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1010
				equalsStockJoinMap.put("fofoId", fofoId);
1011
 
1012
				currentStockMap = itemRepository
1013
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1014
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1015
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1016
 
1017
			}
1018
		}
1019
 
1020
		LOGGER.info("currentStock" + currentStockMap);
1021
 
1022
		Map<Integer, Integer> itemsInTransit = null;
1023
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1024
		if (!isAdmin) {
1025
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 1026
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1027
					OrderRepository.validOrderStatusList);
26131 tejbeer 1028
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1029
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1030
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1031
		} else {
1032
			itemsInTransit = new HashMap<>();
1033
		}
1034
 
1035
		int totalPcs = 0;
1036
 
1037
		float totalAmount = 0;
1038
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1039
 
27088 tejbeer 1040
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1041
				.collect(Collectors.toList());
26131 tejbeer 1042
 
27088 tejbeer 1043
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1044
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1045
 
26978 tejbeer 1046
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
1047
				planMonthStart.minusMonths(1));
26956 amit.gupta 1048
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
1049
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
1050
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 1051
 
1052
		Map<Integer, Integer> plannedDetailMap = null;
1053
		if (monthlyPlanned != null) {
1054
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1055
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1056
 
1057
		}
1058
 
1059
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1060
		List<Integer> fofoOrderIds = fofoOrderRepository
1061
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26978 tejbeer 1062
						planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
26131 tejbeer 1063
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 1064
 
26131 tejbeer 1065
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1066
		Map<String, Object> equalsJoinMap = new HashMap<>();
1067
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 1068
		Map<Integer, Integer> lastMonthSaleMap = null;
1069
		if (!fofoOrderIds.isEmpty()) {
1070
			lastMonthSaleMap = itemRepository
1071
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1072
							notEqualsJoinMap, "quantity")
1073
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1074
		}
26131 tejbeer 1075
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
1076
 
1077
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1078
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1079
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1080
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1081
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1082
		LOGGER.info("catalogIdItemMap");
1083
 
1084
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1085
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 1086
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26131 tejbeer 1087
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1088
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 1089
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26131 tejbeer 1090
			int catalogId = catalogIdAggregateValue.getCatalogId();
1091
			Item item = catalogIdItemMap.get(catalogId).get(0);
1092
			TagListing tagListing = taglistingMap.get(item.getId());
1093
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1094
			if (!catalogListingMap.containsKey(catalogId)) {
1095
				catalogListingModel = new CatalogListingModel();
1096
				catalogListingModel.setCatalogId(catalogId);
1097
				catalogListingModel.setDp(tagListing.getSellingPrice());
1098
				catalogListingModel.setMop(tagListing.getMop());
1099
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1100
				if (plannedDetailMap != null) {
1101
 
1102
					Integer quantity = plannedDetailMap.get(catalogId);
1103
					if (quantity != null) {
1104
						catalogListingModel.setAllocatedQuantity(quantity);
1105
					}
1106
				}
1107
 
1108
				if (lastMonthSaleMap != null) {
1109
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
1110
 
1111
					if (lastMonthSale != null) {
1112
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
1113
					} else {
1114
						catalogListingModel.setLastMonthSaleMap(0);
1115
					}
1116
				} else {
1117
					catalogListingModel.setLast15DaysSale(0);
1118
				}
1119
 
1120
				catalogListingModel.setBrand(item.getBrand());
1121
				if (item.getCategoryId() == 10006) {
1122
					catalogListingModel.setCategoryId(item.getCategoryId());
1123
				}
1124
 
1125
				FocusedModel fm = focusedModelMap.get(catalogId);
1126
				if (fm != null) {
1127
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1128
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1129
 
1130
				} else {
1131
					catalogListingModel.setRecommendedQty(0);
1132
					catalogListingModel.setMinimumQty(0);
1133
				}
1134
 
1135
				catalogListingMap.put(catalogId, catalogListingModel);
1136
 
1137
			}
1138
			int itemAvailability = 0;
1139
			if (currentStockMap != null) {
1140
				Integer qty = currentStockMap.get(catalogId);
1141
				itemAvailability = qty == null ? 0 : qty;
1142
				catalogListingModel.setStockInHand(itemAvailability);
1143
			} else {
1144
				catalogListingModel.setStockInHand(0);
1145
			}
1146
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1147
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1148
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1149
 
1150
		}
1151
 
26963 amit.gupta 1152
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 1153
		if (fofoId > 0) {
1154
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1155
			model.addAttribute("retailerName",
1156
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1157
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1158
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1159
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1160
		} else {
1161
			model.addAttribute("counterSize", counterSize.toString());
1162
		}
1163
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1164
 
1165
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1166
 
1167
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1168
				Comparator.reverseOrder());
1169
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1170
		model.addAttribute("catalogTagListings",
1171
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1172
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1173
		model.addAttribute("previousMonth", true);
1174
		model.addAttribute("freezed", true);
26177 tejbeer 1175
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 1176
		model.addAttribute("customRetailers", customRetailers);
1177
		model.addAttribute("totalAmount", totalAmount);
1178
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1179
		model.addAttribute("totalPcs", totalPcs);
1180
		return "open-indent";
1181
 
1182
	}
1183
 
30664 amit.gupta 1184
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1185
		Map<Integer, Item> itemMap = new HashMap<>();
1186
		for (FocusedModel focusedModel : focusedModels) {
1187
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1188
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
23796 amit.gupta 1189
		}
1190
 
30664 amit.gupta 1191
		return itemMap;
1192
	}
25378 tejbeer 1193
 
30664 amit.gupta 1194
	private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1195
		Map<Integer, Region> regionMap = new HashMap<>();
1196
		for (FocusedModel focusedModel : focusedModels) {
1197
			Region region = regionRepository.selectById(focusedModel.getRegionId());
1198
			regionMap.put(region.getId(), region);
24406 amit.gupta 1199
		}
24231 amit.gupta 1200
 
30664 amit.gupta 1201
		return regionMap;
23796 amit.gupta 1202
	}
24231 amit.gupta 1203
 
25721 tejbeer 1204
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1205
	public String getFocusedModel(HttpServletRequest request,
30664 amit.gupta 1206
								  @RequestParam(name = "offset", defaultValue = "0") int offset,
1207
								  @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
25721 tejbeer 1208
			throws ProfitMandiBusinessException {
25736 tejbeer 1209
 
1210
		long size = 0;
25721 tejbeer 1211
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
27081 tejbeer 1212
 
25736 tejbeer 1213
		size = focusedModelRepository.selectAllCount();
1214
		if (!focusedModels.isEmpty()) {
1215
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1216
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1217
 
27088 tejbeer 1218
			LOGGER.info("regionMap" + regionMap);
25736 tejbeer 1219
			model.addAttribute("focusedModels", focusedModels);
1220
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1221
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1222
			model.addAttribute("start", offset + 1);
1223
			model.addAttribute("size", size);
1224
			model.addAttribute("url", "/getPaginatedFocusedModel");
1225
 
1226
			if (focusedModels.size() < limit) {
1227
				model.addAttribute("end", offset + focusedModels.size());
1228
			} else {
1229
				model.addAttribute("end", offset + limit);
1230
			}
1231
		} else {
1232
 
1233
			model.addAttribute("walletRequest", focusedModels);
1234
			model.addAttribute("size", size);
1235
 
1236
		}
1237
 
27088 tejbeer 1238
		List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1239
 
27088 tejbeer 1240
		model.addAttribute("regions", regions);
1241
 
25721 tejbeer 1242
		return "focused_model";
1243
	}
1244
 
25736 tejbeer 1245
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1246
	public String getPaginatedFocusedModel(HttpServletRequest request,
30664 amit.gupta 1247
										   @RequestParam(name = "offset", defaultValue = "0") int offset,
1248
										   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
25736 tejbeer 1249
			throws ProfitMandiBusinessException {
1250
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1251
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1252
 
1253
		if (!focusedModels.isEmpty()) {
1254
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1255
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25736 tejbeer 1256
			model.addAttribute("focusedModels", focusedModels);
1257
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1258
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1259
			model.addAttribute("url", "/getPaginatedFocusedModel");
1260
		} else {
1261
			model.addAttribute("focusedModels", focusedModels);
1262
 
1263
		}
27081 tejbeer 1264
 
27088 tejbeer 1265
		List<Region> regions = regionRepository.selectAll();
1266
 
1267
		model.addAttribute("regions", regions);
25736 tejbeer 1268
		return "focused-model-paginated";
1269
	}
1270
 
25798 tejbeer 1271
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1272
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1273
 
25798 tejbeer 1274
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1275
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1276
 
1277
		mobileBrands.stream().forEach(x -> {
1278
			String brand = (String) x.get("name");
1279
			if (brandStockPricesMap.containsKey(brand)) {
1280
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1281
				brandStockPrice.setBrandUrl((String) x.get("url"));
1282
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1283
				brandStockPrices.add(brandStockPrice);
1284
			}
1285
		});
1286
 
1287
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1288
				.collect(Collectors.toList());
1289
	}
1290
 
26721 tejbeer 1291
	@RequestMapping(value = "/getPartnerAllocation")
1292
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1293
 
1294
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1295
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1296
 
1297
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1298
 
1299
		List<Integer> fofoIds = pp.get(authUser.getId());
1300
 
30426 tejbeer 1301
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1302
		Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1303
				.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26721 tejbeer 1304
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1305
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1306
 
30426 tejbeer 1307
		model.addAttribute("customRetailersMap", crm);
26721 tejbeer 1308
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1309
		return "partners_allocation";
1310
 
1311
	}
1312
 
26846 tejbeer 1313
	@RequestMapping(value = "/partnerPendingOrder")
1314
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1315
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1316
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1317
 
1318
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1319
 
1320
		List<Integer> fofoIds = pp.get(authUser.getId());
30426 tejbeer 1321
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1322
		Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1323
				.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26846 tejbeer 1324
 
30426 tejbeer 1325
		model.addAttribute("customRetailersMap", crm);
26846 tejbeer 1326
 
1327
		return "partner-po";
1328
 
1329
	}
1330
 
30664 amit.gupta 1331
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1332
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,
1333
							   @RequestParam(name = "recommended", defaultValue = "0") int recommended,
1334
							   @RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,
1335
							   @RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,
1336
							   @RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,
1337
							   Model model) throws ProfitMandiBusinessException {
1338
 
1339
		FocusedModel fm = new FocusedModel();
1340
		fm.setCatalogId(catalogId);
1341
		fm.setMinimumQty(minimumQty);
1342
		fm.setRecommendedQty(recommended);
1343
		fm.setRegionId(regionId);
1344
		fm.setObsRecommendedQty(obvrecommend);
1345
		fm.setObsMinimumQty(obvminimum);
1346
		fm.setCreatedTimestamp(LocalDateTime.now());
1347
		focusedModelRepository.persist(fm);
1348
		return "focused_model";
1349
	}
1350
 
30017 amit.gupta 1351
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1352
	public String removeFocusedModelItem(HttpServletRequest request,
30664 amit.gupta 1353
										 @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
30017 amit.gupta 1354
 
1355
		focusedModelRepository.deleteById(id);
1356
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1357
		return "response";
1358
	}
1359
 
26846 tejbeer 1360
	@RequestMapping(value = "/getPartnerloadContent")
1361
	public String getPartnerloadContent(HttpServletRequest request, Model model,
30664 amit.gupta 1362
										@RequestParam(required = false, defaultValue = "0") int fofoId,
1363
										@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26846 tejbeer 1364
 
1365
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1366
		Set<Integer> roleIds = loginDetails.getRoleIds();
1367
		LOGGER.info("Counter size is {}", counterSize);
1368
		LOGGER.info("Fofo Id is {}", fofoId);
1369
		boolean isAdmin = roleManager.isAdmin(roleIds);
1370
 
1371
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1372
				.collect(Collectors.toList());
1373
 
1374
		Map<String, Object> equalsMap = new HashMap<>();
1375
		equalsMap.put("categoryId", 10006);
1376
		equalsMap.put("brand", brands);
1377
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1378
 
1379
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1380
		Map<Integer, Integer> currentStockMap;
1381
 
1382
		if (!isAdmin && fofoId == 0) {
1383
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1384
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1385
			equalsStockJoinMap.put("fofoId", fofoId);
1386
			currentStockMap = itemRepository
1387
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1388
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1389
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1390
			LOGGER.info("currentStock");
1391
		} else {
1392
			if (fofoId == 0) {
1393
 
1394
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1395
				equalsStockJoinMap.put("fofoId", fofoId);
1396
 
1397
				currentStockMap = itemRepository
1398
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1399
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1400
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1401
 
1402
			} else {
1403
 
1404
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1405
				equalsStockJoinMap.put("fofoId", fofoId);
1406
 
1407
				currentStockMap = itemRepository
1408
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1409
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1410
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1411
 
1412
			}
1413
		}
1414
 
27768 tejbeer 1415
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
26846 tejbeer 1416
		LOGGER.info("currentStock" + currentStockMap);
1417
 
1418
		Map<Integer, Integer> itemsInTransit = null;
1419
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1420
		if (!isAdmin) {
1421
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 1422
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1423
					OrderRepository.validOrderStatusList);
26846 tejbeer 1424
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1425
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1426
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1427
		} else {
1428
			itemsInTransit = new HashMap<>();
1429
		}
1430
 
1431
		int totalPcs = 0;
1432
 
1433
		float totalAmount = 0;
1434
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1435
 
27088 tejbeer 1436
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1437
				.collect(Collectors.toList());
26846 tejbeer 1438
 
27088 tejbeer 1439
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1440
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1441
 
26846 tejbeer 1442
		LocalDate currentMonthDate = LocalDate.now();
1443
		MonthlyPlanned monthlyPlanned = null;
1444
		List<Integer> fofoOrderIds = null;
1445
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1446
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1447
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1448
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1449
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1450
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 1451
							LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
26846 tejbeer 1452
					.collect(Collectors.toList());
1453
 
1454
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1455
		} else {
26846 tejbeer 1456
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1457
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1458
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1459
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1460
			model.addAttribute("mtd", true);
1461
			model.addAttribute("freezed", true);
1462
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 1463
							curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
26846 tejbeer 1464
					.collect(Collectors.toList());
1465
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1466
		}
1467
 
1468
		Map<Integer, Integer> plannedDetailMap = null;
1469
		if (monthlyPlanned != null) {
1470
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1471
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1472
 
1473
		}
1474
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1475
 
1476
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1477
		Map<String, Object> equalsJoinMap = new HashMap<>();
1478
 
1479
		equalsJoinMap.put("orderId", fofoOrderIds);
1480
		Map<Integer, Integer> last15daysMap = null;
1481
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1482
 
1483
			last15daysMap = itemRepository
1484
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1485
							notEqualsJoinMap, "quantity")
1486
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1487
		}
1488
		LOGGER.info("last15daysMap" + last15daysMap);
1489
 
1490
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1491
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1492
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1493
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1494
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1495
		LOGGER.info("catalogIdItemMap");
1496
 
1497
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1498
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 1499
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26846 tejbeer 1500
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
27768 tejbeer 1501
		Map<Integer, Integer> ourStockAvailability = new HashMap<>();
1502
 
1503
		Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1504
				.selectAllByCatalogIds(new HashSet<>(
1505
						tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1506
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1507
						Collectors.mapping(y -> y.getId(), Collectors.toList())));
1508
		for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1509
			List<Integer> itemIds = catalogItem.getValue();
1510
			int availability = 0;
1511
			for (Integer itemId : itemIds) {
30664 amit.gupta 1512
				List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId, fofoStore.getWarehouseId());
1513
				if (saholicCISTableList != null) {
1514
					availability += saholicCISTableList.stream().collect(Collectors.summingInt(x -> x.getAvailability()));
27768 tejbeer 1515
				}
1516
			}
1517
			Integer catalogItemId = catalogItem.getKey();
1518
			ourStockAvailability.put(catalogItemId, availability);
1519
		}
1520
		LOGGER.info("ourStockAvailability" + ourStockAvailability);
1521
 
28897 amit.gupta 1522
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26846 tejbeer 1523
			int catalogId = catalogIdAggregateValue.getCatalogId();
1524
			Item item = catalogIdItemMap.get(catalogId).get(0);
1525
			TagListing tagListing = taglistingMap.get(item.getId());
1526
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1527
			if (!catalogListingMap.containsKey(catalogId)) {
1528
				catalogListingModel = new CatalogListingModel();
1529
				catalogListingModel.setCatalogId(catalogId);
1530
				catalogListingModel.setDp(tagListing.getSellingPrice());
1531
				catalogListingModel.setMop(tagListing.getMop());
1532
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1533
				if (plannedDetailMap != null) {
1534
 
1535
					Integer quantity = plannedDetailMap.get(catalogId);
1536
					if (quantity != null) {
1537
						catalogListingModel.setAllocatedQuantity(quantity);
1538
					}
1539
				}
1540
 
1541
				if (last15daysMap != null) {
1542
					Integer last15DaysSale = last15daysMap.get(catalogId);
1543
 
1544
					if (last15DaysSale != null) {
1545
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1546
					} else {
1547
						catalogListingModel.setLast15DaysSale(0);
1548
					}
1549
				} else {
1550
					catalogListingModel.setLast15DaysSale(0);
1551
				}
1552
 
1553
				catalogListingModel.setBrand(item.getBrand());
1554
				if (item.getCategoryId() == 10006) {
1555
					catalogListingModel.setCategoryId(item.getCategoryId());
1556
				}
1557
 
27768 tejbeer 1558
				Integer ourStock = ourStockAvailability.get(catalogId);
1559
				LOGGER.info("catalogId" + catalogId);
1560
 
1561
				LOGGER.info("ourStock" + ourStock);
1562
				if (ourStock != null) {
1563
					catalogListingModel.setOurStockQty(ourStock);
1564
				}
1565
 
26846 tejbeer 1566
				FocusedModel fm = focusedModelMap.get(catalogId);
1567
				if (fm != null) {
1568
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1569
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
29667 tejbeer 1570
					catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());
1571
					catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());
26846 tejbeer 1572
 
1573
				} else {
1574
					catalogListingModel.setRecommendedQty(0);
1575
					catalogListingModel.setMinimumQty(0);
29667 tejbeer 1576
 
1577
					catalogListingModel.setObsRecommendedQty(0);
1578
					catalogListingModel.setObsMinimumQty(0);
1579
 
26846 tejbeer 1580
				}
1581
 
1582
				catalogListingMap.put(catalogId, catalogListingModel);
1583
 
1584
			}
1585
			int itemAvailability = 0;
1586
			if (currentStockMap != null) {
1587
				Integer qty = currentStockMap.get(catalogId);
1588
				itemAvailability = qty == null ? 0 : qty;
1589
				catalogListingModel.setStockInHand(itemAvailability);
1590
			} else {
1591
				catalogListingModel.setStockInHand(0);
1592
			}
1593
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1594
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1595
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1596
			if (plannedDetailMap != null) {
1597
				if (plannedDetailMap.get(catalogId) != null) {
1598
 
1599
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1600
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1601
					LOGGER.info("remaning" + remaining);
1602
 
1603
					if (remaining != 0) {
1604
						catalogListingModel.setRemaining(remaining);
1605
					} else {
1606
						catalogListingModel.setRemaining(0);
1607
					}
1608
				}
1609
			}
1610
		}
1611
 
26963 amit.gupta 1612
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1613
		if (fofoId > 0) {
1614
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1615
			model.addAttribute("retailerName",
1616
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1617
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1618
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1619
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1620
		} else {
1621
			model.addAttribute("counterSize", counterSize.toString());
1622
		}
1623
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1624
 
1625
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1626
 
1627
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1628
				Comparator.reverseOrder());
1629
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1630
		model.addAttribute("catalogTagListings",
1631
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1632
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
27768 tejbeer 1633
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26846 tejbeer 1634
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1635
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1636
 
1637
		model.addAttribute("customRetailers", customRetailers);
1638
		model.addAttribute("totalAmount", totalAmount);
1639
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1640
		model.addAttribute("totalPcs", totalPcs);
1641
 
1642
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1643
 
1644
		model.addAttribute("userWallet", userWallet);
1645
 
1646
		return "create-partner-po";
1647
 
1648
	}
1649
 
1650
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1651
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1652
			throws Exception {
1653
 
1654
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1655
 
1656
		List<Item> items = new ArrayList<>();
1657
		for (Item item : selecteditems) {
1658
 
1659
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1660
 
1661
			if (tagListing != null) {
1662
				items.add(item);
1663
			}
1664
 
1665
		}
1666
		model.addAttribute("items", items);
1667
		LOGGER.info("itemIdAndColorMap" + items);
1668
		return "select-item-color";
1669
	}
1670
 
30003 tejbeer 1671
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
30564 tejbeer 1672
			"niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com");
30003 tejbeer 1673
 
1674
	@Autowired
1675
	private PositionRepository positionRepository;
1676
 
1677
	@Autowired
1678
	private PartnerTypeChangeService partnerTypeChangeService;
1679
 
1680
	@Autowired
1681
	private com.spice.profitmandi.service.transaction.TransactionService transactionService;
1682
 
1683
	@Autowired
1684
	private CategoryRepository categoryRepository;
1685
 
30044 tejbeer 1686
	@Autowired
1687
	private BrandLimitRepository brandLimitRepository;
1688
 
30003 tejbeer 1689
	private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,
1690
			OrderStatus.ACCEPTED);
1691
 
1692
	public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();
1693
 
1694
	static {
30044 tejbeer 1695
 
30003 tejbeer 1696
		Brand_Amount_Limit.put("accessories", 10000.00);
1697
		Brand_Amount_Limit.put("TV", 27000.00);
1698
	}
1699
 
1700
	@RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)
1701
	public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {
1702
 
1703
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1704
		String email = loginDetails.getEmailId();
1705
 
1706
		List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Tecno", "Itel", "OnePlus", "Lava", "Realme",
1707
				"Xiaomi", "Nokia");
1708
 
1709
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1710
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1711
 
1712
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1713
 
1714
		if (emails.contains(authUser.getEmailId())) {
1715
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
1716
			LOGGER.info("fofoIds" + fofoIds);
1717
		}
1718
 
1719
		Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
1720
 
30024 tejbeer 1721
		Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();
30003 tejbeer 1722
 
1723
		Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();
1724
		Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();
1725
		Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();
30426 tejbeer 1726
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30003 tejbeer 1727
		Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
1728
		Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();
1729
 
1730
		if (fofoIds.size() > 0 && fofoIds != null) {
1731
			List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1732
 
30046 tejbeer 1733
			Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
1734
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));
1735
 
1736
			model.addAttribute("partnerActivationType", partnerActivationType);
1737
			model.addAttribute("activationTypes", ActivationType.values());
1738
 
30003 tejbeer 1739
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();
1740
 
1741
			model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);
30044 tejbeer 1742
 
1743
			Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
1744
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1745
							Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));
1746
 
1747
			model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
30426 tejbeer 1748
			customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1749
					.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30024 tejbeer 1750
			Map<Integer, Map<String, Double>> inStockBrandModel = new HashMap<>();
1751
			Map<Integer, Map<String, Double>> pendingIndent = new HashMap<>();
1752
			Map<Integer, Map<String, Double>> grnPendingOrders = new HashMap<>();
30003 tejbeer 1753
 
30024 tejbeer 1754
			// mobile
30003 tejbeer 1755
			inStockBrandModel = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList)
1756
					.stream()
1757
					.collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1758
							Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1759
									Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));
1760
 
1761
			pendingIndent = transactionService.getInTransitOrders(fofoIdList).stream()
30024 tejbeer 1762
					.filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
30003 tejbeer 1763
					.collect(Collectors.groupingBy(x -> x.getRetailerId(),
1764
							Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1765
									Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
1766
 
1767
			grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoIdList).stream()
30024 tejbeer 1768
					.filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
30003 tejbeer 1769
					.collect(Collectors.groupingBy(x -> x.getRetailerId(),
1770
							Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1771
									Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
1772
 
30024 tejbeer 1773
			// accessories
30003 tejbeer 1774
			inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
1775
					.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1776
 
1777
			pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1778
					.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1779
 
1780
			grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1781
					.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1782
 
30024 tejbeer 1783
			for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
1784
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
1785
						LocalDate.now());
1786
				fofoIdPartnerTypeMap.put(customRetailer.getKey(), partnerType);
1787
 
1788
				Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
1789
				Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
1790
				Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
1791
				double totalAmount = 0;
1792
 
1793
				Map<String, Double> brandAmountMap = new HashMap<>();
1794
				for (String brand : brands) {
1795
 
1796
					double stockValue = 0;
1797
					double pendingValue = 0;
1798
					double grnValue = 0;
1799
					if (stockBrand != null) {
1800
 
1801
						if (stockBrand.get(brand) != null) {
1802
							stockValue = stockBrand.get(brand);
1803
						}
1804
					}
1805
 
1806
					if (pendingIndentBrand != null) {
1807
						if (pendingIndentBrand.get(brand) != null) {
1808
							pendingValue = pendingIndentBrand.get(brand);
1809
						}
1810
					}
1811
 
1812
					if (grnBrand != null) {
1813
						if (grnBrand.get(brand) != null) {
1814
							grnValue = grnBrand.get(brand);
1815
						}
1816
					}
1817
 
1818
					totalAmount = stockValue + pendingValue + grnValue;
1819
 
1820
					brandAmountMap.put(brand, totalAmount);
1821
 
1822
				}
1823
 
1824
				fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);
1825
 
1826
			}
1827
 
1828
			List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
1829
					.selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
1830
			if (!partnerDailyInvestments.isEmpty()) {
1831
				partnerDailyInvestmentMap = partnerDailyInvestments.stream()
1832
						.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1833
			}
1834
 
30003 tejbeer 1835
		}
1836
 
1837
		model.addAttribute("customRetailers", customRetailers);
1838
 
30024 tejbeer 1839
		LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);
30003 tejbeer 1840
 
1841
		model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);
1842
 
1843
		model.addAttribute("brands", brands);
1844
 
1845
		model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
30024 tejbeer 1846
		model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);
30003 tejbeer 1847
 
1848
		model.addAttribute("inStockAccessTv", inStockAccessTv);
1849
		model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
1850
		model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
1851
		model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
1852
		return "partner-brandwise-detail";
1853
	}
1854
 
30046 tejbeer 1855
	@RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
1856
	public String changeActivationType(HttpServletRequest request, @RequestParam String code,
30664 amit.gupta 1857
									   @RequestParam ActivationType activationType, Model model) throws Exception {
30046 tejbeer 1858
 
1859
		FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);
1860
 
1861
		fofoStore.setActivationType(activationType);
1862
 
1863
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1864
		return "response";
1865
 
1866
	}
1867
 
30017 amit.gupta 1868
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1869
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1870
			throws Exception {
1871
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1872
		SuggestedPo mp = new SuggestedPo();
1873
		mp.setFofoId(monthlyPoModel.getFofoId());
1874
		mp.setCreateTimestamp(LocalDateTime.now());
1875
		mp.setStatus("open");
1876
		mp.setAuthId(loginDetails.getEmailId());
1877
		suggestedPoRepository.persist(mp);
1878
 
1879
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1880
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1881
			mpd.setItemId(poId.getItemId());
1882
			mpd.setQuantity(poId.getQty());
1883
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1884
			mpd.setPoId(mp.getId());
1885
			suggestedPoDetailRepository.persist(mpd);
1886
		}
1887
 
1888
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1889
		sendNotificationModel.setCampaignName("Alert");
1890
		sendNotificationModel.setMessage("Suggested Po");
1891
		sendNotificationModel.setType("url");
1892
		sendNotificationModel.setTitle("Alert");
1893
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1894
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1895
		sendNotificationModel.setMessageType(MessageType.notification);
1896
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1897
 
1898
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1899
		notificationService.sendNotification(sendNotificationModel);
1900
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1901
 
1902
		return "response";
1903
	}
1904
 
30003 tejbeer 1905
	@RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
1906
	public String getPartnerShortageStock(HttpServletRequest request,
30664 amit.gupta 1907
										  @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
30003 tejbeer 1908
			throws Exception {
1909
 
1910
 
1911
		Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
1912
				.getSaholicPOItems();
1913
 
1914
		List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
1915
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1916
		Map<Integer, Integer> processingOrderMap = null;
1917
		Map<Integer, Integer> catalogIdAndQtyMap = null;
1918
		Map<Integer, Integer> grnPendingOrdersMap = null;
1919
 
30044 tejbeer 1920
		List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
1921
 
1922
		List<PartnerStockDescriptionModel> grnPendings = new ArrayList<>();
1923
 
1924
		List<PartnerStockDescriptionModel> pendingIndents = new ArrayList<>();
1925
 
30003 tejbeer 1926
		Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1927
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1928
 
1929
		if (!currentInventorySnapshot.isEmpty()) {
30044 tejbeer 1930
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1931
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1932
						.filter(x -> x.getBrand().equals(brand))
1933
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1934
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
30003 tejbeer 1935
 
30044 tejbeer 1936
			} else {
1937
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1938
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1939
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1940
			}
1941
			inStocks.addAll(getBrandItemwiseDescription(brand, catalogIdAndQtyMap));
30003 tejbeer 1942
		}
1943
 
1944
		Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1945
				.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1946
						Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1947
		if (!grnPendingOrders.isEmpty()) {
1948
 
30044 tejbeer 1949
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1950
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1951
						.filter(x -> x.getBrand().equals(brand))
1952
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1953
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1954
 
1955
			} else {
1956
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1957
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1958
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1959
			}
1960
			grnPendings.addAll(getBrandItemwiseDescription(brand, grnPendingOrdersMap));
1961
 
30003 tejbeer 1962
		}
1963
 
1964
		Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1965
				.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1966
						Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1967
		if (!processingOrder.isEmpty()) {
30044 tejbeer 1968
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1969
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1970
						.filter(x -> x.getBrand().equals(brand)).collect(Collectors.groupingBy(
1971
								x -> x.getCatalogItemId(), Collectors.summingInt(x -> processingOrder.get(x.getId()))));
30003 tejbeer 1972
 
30044 tejbeer 1973
			} else {
1974
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1975
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1976
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1977
			}
1978
			pendingIndents.addAll(getBrandItemwiseDescription(brand, processingOrderMap));
1979
 
30003 tejbeer 1980
		}
1981
 
1982
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1983
				.collect(Collectors.toList());
1984
		LOGGER.info("regionIds" + regionIds);
1985
		if (regionIds.size() == 0) {
1986
			LOGGER.info("No region found for partner {}", fofoId);
1987
 
1988
		}
1989
		Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
1990
				.selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
1991
						Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
1992
 
1993
		for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1994
			List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
1995
 
1996
			if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {
1997
 
1998
				FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
30664 amit.gupta 1999
						processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId, warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2000
 
2001
				focusedModelShortageList.add(fm);
2002
			} else if (brand.equals("accessories")) {
2003
 
2004
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2005
					if (items.get(0).getCategoryId() != 0) {
2006
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2007
 
2008
						if (category.getParentCategoryId() == 10011) {
2009
							FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
30664 amit.gupta 2010
									entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId
2011
									, warehousePoItemAvailabilityMap, items,
30003 tejbeer 2012
									customRetailer);
2013
 
2014
							focusedModelShortageList.add(fm);
2015
 
2016
						}
2017
					}
2018
 
2019
				}
2020
 
2021
			} else if (brand.equals("TV")) {
2022
 
2023
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2024
					LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
2025
					if (items.get(0).getCategoryId() != 0) {
2026
 
2027
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2028
 
2029
						if (category.getParentCategoryId() == 14200) {
2030
							FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2031
									entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
30664 amit.gupta 2032
									warehousePoItemAvailabilityMap, items,
30003 tejbeer 2033
									customRetailer);
2034
 
2035
							focusedModelShortageList.add(fm);
2036
 
2037
						}
2038
					}
2039
 
2040
				}
2041
 
2042
			}
2043
 
2044
		}
2045
 
2046
		LOGGER.info("focusedModelShortageList" + focusedModelShortageList);
2047
 
2048
		model.addAttribute("focusedModelShortageList", focusedModelShortageList);
2049
 
30044 tejbeer 2050
		model.addAttribute("inStocks", inStocks);
2051
 
2052
		model.addAttribute("grnPendings", grnPendings);
2053
 
2054
		model.addAttribute("pendingIndents", pendingIndents);
2055
 
30003 tejbeer 2056
		model.addAttribute("customRetailer", customRetailer);
30044 tejbeer 2057
 
2058
		model.addAttribute("brand", brand);
2059
 
2060
		if (brand.equals("undefined")) {
2061
 
2062
			Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
2063
					.stream().collect(Collectors.groupingBy(x -> x.getBrandName()));
2064
 
2065
			Map<String, List<PartnerStockDescriptionModel>> inStockBrandMap = inStocks.stream()
2066
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2067
 
2068
			LOGGER.info("inStockBrandMap" + inStockBrandMap);
2069
 
2070
			Map<String, List<PartnerStockDescriptionModel>> grnPendingBrandMap = grnPendings.stream()
2071
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2072
 
2073
			LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);
2074
 
2075
			Map<String, List<PartnerStockDescriptionModel>> pendingIndentBrandMap = pendingIndents.stream()
2076
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2077
 
2078
			LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);
2079
 
2080
			model.addAttribute("inStockBrandMap", inStockBrandMap);
2081
 
2082
			model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);
2083
 
2084
			model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);
2085
 
2086
			model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);
2087
 
2088
		}
30003 tejbeer 2089
		return "partner-stock";
2090
 
2091
	}
2092
 
30044 tejbeer 2093
	private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
30664 amit.gupta 2094
																		   Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
30044 tejbeer 2095
		List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
2096
 
2097
		for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2098
			List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
2099
 
2100
			if (brand.equals("accessories")) {
2101
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2102
 
2103
					if (items.get(0).getCategoryId() != 0) {
2104
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2105
 
2106
						if (category.getParentCategoryId() == 10011) {
2107
							PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2108
							psdp.setBrand(items.get(0).getBrand());
2109
							psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2110
									+ items.get(0).getModelNumber());
2111
							psdp.setQty(inStock.getValue());
2112
							inStocks.add(psdp);
2113
						}
2114
					}
2115
 
2116
				}
2117
 
2118
			} else if (brand.equals("TV")) {
2119
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2120
 
2121
					if (items.get(0).getCategoryId() != 0) {
2122
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2123
 
2124
						if (category.getParentCategoryId() == 14200) {
2125
							PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2126
							psdp.setBrand(items.get(0).getBrand());
2127
							psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2128
									+ items.get(0).getModelNumber());
2129
							psdp.setQty(inStock.getValue());
2130
							inStocks.add(psdp);
2131
						}
2132
					}
2133
 
2134
				}
2135
 
2136
			} else {
2137
				PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2138
				psdp.setBrand(items.get(0).getBrand());
2139
				psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2140
						+ items.get(0).getModelNumber());
2141
				psdp.setQty(inStock.getValue());
2142
				inStocks.add(psdp);
2143
			}
2144
 
2145
		}
2146
 
2147
		return inStocks;
2148
	}
2149
 
30003 tejbeer 2150
	private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
30664 amit.gupta 2151
															  Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
2152
															  Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
2153
															  Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
2154
															  CustomRetailer customRetailer) throws ProfitMandiBusinessException {
30003 tejbeer 2155
 
2156
		int minQty = qty;
2157
		int inStockQty = 0;
2158
		int processingQty = 0;
2159
		int grnPendingQty = 0;
2160
		int allColorNetAvailability = 0;
2161
		int allColorPoAvailability = 0;
2162
		if (processingOrderMap != null) {
2163
			processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);
2164
 
2165
		}
2166
		if (grnPendingOrdersMap != null) {
2167
			grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);
2168
 
2169
		}
2170
		if (catalogIdAndQtyMap != null) {
2171
			inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);
2172
 
2173
		}
2174
 
2175
		int grnStockQty = grnPendingQty + inStockQty;
2176
		int totalQty = processingQty + grnPendingQty + inStockQty;
2177
 
2178
		int shortageQty = minQty - totalQty;
2179
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
2180
 
2181
 
2182
		Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2183
				.get(fofoStore.getWarehouseId());
2184
 
2185
		for (Item it : items) {
30664 amit.gupta 2186
			List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(), fofoStore.getWarehouseId());
30003 tejbeer 2187
			List<SaholicPOItem> poItemAvailability = null;
2188
 
2189
			if (poItemAvailabilityMap != null) {
2190
				poItemAvailability = poItemAvailabilityMap.get(it.getId());
2191
			}
2192
			if (currentAvailability != null) {
2193
				allColorNetAvailability += currentAvailability.stream()
30664 amit.gupta 2194
						.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
30003 tejbeer 2195
			}
2196
 
2197
			if (poItemAvailability != null) {
2198
				allColorPoAvailability += poItemAvailability.stream()
2199
						.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
2200
			}
2201
 
2202
		}
2203
 
2204
		FocusedModelShortageModel fm = new FocusedModelShortageModel();
2205
		fm.setFofoId(fofoId);
2206
		fm.setStoreCode(fofoStore.getCode());
2207
		fm.setStoreName(customRetailer.getBusinessName());
2208
		fm.setBrandName(items.get(0).getBrand());
2209
		fm.setModelName(items.get(0).getModelName());
2210
		fm.setModelNumber(items.get(0).getModelNumber());
2211
		fm.setGrnStockQty(grnStockQty);
2212
		fm.setPendingIndentQty(processingQty);
2213
		fm.setShortageQty(shortageQty);
2214
		fm.setPoAvailabitiy(allColorPoAvailability);
2215
		fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2216
		fm.setAvailabitiy(allColorNetAvailability);
2217
		return fm;
2218
 
2219
	}
2220
 
30017 amit.gupta 2221
	@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
2222
	public String SendPONotification(HttpServletRequest request, Model model) {
2223
		model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);
2224
		return "send-po-notification";
2225
	}
2226
 
2227
	@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
30044 tejbeer 2228
	public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
30664 amit.gupta 2229
									 Model model) throws Exception {
30017 amit.gupta 2230
 
30426 tejbeer 2231
		Map<Integer, Item> selectedCatalogItemMap = itemRepository
2232
				.selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
2233
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));
30017 amit.gupta 2234
 
30080 amit.gupta 2235
		Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
30044 tejbeer 2236
				.collect(Collectors.toSet());
30080 amit.gupta 2237
 
30017 amit.gupta 2238
		int warehouseId = poItemWarehouseModel.getWarehouseId();
30080 amit.gupta 2239
		for (String brand : brands) {
30096 amit.gupta 2240
			List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
30426 tejbeer 2241
					.filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
2242
					.map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
30080 amit.gupta 2243
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2244
			sendNotificationModel.setCampaignName("SendPo");
2245
			sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
30096 amit.gupta 2246
			sendNotificationModel.setMessage(String.join(", ", modelNames));
30080 amit.gupta 2247
			sendNotificationModel.setType("url");
2248
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2249
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2250
			sendNotificationModel.setMessageType(MessageType.notification);
30017 amit.gupta 2251
 
30426 tejbeer 2252
			List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
2253
					.filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
2254
							&& !x.isAccessory())
30080 amit.gupta 2255
					.collect(Collectors.toList());
2256
			List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
2257
					.collect(Collectors.toList());
30017 amit.gupta 2258
 
30080 amit.gupta 2259
			List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
2260
					.filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
30017 amit.gupta 2261
 
30080 amit.gupta 2262
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
2263
			sendNotificationModel.setUserIds(userIds);
2264
			notificationService.sendNotification(sendNotificationModel);
2265
		}
30017 amit.gupta 2266
		model.addAttribute("response", true);
2267
		return "response";
2268
	}
2269
 
25721 tejbeer 2270
}