Subversion Repositories SmartDukaan

Rev

Rev 30279 | Rev 30449 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
28468 tejbeer 1
package com.spice.profitmandi.service;
2
 
30279 tejbeer 3
import java.io.FileInputStream;
4
import java.io.ObjectInputStream;
5
import java.time.LocalDate;
6
import java.time.LocalDateTime;
7
import java.time.Period;
8
import java.time.YearMonth;
9
import java.time.format.DateTimeFormatter;
10
import java.time.temporal.ChronoUnit;
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.Comparator;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.LinkedHashMap;
17
import java.util.LinkedHashSet;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Map.Entry;
21
import java.util.Optional;
22
import java.util.Set;
23
import java.util.TreeMap;
24
import java.util.stream.Collectors;
25
import java.util.stream.LongStream;
26
 
27
import org.apache.logging.log4j.LogManager;
28
import org.apache.logging.log4j.Logger;
29
import org.springframework.beans.factory.annotation.Autowired;
30
import org.springframework.stereotype.Component;
31
import org.springframework.ui.Model;
32
 
28468 tejbeer 33
import com.google.gson.Gson;
34
import com.spice.profitmandi.common.enumuration.ReporticoProject;
35
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30279 tejbeer 36
import com.spice.profitmandi.common.model.ChartInvestmentModel;
37
import com.spice.profitmandi.common.model.ChartModel;
38
import com.spice.profitmandi.common.model.CustomRetailer;
39
import com.spice.profitmandi.common.model.Data;
40
import com.spice.profitmandi.common.model.DataInvestmentModel;
41
import com.spice.profitmandi.common.model.Legend;
42
import com.spice.profitmandi.common.model.OptionModel;
43
import com.spice.profitmandi.common.model.PieLables;
44
import com.spice.profitmandi.common.model.ProfitMandiConstants;
28468 tejbeer 45
import com.spice.profitmandi.dao.entity.auth.AuthUser;
46
import com.spice.profitmandi.dao.entity.auth.Menu;
47
import com.spice.profitmandi.dao.entity.cs.Position;
48
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
29165 manish 49
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
28468 tejbeer 50
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
51
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
52
import com.spice.profitmandi.dao.model.BrandWiseModel;
53
import com.spice.profitmandi.dao.model.PartnerDetailModel;
54
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
55
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
56
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
57
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
58
import com.spice.profitmandi.dao.repository.cs.CsService;
59
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
60
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
61
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28825 tejbeer 62
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
28468 tejbeer 63
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
64
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
65
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
66
import com.spice.profitmandi.service.user.RetailerService;
67
 
68
@Component
69
public class AdminUser {
70
	@Autowired
71
	private Gson gson;
72
 
73
	@Autowired
74
	private OrderRepository orderRepository;
75
 
76
	@Autowired
77
	TicketRepository ticketRepository;
78
 
79
	@Autowired
80
	private ChartService chartService;
81
 
82
	@Autowired
83
	RetailerService retailerService;
84
 
85
	@Autowired
86
	AuthRepository authRepository;
87
 
88
	@Autowired
89
	FofoStoreRepository fofoStoreRepository;
90
 
91
	@Autowired
92
	CsService csService;
93
 
94
	@Autowired
95
	private MenuRepository menuRepository;
96
 
97
	@Autowired
98
	private PositionRepository positionRepository;
99
 
100
	@Autowired
101
	private MenuCategoryRepository menuCategoryRepository;
102
 
103
	@Autowired
104
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
105
 
106
	@Autowired
107
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
108
 
109
	@Autowired
28825 tejbeer 110
	private ActivatedImeiRepository activatedImeiRepository;
111
 
112
	@Autowired
28468 tejbeer 113
	private PartnerStatsService partnerStatsService;
114
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
115
			"niranjan.kala@smartdukaan.com", "hemant.kaura@smartdukaan.com", "amit.gupta@shop2020.in",
116
			"tejbeer.kaur@shop2020.in");
117
 
118
	List<String> colorList = Arrays.asList("mediumseagreen", "dodgerblue", "darkblue", "gold", "coral", "steelblue",
119
			"red", "deeppink", "midnightblue", "cornsilk");
120
 
121
	List<String> borderList = Arrays.asList("lawngreen", "lightblue", "#0000cd", "#f7e98e", "lightcoral", "#0000cd",
122
			"lightsalmon", "pink", "#0000cd", "cornsilk");
123
 
124
	List<String> brands = Arrays.asList("Oppo", "Vivo", "Samsung", "Realme", "Xiaomi", "Tecno", "Itel", "Lava",
125
			"Nokia");
126
 
127
	private static final Logger LOGGER = LogManager.getLogger(AdminUser.class);
128
 
30279 tejbeer 129
	public ChartModel getBrandWiseLmp(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
130
			LocalDate endDate, String filterType) {
131
		LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 132
 
30279 tejbeer 133
		List<BrandWiseModel> brandWiseLms = orderRepository.selectGroupByBrandLmp(fofoIds, warehouseIds, startDate,
134
				endDate, filterType);
28468 tejbeer 135
		LOGGER.info("brandWiseLms" + brandWiseLms);
30279 tejbeer 136
		ChartModel cm = null;
28468 tejbeer 137
 
30279 tejbeer 138
		if (filterType.equals("dateWise")) {
139
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 140
 
30279 tejbeer 141
			Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
142
			for (BrandWiseModel bwl : brandWiseLms) {
143
				if (!brandDateValue.containsKey(bwl.getBrand())) {
144
					brandDateValue.put(bwl.getBrand(), new HashMap<>());
145
				}
146
				Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
147
				dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
28468 tejbeer 148
			}
149
 
30279 tejbeer 150
			long days = startDate.until(endDate, ChronoUnit.DAYS);
151
			List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
152
					.collect(Collectors.toList());
153
			LOGGER.info("All dates between {}", allDatesBetween);
28468 tejbeer 154
 
30279 tejbeer 155
			Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 156
 
30279 tejbeer 157
			for (String brand : brands) {
158
				if (!brandDateValue.containsKey(brand)) {
159
					brandDateValue.put(brand, new HashMap<>());
160
				}
161
				Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
162
				for (LocalDate date : allDatesBetween) {
163
					if (dateWiseBrand.get(date) == null) {
164
						dateWiseBrand.put(date, 0.0);
165
					}
166
				}
167
 
168
				Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
169
				sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
170
				LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
30220 amit.gupta 171
			}
30279 tejbeer 172
 
173
			LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
174
 
175
			LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
176
			cm = chartService.createChartWithLabels(
177
					allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
178
							.collect(Collectors.toCollection(LinkedHashSet::new)),
179
					sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Purchase");
180
 
181
		} else {
182
 
183
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
184
 
185
			Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
186
			for (BrandWiseModel bwl : brandWiseLms) {
187
				Map<YearMonth, Double> yearMonthValue = new HashMap<>();
188
				if (brandMonthValue.containsKey(bwl.getBrand())) {
189
					yearMonthValue = brandMonthValue.get(bwl.getBrand());
190
					yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
191
							(double) bwl.getAmount());
192
				} else {
193
 
194
					yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
195
							(double) bwl.getAmount());
196
 
28468 tejbeer 197
				}
30279 tejbeer 198
				brandMonthValue.put(bwl.getBrand(), yearMonthValue);
199
 
28468 tejbeer 200
			}
30279 tejbeer 201
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 202
 
30279 tejbeer 203
			Period age = Period.between(startDate, endDate);
204
			int months = age.getMonths();
205
			LOGGER.info("months" + months);
206
			LOGGER.info("brandWiseLms" + brandWiseLms);
207
			LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 208
 
30279 tejbeer 209
			Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 210
 
30279 tejbeer 211
			for (String brand : brands) {
212
				Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
213
				for (int i = months; i >= 0; i--) {
28468 tejbeer 214
 
30279 tejbeer 215
					LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
28468 tejbeer 216
 
30279 tejbeer 217
					if (yearMonthValue != null) {
218
						if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
219
							yearMonthValue.put(YearMonth.from(startMonth), 0.0);
220
						}
221
 
222
					} else {
223
						yearMonthValue = new HashMap<>();
224
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
225
					}
226
				}
227
 
228
				Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
229
 
230
				brandMonthValue.put(brand, sortedMonthBrandValue);
231
 
232
				sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
233
 
234
			}
235
 
236
			cm = chartService.createChart(months, sortedBrandValue, colorList, borderList,
237
					"Brand Wise Monthly Purchase");
238
 
239
		}
240
 
28468 tejbeer 241
		return cm;
242
	}
243
 
29165 manish 244
	public ChartInvestmentModel getAllStatePartnerType(Map<Integer, PartnerDetailModel> fofoIdAndallValues)
245
			throws ProfitMandiBusinessException {
246
 
247
		Map<String, Float> partnerTypeCount = new HashMap<>();
248
 
249
		List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values());
250
 
251
		for (PartnerType partnerType : partnerTypes) {
252
 
253
			float count = fofoIdAndallValues.entrySet().stream()
254
					.filter(x -> x.getValue().getPartnerType().equals(partnerType)).count();
255
 
256
			partnerTypeCount.put(partnerType.toString(), count);
257
 
258
		}
259
 
260
		ChartInvestmentModel cm = new ChartInvestmentModel();
261
 
262
		HashSet<String> labels = new HashSet<String>();
263
		labels.addAll(partnerTypes.stream().skip(1).map(x -> x.toString()).collect(Collectors.toList()));
264
		List<String> labelList = new ArrayList<>(labels);
265
 
266
		List<String> backgroundColor = new ArrayList<>();
267
 
268
		List<Float> values = new ArrayList<>();
269
 
270
		for (String label : labelList) {
271
			values.add(partnerTypeCount.get(label));
272
			if (label.equals("BRONZE")) {
29168 manish 273
				backgroundColor.add("#CD7F32");
29165 manish 274
			}
275
			if (label.equals("SILVER")) {
276
				backgroundColor.add("silver");
277
			}
278
			if (label.equals("GOLD")) {
29168 manish 279
				backgroundColor.add("#FFD700");
29165 manish 280
			}
281
			if (label.equals("DIAMOND")) {
282
				backgroundColor.add("#B9F2FF");
283
			}
284
 
285
			if (label.equals("PLATINUM")) {
29198 manish 286
				backgroundColor.add("#800080");
29165 manish 287
			}
288
			if (label.equals("NEW")) {
289
				backgroundColor.add("green");
290
			}
291
 
292
		}
293
 
294
		LOGGER.info("valuesPartnerType" + values);
295
		LOGGER.info("partnerTypeCount" + partnerTypeCount);
296
 
297
		Data data = new Data();
298
		data.setData(values);
299
		data.setBackgroundColor(backgroundColor);
300
		data.setLabel("DataSet 1");
301
 
302
		PieLables label = new PieLables();
303
		label.setFontColor("black");
304
		label.setFontSize(22);
305
 
306
		Legend legend = new Legend();
307
		legend.setLabels(label);
308
		legend.setPosition("left");
309
 
310
		List<Data> dataList = new ArrayList<>();
311
		dataList.add(data);
312
 
313
		DataInvestmentModel datasets = new DataInvestmentModel();
314
		datasets.setDatasets(dataList);
315
		datasets.setLabels(labels);
316
 
317
		OptionModel om = new OptionModel();
318
		om.setLegend(legend);
319
		cm.setType("pie");
320
		cm.setData(datasets);
321
		cm.setOptions(om);
322
 
323
		return cm;
324
	}
325
 
30279 tejbeer 326
	public Map<String, Object> getFilter(int warehouseId, String email, LocalDateTime date, LocalDateTime endDate)
28468 tejbeer 327
			throws ProfitMandiBusinessException {
328
		Map<String, Object> map = new HashMap<>();
30426 tejbeer 329
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
330
		Map<Integer, CustomRetailer> crm = null;
28468 tejbeer 331
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
332
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
333
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
334
 
335
		Set<Integer> fofoIds = null;
336
		fofoIds = storeGuyMap.get(authUser.getEmailId());
337
		if (emails.contains(authUser.getEmailId())) {
338
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
339
 
340
		}
341
 
342
		if (fofoIds == null) {
343
			List<Position> positions1 = positionRepository.selectAll(authUser.getId());
344
			if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
345
					.count() > 0) {
346
				fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
347
						.map(x -> x.getPartnerId()).collect(Collectors.toSet());
348
			}
349
		}
350
 
351
		if (warehouseId != 0) {
352
 
353
			fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
354
					.stream().map(x -> x).collect(Collectors.toSet());
355
 
356
		}
357
 
358
		if (fofoIds != null) {
359
 
30426 tejbeer 360
			crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
361
					.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
362
 
28468 tejbeer 363
		}
364
 
365
		map.put("date", date);
30279 tejbeer 366
		map.put("endDate", endDate);
30426 tejbeer 367
		map.put("customRetailersMap", crm);
28468 tejbeer 368
		map.put("fofoIds", fofoIds);
369
		map.put("warehouseMap", warehouseMap);
370
 
371
		return map;
372
 
373
	}
374
 
30279 tejbeer 375
	public ChartModel getBrandWiseLms(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
376
			LocalDate endDate, String filterType) {
377
		LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 378
 
30279 tejbeer 379
		List<BrandWiseModel> brandWiseLms = fofoStoreRepository.selectGroupByBrandLms(fofoIds, warehouseIds, startDate,
380
				endDate, filterType);
28468 tejbeer 381
		LOGGER.info("brandWiseLms" + brandWiseLms);
382
 
30279 tejbeer 383
		ChartModel cm = null;
28468 tejbeer 384
 
30279 tejbeer 385
		if (filterType.equals("dateWise")) {
386
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 387
 
30279 tejbeer 388
			Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
389
			for (BrandWiseModel bwl : brandWiseLms) {
390
				if (!brandDateValue.containsKey(bwl.getBrand())) {
391
					brandDateValue.put(bwl.getBrand(), new HashMap<>());
392
				}
393
				Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
394
				dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
395
			}
28468 tejbeer 396
 
30279 tejbeer 397
			long days = startDate.until(endDate, ChronoUnit.DAYS);
398
			List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
399
					.collect(Collectors.toList());
400
			LOGGER.info("All dates between {}", allDatesBetween);
401
 
402
			Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
403
 
404
			for (String brand : brands) {
405
				if (!brandDateValue.containsKey(brand)) {
406
					brandDateValue.put(brand, new HashMap<>());
407
				}
408
				Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
409
				for (LocalDate date : allDatesBetween) {
410
					if (dateWiseBrand.get(date) == null) {
411
						dateWiseBrand.put(date, 0.0);
412
					}
413
				}
414
 
415
				Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
416
				sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
417
				LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
28468 tejbeer 418
			}
419
 
30279 tejbeer 420
			LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
28468 tejbeer 421
 
30279 tejbeer 422
			LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
423
			cm = chartService.createChartWithLabels(
424
					allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
425
							.collect(Collectors.toCollection(LinkedHashSet::new)),
426
					sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Sale");
28468 tejbeer 427
 
30279 tejbeer 428
		} else {
28468 tejbeer 429
 
30279 tejbeer 430
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
28468 tejbeer 431
 
30279 tejbeer 432
			Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
433
			for (BrandWiseModel bwl : brandWiseLms) {
434
				Map<YearMonth, Double> yearMonthValue = new HashMap<>();
435
				if (brandMonthValue.containsKey(bwl.getBrand())) {
436
					yearMonthValue = brandMonthValue.get(bwl.getBrand());
437
					yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
438
							(double) bwl.getAmount());
439
				} else {
28468 tejbeer 440
 
30279 tejbeer 441
					yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
442
							(double) bwl.getAmount());
28468 tejbeer 443
 
444
				}
30279 tejbeer 445
				brandMonthValue.put(bwl.getBrand(), yearMonthValue);
446
 
28468 tejbeer 447
			}
30279 tejbeer 448
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 449
 
30279 tejbeer 450
			Period age = Period.between(startDate, endDate);
451
			int months = age.getMonths();
452
			LOGGER.info("months" + months);
453
			LOGGER.info("brandWiseLms" + brandWiseLms);
454
			LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 455
 
30279 tejbeer 456
			Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 457
 
30279 tejbeer 458
			for (String brand : brands) {
459
				Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
460
				for (int i = months; i >= 0; i--) {
28468 tejbeer 461
 
30279 tejbeer 462
					LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
463
 
464
					if (yearMonthValue != null) {
465
						if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
466
							yearMonthValue.put(YearMonth.from(startMonth), 0.0);
467
						}
468
 
469
					} else {
470
						yearMonthValue = new HashMap<>();
471
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
472
					}
473
				}
474
 
475
				Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
476
 
477
				brandMonthValue.put(brand, sortedMonthBrandValue);
478
 
479
				sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
480
 
481
			}
482
 
483
			cm = chartService.createChart(months, sortedBrandValue, colorList, borderList, "Brand Wise Monthly Sale");
28468 tejbeer 484
		}
485
 
486
		return cm;
487
	}
488
 
489
	public String adminPanel(int fofoId, String email, Model model) throws Exception {
490
		List<Menu> menus = null;
491
		try {
492
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
493
			List<Position> positions = positionRepository.selectAll(authUser.getId());
494
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
495
			ReporticoCacheTable rctSaholic = null;
496
			ReporticoCacheTable rctPartneStat = null;
497
 
498
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
499
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
500
 
501
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
502
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
503
 
504
			Map<AuthUser, Long> authUserTicketCount = null;
505
 
506
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
507
				wm.put(entry.getKey(), entry.getValue());
508
			}
509
 
510
			wm.put(0, "Total Values");
511
			long stockValue = 0;
512
			long stockQty = 0;
513
			long pendingIndent = 0;
514
			long tertiary = 0;
515
 
516
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
517
 
518
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
519
			if (emails.contains(authUser.getEmailId())) {
520
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
521
				LOGGER.info("fofoIds" + fofoIds);
522
			}
523
			if (fofoIds == null) {
524
				List<Position> positions1 = positionRepository.selectAll(authUser.getId());
525
				if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
526
						.count() > 0) {
527
					fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
528
							.flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
529
				}
530
			}
531
 
532
			if (fofoIds != null && fofoIds.size() > 0) {
533
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
534
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
535
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
536
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
537
				// warehouseStock
538
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
539
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
540
 
541
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
542
 
543
				if (!warehouseStockMap.isEmpty()) {
544
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
545
						stockValue += warehouseStock.getValue().getStockValue();
546
						stockQty += warehouseStock.getValue().getStockQty();
547
						pendingIndent += warehouseStock.getValue().getPendingIndent();
548
						tertiary += warehouseStock.getValue().getTertiary();
549
					}
550
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
551
					ws.setStockQty(stockQty);
552
					ws.setStockValue(stockValue);
553
					ws.setPendingIndent(pendingIndent);
554
					ws.setTertiary(tertiary);
555
					ws.setWarehouseId(0);
556
					warehouseStockMap.put(0, ws);
557
 
558
				}
559
 
560
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
561
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
562
 
563
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
564
 
565
				// warehouseStock
566
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
567
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
568
 
569
				Set<CustomRetailer> positionRetailers = fofoIds.stream()
570
						.map(x -> retailerService.getAllFofoRetailers().get(x)).filter(x -> x != null)
571
						.collect(Collectors.toSet());
572
				model.addAttribute("retailers", gson.toJson(positionRetailers));
573
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
574
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
575
			} else {
576
				List<Position> warehousePositions = positions.stream()
577
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
578
						.collect(Collectors.toList());
579
				if (warehousePositions.size() > 0) {
580
					Set<CustomRetailer> positionRetailers = new HashSet<>();
581
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
582
						positionRetailers.addAll(customRetailers);
583
					});
584
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
585
					model.addAttribute("retailers", gson.toJson(positionRetailers));
586
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
587
				}
30056 amit.gupta 588
				List<Position> categoryPositions = positions.stream()
589
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_CATEGORY)
590
						.collect(Collectors.toList());
591
				if (categoryPositions.size() > 0) {
592
					Set<CustomRetailer> positionRetailers = new HashSet<>();
593
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
594
						positionRetailers.addAll(customRetailers);
595
					});
596
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
597
					model.addAttribute("retailers", gson.toJson(positionRetailers));
598
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
599
				}
28468 tejbeer 600
			}
601
 
602
			if (positions.size() > 0) {
603
				if (positions.stream()
604
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
605
								|| x.getEscalationType().equals(EscalationType.L4)
606
								|| x.getEscalationType().equals(EscalationType.L5))
607
						.count() > 0) {
608
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
609
				}
610
			}
611
 
612
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
613
					.contains(email)) {
614
				menus = menuRepository.selectAll();
615
			} else if (positions.size() > 0) {
616
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
617
					menus = menuRepository.selectAll();
618
				} else {
619
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
620
							.map(x -> x.getMenuId()).collect(Collectors.toList());
621
					if (menuIds.size() > 0) {
622
						menus = menuRepository.selectAllByIds(menuIds);
623
					}
624
				}
625
			}
626
 
627
			model.addAttribute("authId", authUser.getId());
628
 
629
			model.addAttribute("rctPartneStat", rctPartneStat);
630
 
631
			model.addAttribute("reporticoDate", rctSaholic);
632
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
633
			model.addAttribute("warehouseMap", wm);
634
			model.addAttribute("authUserTicketCount", authUserTicketCount);
635
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
636
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
637
 
638
			model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
639
 
640
		} catch (ProfitMandiBusinessException e) {
641
		}
642
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
643
		LOGGER.info("menu" + menuList);
644
		model.addAttribute("menu", menuList);
645
		return "admin";
646
	}
647
 
648
	private List<Menu> prepareMenu(List<Menu> menus) {
649
		List<Menu> returnMenu = new ArrayList<>();
30268 amit.gupta 650
		Map<Menu, List<Menu>> subMenuMap = new HashMap<>();
28468 tejbeer 651
		for (Menu menu : menus) {
652
			if (menu.get_parent() == null) {
653
				if (!subMenuMap.containsKey(menu)) {
654
					subMenuMap.put(menu, new ArrayList<>());
655
				}
656
			} else {
657
				Menu parentMenu = menu.get_parent();
658
				if (!subMenuMap.containsKey(parentMenu)) {
659
					subMenuMap.put(parentMenu, new ArrayList<>());
660
				}
661
				subMenuMap.get(parentMenu).add(menu);
662
			}
663
		}
664
		subMenuMap.entrySet().stream().forEach(entry -> {
665
			entry.getKey().setSubMenus(entry.getValue());
666
			returnMenu.add(entry.getKey());
667
		});
668
		return returnMenu;
669
	}
670
 
671
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
672
			throws Exception {
673
 
674
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
675
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
676
		// fofoStoreRepository.getWarehousePartnerMap();
677
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
678
		List<Integer> allfofoIds = new ArrayList<>();
679
		if (partnerStats != null) {
680
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
30246 amit.gupta 681
				List<Integer> fofoIds = warehouse.getValue().stream().collect(Collectors.toList());
28468 tejbeer 682
				allfofoIds.addAll(fofoIds);
683
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
684
						.collect(Collectors.toList());
685
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
686
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
687
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
688
				}
689
 
690
			}
691
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
692
					.collect(Collectors.toList());
693
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
694
			PartnerDetailModel partnerDetailModel = partnerStatsService
695
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
30268 amit.gupta 696
			warehouseIdAndallValues.put(0, partnerDetailModel);
28468 tejbeer 697
		}
698
		return warehouseIdAndallValues;
699
	}
700
 
701
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
702
		ObjectInputStream objectinputstream = null;
703
		Map<Integer, PartnerDetailModel> partnerStat = null;
704
		try {
705
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
706
			objectinputstream = new ObjectInputStream(streamIn);
707
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
708
 
709
			LOGGER.info("partnerStat" + partnerStat);
710
			objectinputstream.close();
711
 
712
		} catch (Exception e) {
713
			LOGGER.info("exceptionddd" + e);
714
 
715
			e.printStackTrace();
716
 
717
		} finally {
718
			if (objectinputstream != null) {
719
				objectinputstream.close();
720
				LOGGER.info("clofddd" + partnerStat);
721
 
722
			}
723
		}
724
		return partnerStat;
725
 
726
	}
727
 
728
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
729
		Map<Integer, String> warehouses = new HashMap<>();
730
		positionRetailers.stream().forEach(x -> {
731
			if (x.getWarehouseId() != 0) {
732
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
733
			}
734
		});
735
		return gson.toJson(warehouses);
736
 
737
	}
738
 
739
}