Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21615 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
25651 tejbeer 3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.FileNotFoundException;
24288 amit.gupta 6
import java.time.LocalDate;
24276 amit.gupta 7
import java.time.LocalDateTime;
24880 govind 8
import java.time.LocalTime;
25649 tejbeer 9
import java.time.ZoneOffset;
27474 tejbeer 10
import java.time.format.DateTimeFormatter;
24339 amit.gupta 11
import java.util.ArrayList;
26027 amit.gupta 12
import java.util.Arrays;
26011 amit.gupta 13
import java.util.HashMap;
26090 amit.gupta 14
import java.util.HashSet;
25136 amit.gupta 15
import java.util.LinkedHashMap;
23884 amit.gupta 16
import java.util.List;
24880 govind 17
import java.util.Map;
26055 tejbeer 18
import java.util.Map.Entry;
26071 tejbeer 19
import java.util.Optional;
26090 amit.gupta 20
import java.util.Set;
24880 govind 21
import java.util.stream.Collectors;
23568 govind 22
 
22086 amit.gupta 23
import javax.servlet.http.HttpServletRequest;
25221 amit.gupta 24
import javax.transaction.Transactional;
22086 amit.gupta 25
 
23786 amit.gupta 26
import org.apache.logging.log4j.LogManager;
23568 govind 27
import org.apache.logging.log4j.Logger;
26158 amit.gupta 28
import org.json.JSONObject;
22481 ashik.ali 29
import org.springframework.beans.factory.annotation.Autowired;
23379 ashik.ali 30
import org.springframework.beans.factory.annotation.Value;
25651 tejbeer 31
import org.springframework.core.io.InputStreamResource;
32
import org.springframework.http.HttpHeaders;
33
import org.springframework.http.HttpStatus;
25649 tejbeer 34
import org.springframework.http.ResponseEntity;
21615 kshitij.so 35
import org.springframework.stereotype.Controller;
22073 ashik.ali 36
import org.springframework.ui.Model;
21615 kshitij.so 37
import org.springframework.web.bind.annotation.RequestMapping;
38
import org.springframework.web.bind.annotation.RequestMethod;
25649 tejbeer 39
import org.springframework.web.bind.annotation.RequestParam;
21615 kshitij.so 40
 
25649 tejbeer 41
import com.google.gson.Gson;
25677 amit.gupta 42
import com.mongodb.DBObject;
25651 tejbeer 43
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 44
import com.spice.profitmandi.common.enumuration.MessageType;
26065 amit.gupta 45
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22481 ashik.ali 46
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25677 amit.gupta 47
import com.spice.profitmandi.common.model.BrandStockPrice;
26055 tejbeer 48
import com.spice.profitmandi.common.model.ChartModel;
26005 amit.gupta 49
import com.spice.profitmandi.common.model.CustomRetailer;
26055 tejbeer 50
import com.spice.profitmandi.common.model.DataModel;
51
import com.spice.profitmandi.common.model.DatasetModel;
52
import com.spice.profitmandi.common.model.LegendModel;
25649 tejbeer 53
import com.spice.profitmandi.common.model.Notification;
26055 tejbeer 54
import com.spice.profitmandi.common.model.OptionsModel;
24203 amit.gupta 55
import com.spice.profitmandi.common.model.ProfitMandiConstants;
27529 tejbeer 56
import com.spice.profitmandi.common.model.SaholicInventoryCIsModel;
26055 tejbeer 57
import com.spice.profitmandi.common.model.TitleModel;
25651 tejbeer 58
import com.spice.profitmandi.common.web.util.ResponseSender;
25649 tejbeer 59
import com.spice.profitmandi.dao.Interface.Campaign;
26011 amit.gupta 60
import com.spice.profitmandi.dao.entity.auth.AuthUser;
61
import com.spice.profitmandi.dao.entity.auth.Menu;
27355 tejbeer 62
import com.spice.profitmandi.dao.entity.catalog.Item;
26674 tejbeer 63
import com.spice.profitmandi.dao.entity.catalog.Offer;
64
import com.spice.profitmandi.dao.entity.catalog.OfferPartner;
65
import com.spice.profitmandi.dao.entity.catalog.Offermargin;
26011 amit.gupta 66
import com.spice.profitmandi.dao.entity.cs.Position;
25651 tejbeer 67
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 68
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
22654 ashik.ali 69
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24288 amit.gupta 70
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25214 amit.gupta 71
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
25566 tejbeer 72
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
27474 tejbeer 73
import com.spice.profitmandi.dao.entity.fofo.PartnerTypeChange;
27529 tejbeer 74
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
75
import com.spice.profitmandi.dao.entity.inventory.SaholicInventoryCIS;
26418 tejbeer 76
import com.spice.profitmandi.dao.entity.user.Lead;
27355 tejbeer 77
import com.spice.profitmandi.dao.enumuration.catalog.ItemCriteriaType;
26024 amit.gupta 78
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26418 tejbeer 79
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
26674 tejbeer 80
import com.spice.profitmandi.dao.model.CreateOfferRequest;
27355 tejbeer 81
import com.spice.profitmandi.dao.model.ItemTypeParams;
27474 tejbeer 82
import com.spice.profitmandi.dao.model.MonthSaleModel;
26418 tejbeer 83
import com.spice.profitmandi.dao.model.PartnerDetailModel;
25649 tejbeer 84
import com.spice.profitmandi.dao.model.SimpleCampaign;
85
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
27509 tejbeer 86
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
87
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
88
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
25976 amit.gupta 89
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26011 amit.gupta 90
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
91
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
27355 tejbeer 92
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
26588 tejbeer 93
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
94
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
95
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
26090 amit.gupta 96
import com.spice.profitmandi.dao.repository.cs.CsService;
26418 tejbeer 97
import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;
26011 amit.gupta 98
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
99
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
26418 tejbeer 100
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
25651 tejbeer 101
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22481 ashik.ali 102
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26418 tejbeer 103
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
24996 amit.gupta 104
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25649 tejbeer 105
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
106
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
107
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
24203 amit.gupta 108
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24880 govind 109
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
26071 tejbeer 110
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
25649 tejbeer 111
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
26234 amit.gupta 112
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24288 amit.gupta 113
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
25214 amit.gupta 114
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
27474 tejbeer 115
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
25566 tejbeer 116
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
27529 tejbeer 117
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
118
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
27509 tejbeer 119
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
24336 amit.gupta 120
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 121
import com.spice.profitmandi.service.PartnerStatsService;
23844 amit.gupta 122
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 123
import com.spice.profitmandi.service.inventory.InventoryService;
26005 amit.gupta 124
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 125
import com.spice.profitmandi.web.model.LoginDetails;
126
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 127
import com.spice.profitmandi.web.util.MVCResponseSender;
22481 ashik.ali 128
 
21615 kshitij.so 129
@Controller
25222 amit.gupta 130
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 131
public class DashboardController {
23923 amit.gupta 132
 
26460 amit.gupta 133
	private static final double ONE_LAC = 1 * 1000 * 100;
134
	private static final double TWO_LAC = 2 * 1000 * 100;
135
	private static final double FOUR_LAC = 4 * 1000 * 100;
136
 
23379 ashik.ali 137
	@Value("${web.api.host}")
138
	private String webApiHost;
23923 amit.gupta 139
 
24072 amit.gupta 140
	@Value("${web.api.scheme}")
141
	private String webApiScheme;
24288 amit.gupta 142
 
24078 amit.gupta 143
	@Value("${web.api.root}")
144
	private String webApiRoot;
145
 
23379 ashik.ali 146
	@Value("${web.api.port}")
147
	private int webApiPort;
21615 kshitij.so 148
 
22481 ashik.ali 149
	@Autowired
22927 ashik.ali 150
	private CookiesProcessor cookiesProcessor;
26468 amit.gupta 151
 
26460 amit.gupta 152
	@Autowired
153
	private PartnerStatsService partnerStatsService;
23923 amit.gupta 154
 
23568 govind 155
	@Autowired
26011 amit.gupta 156
	private MenuRepository menuRepository;
26012 amit.gupta 157
 
26011 amit.gupta 158
	@Autowired
159
	private MenuCategoryRepository menuCategoryRepository;
160
 
161
	@Autowired
26090 amit.gupta 162
	private CsService csService;
163
 
164
	@Autowired
25214 amit.gupta 165
	private PartnerTargetRepository partnerTargetRepository;
166
 
167
	@Autowired
25653 amit.gupta 168
	private ResponseSender<?> responseSender;
26012 amit.gupta 169
 
26005 amit.gupta 170
	@Autowired
171
	RetailerService retailerService;
25214 amit.gupta 172
 
173
	@Autowired
23786 amit.gupta 174
	private RoleManager roleManager;
23923 amit.gupta 175
 
23838 ashik.ali 176
	@Autowired
177
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 178
 
179
	@Autowired
24880 govind 180
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
23923 amit.gupta 181
 
23884 amit.gupta 182
	@Autowired
24880 govind 183
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 184
 
23884 amit.gupta 185
	@Autowired
25653 amit.gupta 186
	DocumentRepository documentRepository;
26236 amit.gupta 187
 
26234 amit.gupta 188
	@Autowired
189
	InventoryItemRepository inventoryItemRepository;
25683 tejbeer 190
 
25677 amit.gupta 191
	@Autowired
192
	InventoryService inventoryService;
23923 amit.gupta 193
 
23884 amit.gupta 194
	@Autowired
24203 amit.gupta 195
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
196
 
24880 govind 197
	@Autowired
198
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 199
 
26011 amit.gupta 200
	@Autowired
201
	private TicketCategoryRepository ticketCategoryRepository;
24880 govind 202
 
203
	@Autowired
25566 tejbeer 204
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 205
 
24996 amit.gupta 206
	@Autowired
25649 tejbeer 207
	private HygieneDataRepository hygieneDataRepository;
208
 
209
	@Autowired
210
	private UserCampaignRepository userCampaignRepository;
26012 amit.gupta 211
 
26011 amit.gupta 212
	@Autowired
213
	private PositionRepository positionRepository;
27474 tejbeer 214
	@Autowired
215
	private PartnerTypeChangeRepository partnerTypeChangeRepository;
25649 tejbeer 216
 
217
	@Autowired
26418 tejbeer 218
	private PartnersPositionRepository partnerPositionRepository;
219
 
220
	@Autowired
25649 tejbeer 221
	private UserAccountRepository userAccountRepository;
222
 
223
	@Autowired
224
	private NotificationCampaignRepository notificationCampaignRepository;
225
 
226
	@Autowired
24996 amit.gupta 227
	private Mongo mongoClient;
26012 amit.gupta 228
 
25976 amit.gupta 229
	@Autowired
230
	private AuthRepository authRepository;
24880 govind 231
 
25649 tejbeer 232
	@Autowired
26071 tejbeer 233
	private FofoOrderRepository fofoOrderRepository;
234
 
235
	@Autowired
25649 tejbeer 236
	private Gson gson;
237
 
26418 tejbeer 238
	@Autowired
239
	TicketRepository ticketRepository;
240
 
241
	@Autowired
242
	private LeadRepository leadRepository;
243
 
26588 tejbeer 244
	@Autowired
245
	private OfferRepository offerRepository;
246
 
247
	@Autowired
248
	private OfferPartnerRepository offerPartnerRepository;
249
 
250
	@Autowired
251
	private OfferMarginRepository offerMarginRepository;
27529 tejbeer 252
 
27355 tejbeer 253
	@Autowired
254
	private ItemRepository itemRepository;
26588 tejbeer 255
 
27509 tejbeer 256
	@Autowired
257
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
27529 tejbeer 258
 
259
	@Autowired
260
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
261
 
262
	@Autowired
263
	private MVCResponseSender mvcResponseSender;
264
 
265
	@Autowired
266
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
267
 
23568 govind 268
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 269
 
25136 amit.gupta 270
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 271
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 272
		boolean isAdmin = false;
273
		model.addAttribute("isAdmin", isAdmin);
274
 
275
		model.addAttribute("webApiHost", webApiHost);
276
		model.addAttribute("webApiPort", webApiPort);
277
		model.addAttribute("webApiScheme", webApiScheme);
278
		model.addAttribute("webApiRoot", webApiRoot);
279
		if (isAdmin) {
280
			return "dashboard1";
26236 amit.gupta 281
		}
282
 
283
		FofoStore fofoStore = null;
26234 amit.gupta 284
		try {
285
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
286
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
287
			if (!fofoStore.isActive()) {
288
				return "redirect:/login";
289
			}
25740 amit.gupta 290
 
26234 amit.gupta 291
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
292
			model.addAttribute("partnerType", partnerType);
293
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
294
			model.addAttribute("fofoStore", customRetailer);
295
			model.addAttribute("partnerType", partnerType);
296
			model.addAttribute("hasGift", hasGift(fofoId));
297
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 298
 
26234 amit.gupta 299
			model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
300
			model.addAttribute("salesMap", this.getSales(fofoId));
301
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
302
			// this.setInvestments
303
			//
304
			model.addAttribute("investments", this.getInvestments(fofoId));
305
			model.addAttribute("isInvestmentOk",
306
					partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
307
		} catch (ProfitMandiBusinessException e) {
308
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 309
 
310
		}
311
 
312
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
313
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
26012 amit.gupta 314
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)
315
				/ 2;
316
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
317
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
25740 amit.gupta 318
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
319
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
320
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
321
 
26012 amit.gupta 322
		long hygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, true, currentMonthStart, currentMonthEnd);
323
 
324
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,
25740 amit.gupta 325
				currentMonthEnd);
326
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
327
			invalidHygieneCount = 1;
328
		}
329
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
26460 amit.gupta 330
 
25740 amit.gupta 331
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
332
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
333
		return "12dashboard34";
25136 amit.gupta 334
	}
335
 
336
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
337
		Map<String, Object> investments = new LinkedHashMap<>();
26233 amit.gupta 338
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
25649 tejbeer 339
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
25136 amit.gupta 340
		LocalDate yesterDate = LocalDate.now().minusDays(1);
341
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
342
		if (yesterdayInvestment == null) {
343
			yesterdayInvestment = new PartnerDailyInvestment();
344
		}
345
 
346
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
347
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
348
 
25140 amit.gupta 349
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
25136 amit.gupta 350
				.collect(Collectors.counting());
25140 amit.gupta 351
		investments.put("today", investment.getTotalInvestment());
352
		investments.put("investment", investment);
353
		investments.put("inStock", investment.getInStockAmount());
25182 amit.gupta 354
		investments.put("minimum", investment.getMinInvestmentString());
25140 amit.gupta 355
		investments.put("short", investment.getShortPercentage());
26267 amit.gupta 356
		investments.put("activated_stock", investment.getActivatedStockAmount());
25649 tejbeer 357
		investments.put("okDays", okInvestmentDays);
25136 amit.gupta 358
		return investments;
359
	}
360
 
25221 amit.gupta 361
	private Map<String, Object> getSales(int fofoId) {
25653 amit.gupta 362
 
25221 amit.gupta 363
		Map<String, Object> salesMap = new LinkedHashMap<>();
25140 amit.gupta 364
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
25214 amit.gupta 365
		int monthLength = LocalDate.now().lengthOfMonth();
26012 amit.gupta 366
		Double todaySale = fofoOrderItemRepository
27084 amit.gupta 367
				.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
26012 amit.gupta 368
		Double mtdSale = fofoOrderItemRepository
27084 amit.gupta 369
				.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false)
26012 amit.gupta 370
				.get(fofoId);
27352 tejbeer 371
		Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
372
				curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);
25214 amit.gupta 373
 
374
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
375
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 376
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 377
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 378
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 379
		}
25214 amit.gupta 380
 
25653 amit.gupta 381
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 382
 
25664 amit.gupta 383
		int currentRate = (int) (mtdSale / curDate.getDayOfMonth());
25653 amit.gupta 384
 
385
		salesMap.put("requiredType", partnerType.next());
386
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
387
		int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
388
		salesMap.put("requiredRate", requiredRate);
389
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
390
 
25858 amit.gupta 391
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
392
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 393
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 394
 
27352 tejbeer 395
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
25653 amit.gupta 396
		salesMap.put("currentRate", currentRate);
397
		salesMap.put("currentType", currentType);
398
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 399
		return salesMap;
400
	}
401
 
27474 tejbeer 402
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
403
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
404
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
405
		int fofoId = loginDetails.getFofoId();
406
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
407
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
408
		int dayOfMonth = curDate.getDayOfMonth();
409
		for (int i = 1; i <= 6; i++) {
410
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
411
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
412
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
413
 
414
			double mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
415
					startOfMonth.plusDays(dayOfMonth), loginDetails.getFofoId(), false).get(fofoId);
416
 
417
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
418
 
419
			MonthSaleModel ms = new MonthSaleModel();
420
			ms.setMtdSales(this.format((long) mtdSales));
421
			ms.setMonthlySales(this.format(((long) monthSales)));
422
			ms.setPartnerType(partnerType);
27476 tejbeer 423
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
27474 tejbeer 424
			monthSaleMap.put(i, ms);
425
 
426
		}
427
		model.addAttribute("monthSales", monthSaleMap);
428
		return "monthSales";
429
	}
430
 
431
	private String format(long value) {
432
		String finalval = null;
433
 
434
		if (value >= 100000 && value < 10000000) {
435
			long reminder = value / 100000;
436
			long quitonent = value % 100000;
437
			finalval = reminder + "." + quitonent;
438
			String secondval = String.valueOf(quitonent);
439
			if (secondval.length() >= 2) {
440
				secondval = secondval.substring(0, 2);
441
				finalval = reminder + "." + secondval;
442
			}
443
			return String.valueOf(finalval) + " Lacs";
444
		} else if (value >= 1000 && value < 100000) {
445
			long reminder = value / 1000;
446
			long quitonent = value % 1000;
447
			finalval = reminder + "." + quitonent;
448
			String secondval = String.valueOf(quitonent);
449
			if (secondval.length() >= 2) {
450
				secondval = secondval.substring(0, 2);
451
				finalval = reminder + "." + secondval;
452
			}
453
			return String.valueOf(finalval) + " K";
454
		} else if (value >= 10000000 && value < 1000000000) {
455
			long reminder = value / 10000000;
456
			long quitonent = value % 10000000;
457
			finalval = reminder + "." + quitonent;
458
			String secondval = String.valueOf(quitonent);
459
			if (secondval.length() >= 2) {
460
				secondval = secondval.substring(0, 2);
461
				finalval = reminder + "." + secondval;
462
			}
463
			return String.valueOf(finalval) + " Cr";
464
		}
465
		return String.valueOf(finalval);
466
 
467
	}
468
 
25677 amit.gupta 469
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
470
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 471
 
26309 amit.gupta 472
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
25677 amit.gupta 473
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
474
 
475
		mobileBrands.stream().forEach(x -> {
476
			String brand = (String) x.get("name");
477
			if (brandStockPricesMap.containsKey(brand)) {
478
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
479
				brandStockPrice.setBrandUrl((String) x.get("url"));
480
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
481
				brandStockPrices.add(brandStockPrice);
482
			}
483
		});
484
 
485
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
486
				.collect(Collectors.toList());
487
	}
488
 
21615 kshitij.so 489
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 490
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 491
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 492
		String email = loginDetails.getEmailId();
25180 amit.gupta 493
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
494
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 495
 
25274 amit.gupta 496
		model.addAttribute("webApiHost", webApiHost);
497
		model.addAttribute("webApiPort", webApiPort);
498
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 499
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 500
		if (isAdmin) {
26011 amit.gupta 501
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 502
		} else {
25740 amit.gupta 503
			FofoStore fofoStore = null;
25180 amit.gupta 504
			try {
505
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 506
				if (!fofoStore.isActive()) {
507
					return "redirect:/login";
508
				}
25649 tejbeer 509
 
25740 amit.gupta 510
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 511
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 512
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 513
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 514
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 515
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
516
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 517
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 518
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 519
				model.addAttribute("activatedImeis",
520
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
26071 tejbeer 521
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
522
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
523
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
524
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
525
				LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
526
				Double accesoriesStock = currentInventorySnapshotRepository
527
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
528
								Optional.of(false))
529
						.get(loginDetails.getFofoId());
25180 amit.gupta 530
 
26071 tejbeer 531
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
26065 amit.gupta 532
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 533
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 534
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
535
 
536
				LOGGER.info("chartMap" + gson.toJson(cm));
537
				model.addAttribute("chartMap", gson.toJson(cm));
25544 amit.gupta 538
				// this.setInvestments
539
				//
25180 amit.gupta 540
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 541
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
542
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 543
 
544
				// Hardcoded for valentine
545
				// Hardcoded for valentine
26588 tejbeer 546
 
26694 tejbeer 547
				List<Offer> offers = offerRepository.selectOfferByStatus(true);
26588 tejbeer 548
				if (!offers.isEmpty()) {
549
					List<CreateOfferRequest> cors = new ArrayList<>();
550
					for (Offer offer : offers) {
551
 
552
						List<OfferPartner> offerPartners = offerPartnerRepository.selectByOfferId(offer.getId());
553
 
554
						for (OfferPartner offerPartner : offerPartners) {
555
 
556
							if (offerPartner.getFofoId() == loginDetails.getFofoId()) {
27352 tejbeer 557
								/*
558
								 * if (LocalDateTime.now().isAfter(offer.getStartDateTime()) &&
559
								 * LocalDateTime.now().isBefore(offer.getEndDateTime())) {
560
								 */
27398 tejbeer 561
								int todayMonth = LocalDateTime.now().getMonthValue();
562
								if (todayMonth == offer.getStartDateTime().getMonthValue()
563
										|| todayMonth == offer.getEndDateTime().getMonthValue()) {
26674 tejbeer 564
									LocalDateTime cur = LocalDate.now().minusMonths(2).atStartOfDay();
26619 tejbeer 565
									LOGGER.info("value" + cur);
26588 tejbeer 566
									Map<Integer, Double> value = offerRepository.selectSumOfferByRetailer(
26675 tejbeer 567
											offer.getStartDateTime(), offer.getEndDateTime(), loginDetails.getFofoId(),
568
											offer, true);
26588 tejbeer 569
									CreateOfferRequest createOfferRequest = new CreateOfferRequest();
570
									List<Offermargin> offerMargins = offerMarginRepository
571
											.selectByOfferId(offer.getId());
572
									LOGGER.info("value" + offer.getId());
573
									LOGGER.info("value" + value);
574
									for (Offermargin om : offerMargins) {
26619 tejbeer 575
										if (value.get(loginDetails.getFofoId()) <= om.getValue()) {
26588 tejbeer 576
											createOfferRequest.setMargin(om.getMargin());
26694 tejbeer 577
											createOfferRequest.setValue(om.getValue());
26588 tejbeer 578
											createOfferRequest.setShortAmount(
579
													om.getValue() - value.get(loginDetails.getFofoId()));
26674 tejbeer 580
 
26588 tejbeer 581
											break;
582
										} else {
583
											createOfferRequest.setMargin(om.getMargin());
26675 tejbeer 584
 
26588 tejbeer 585
										}
586
 
587
									}
27360 tejbeer 588
									createOfferRequest.setId(offer.getId());
26588 tejbeer 589
 
590
									createOfferRequest.setName(offer.getName());
591
									createOfferRequest.setDescription(offer.getDescription());
592
									createOfferRequest.setTargetType(offer.getTargetType());
593
									createOfferRequest.setAmountType(offer.getAmountType());
26694 tejbeer 594
									createOfferRequest.setStartDateTime(offer.getStartDateTime().toLocalDate());
595
									createOfferRequest.setEndDateTime(offer.getEndDateTime().toLocalDate());
26588 tejbeer 596
									createOfferRequest.setTotalSale(value.get(loginDetails.getFofoId()));
27352 tejbeer 597
									createOfferRequest.setOfferMargin(offerMargins);
26588 tejbeer 598
									cors.add(createOfferRequest);
599
 
600
									model.addAttribute("sales", value.get(loginDetails.getFofoId()));
601
								}
602
							}
603
 
604
						}
26327 amit.gupta 605
					}
26588 tejbeer 606
					model.addAttribute("offers", cors);
607
 
26674 tejbeer 608
				}
26588 tejbeer 609
 
25180 amit.gupta 610
			} catch (ProfitMandiBusinessException e) {
611
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
612
 
613
			}
22481 ashik.ali 614
		}
25649 tejbeer 615
 
616
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 617
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 618
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
619
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 620
				currentMonthEnd) / 2;
25747 amit.gupta 621
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
622
				currentMonthStart) / 2;
623
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 624
				currentMonthEnd) / 2;
625
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
626
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
627
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 628
 
25653 amit.gupta 629
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
630
				currentMonthEnd);
25651 tejbeer 631
 
25653 amit.gupta 632
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
633
				currentMonthStart, currentMonthEnd);
634
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
635
			invalidHygieneCount = 1;
636
		}
637
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 638
 
25197 amit.gupta 639
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
640
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27352 tejbeer 641
		if (loginDetails.isReadOnly()) {
27229 amit.gupta 642
			return "dashboard-readonly";
643
		} else {
644
			return "dashboard1";
645
		}
21615 kshitij.so 646
	}
23923 amit.gupta 647
 
27355 tejbeer 648
	@RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
649
	public String getOfferMargins(HttpServletRequest request,
650
			@RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
651
		Offer offer = offerRepository.selectById(offerId);
652
 
653
		LOGGER.info("offerId" + offer.getId());
654
 
655
		Map<Integer, Double> value = offerRepository.selectSumOfferByRetailer(offer.getStartDateTime(),
656
				offer.getEndDateTime(), 0, offer, true);
657
 
658
		LOGGER.info("value" + value);
659
		List<Offermargin> offerMargin = offerMarginRepository.selectByOfferId(offerId);
660
 
661
		ItemTypeParams scp = gson.fromJson(offer.getItemParam(), ItemTypeParams.class);
662
		if (offer.getItemCriteria().equals(ItemCriteriaType.Multiple_Brand)) {
663
			List<String> brands = scp.getBrands();
664
			model.addAttribute("brands", brands);
665
		}
666
		if (offer.getItemCriteria().equals(ItemCriteriaType.Item_Model)) {
667
			List<Integer> catalogIds = scp.getCatalogId();
668
			List<Item> newList = new ArrayList<>();
669
			Set<Integer> catalogId = new HashSet<>();
670
			List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds.stream().collect(Collectors.toSet()));
671
			for (Item item : items) {
672
				if (catalogId.add(item.getCatalogItemId())) {
673
					newList.add(item);
674
				}
675
			}
676
			model.addAttribute("items", newList);
677
		}
678
 
679
		model.addAttribute("offerMargin", offerMargin);
680
		model.addAttribute("offer", offer);
681
 
682
		return "offer_margin_detail_partner";
683
 
684
	}
685
 
26055 tejbeer 686
	private ChartModel getBrandChart(int fofoId) {
687
 
688
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
689
 
690
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
691
 
692
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
693
 
694
		Map<String, Double> brandwisesale = fofoOrderItemRepository
695
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 696
 
697
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
698
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
699
 
700
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
701
 
26055 tejbeer 702
		LOGGER.info("brandwisesale" + brandwisesale);
703
 
704
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
705
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
706
 
26244 tejbeer 707
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
708
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
709
				Optional.of(false));
710
		LOGGER.info("accesorieslmtdsale" + accesorieslmtdsale);
26055 tejbeer 711
		ChartModel cm = new ChartModel();
712
 
713
		List<String> labels = new ArrayList<>();
714
		labels.addAll(brandwisesale.keySet());
26244 tejbeer 715
		labels.add("accessories");
26055 tejbeer 716
		List<Double> values = new ArrayList<>();
717
		values.addAll(brandwisesale.values());
26244 tejbeer 718
		values.addAll(accesoriesmtdsale.values());
26055 tejbeer 719
 
720
		List<Double> lmtdValues = new ArrayList<>();
721
		lmtdValues.addAll(lmtdBrandWiseSale.values());
26244 tejbeer 722
		lmtdValues.addAll(accesorieslmtdsale.values());
26055 tejbeer 723
 
724
		DatasetModel dsm = new DatasetModel();
725
		dsm.setLabel("mtd sales");
726
 
727
		List<String> backgroundColor = new ArrayList<>();
728
		for (Entry<String, Double> bs : brandwisesale.entrySet()) {
729
			backgroundColor.add("#3e95cd");
730
		}
26244 tejbeer 731
		backgroundColor.add("#3e95cd");
26055 tejbeer 732
		dsm.setBackgroundColor(backgroundColor);
733
		dsm.setData(values);
734
 
735
		DatasetModel lmtddsm = new DatasetModel();
736
		lmtddsm.setLabel("lmtd sales");
737
 
738
		List<String> background = new ArrayList<>();
739
		for (Entry<String, Double> bs : lmtdBrandWiseSale.entrySet()) {
740
			background.add("#8e5ea2");
741
		}
26244 tejbeer 742
		background.add("#8e5ea2");
26055 tejbeer 743
		lmtddsm.setBackgroundColor(background);
744
		lmtddsm.setData(lmtdValues);
745
 
746
		List<DatasetModel> datasets = new ArrayList<>();
747
		datasets.add(dsm);
748
		datasets.add(lmtddsm);
749
 
750
		DataModel dm = new DataModel();
751
		dm.setDatasets(datasets);
752
		dm.setLabels(labels);
753
 
754
		LegendModel lm = new LegendModel();
755
		lm.setDisplay(true);
756
 
757
		TitleModel tm = new TitleModel();
758
		tm.setText("Brand Wise Sale Graph");
759
		tm.setDisplay(true);
760
 
761
		OptionsModel om = new OptionsModel();
762
		om.setLegend(lm);
763
		om.setTitle(tm);
764
 
765
		cm.setType("bar");
766
		cm.setData(dm);
767
		cm.setOptions(om);
768
 
769
		return cm;
770
 
771
	}
772
 
26418 tejbeer 773
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 774
		List<Menu> menus = null;
26011 amit.gupta 775
		try {
776
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
777
			List<Position> positions = positionRepository.selectAll(authUser.getId());
26418 tejbeer 778
			Map<Integer, AuthUser> authIdAndAuthUserMap = null;
27529 tejbeer 779
			ReporticoCacheTable rct = null;
27509 tejbeer 780
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
781
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
26460 amit.gupta 782
			Map<Integer, PartnerDetailModel> authIdAndallValues = null;
26418 tejbeer 783
			if (positions.size() > 0) {
27352 tejbeer 784
				if (positions.stream()
785
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
786
								|| x.getEscalationType().equals(EscalationType.L4)
787
								|| x.getEscalationType().equals(EscalationType.L5))
788
						.count() > 0) {
26418 tejbeer 789
 
790
					authIdAndAuthUserMap = authRepository.selectAllActiveUser().stream()
791
							.collect(Collectors.toMap(x -> x.getId(), x -> x));
26588 tejbeer 792
 
26997 amit.gupta 793
					AuthUser unmappedAuthUser = new AuthUser();
794
					unmappedAuthUser.setFirstName("Unmapped");
795
					unmappedAuthUser.setLastName("Partners");
26999 amit.gupta 796
					authIdAndAuthUserMap.put(-1, unmappedAuthUser);
26997 amit.gupta 797
 
26468 amit.gupta 798
					AuthUser dummyAuthUser = new AuthUser();
799
					dummyAuthUser.setFirstName("Total");
800
					dummyAuthUser.setLastName("Values");
801
					authIdAndAuthUserMap.put(0, dummyAuthUser);
27529 tejbeer 802
 
803
					warehouseStockMap = saholicInventoryCISRepository.selectGroupByWarehouse().stream()
27509 tejbeer 804
							.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
27352 tejbeer 805
 
27529 tejbeer 806
					rct = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
27509 tejbeer 807
					LOGGER.info("warehouseStockMap" + warehouseStockMap);
27529 tejbeer 808
 
26422 tejbeer 809
					authIdAndallValues = this.getL2AuthUserPartnerDetail();
26418 tejbeer 810
				}
811
			}
812
 
27415 tejbeer 813
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
814
					.contains(email)) {
26029 amit.gupta 815
				menus = menuRepository.selectAll();
816
			} else if (positions.size() > 0) {
27108 amit.gupta 817
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 818
					menus = menuRepository.selectAll();
819
				} else {
820
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
821
							.map(x -> x.getMenuId()).collect(Collectors.toList());
822
					LOGGER.info("Menu Ids are {}", menuIds);
823
					if (menuIds.size() > 0) {
824
						menus = menuRepository.selectAllByIds(menuIds);
825
					}
26022 amit.gupta 826
				}
26090 amit.gupta 827
				List<Position> salesPositions = positions.stream()
828
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
829
						.collect(Collectors.toList());
830
				if (salesPositions.size() > 0) {
831
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 832
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 833
						positionRetailers.addAll(customRetailers);
834
					});
835
					model.addAttribute("retailers", gson.toJson(positionRetailers));
836
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 837
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 838
				}
26114 amit.gupta 839
				List<Position> warehousePositions = positions.stream()
840
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
841
						.collect(Collectors.toList());
842
				if (warehousePositions.size() > 0) {
843
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 844
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 845
						positionRetailers.addAll(customRetailers);
846
					});
847
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
848
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 849
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 850
				}
26142 amit.gupta 851
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 852
 
26022 amit.gupta 853
			}
27529 tejbeer 854
			model.addAttribute("reporticoDate", rct);
26418 tejbeer 855
			model.addAttribute("authIdAndallValues", authIdAndallValues);
856
			model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
27509 tejbeer 857
			model.addAttribute("warehouseMap", warehouseMap);
858
			model.addAttribute("warehouseStockMap", warehouseStockMap);
26012 amit.gupta 859
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 860
		}
26028 amit.gupta 861
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 862
		LOGGER.info("menu" + menuList);
26022 amit.gupta 863
		model.addAttribute("menu", menuList);
26012 amit.gupta 864
		return "admin";
865
	}
866
 
26468 amit.gupta 867
	/*
868
	 * @RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET) public
869
	 * String L1AuthUsersDetail(HttpServletRequest request, Model
870
	 * model, @RequestParam int authId) throws Exception {
871
	 * 
872
	 * Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
873
	 * 
874
	 * LocalDateTime curDate = LocalDate.now().atStartOfDay(); Map<Integer, Double>
875
	 * lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
876
	 * curDate.withDayOfMonth(1).minusMonths(1),
877
	 * curDate.with(LocalTime.MAX).minusMonths(1), 0, false); Map<Integer, Double>
878
	 * mtdSale =
879
	 * fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth
880
	 * (1), curDate.with(LocalTime.MAX), 0, false); Map<Integer, List<Integer>>
881
	 * L2L1Mapping = csService.getL1L2Mapping();
882
	 * 
883
	 * LOGGER.info("L2L1Mapping" + L2L1Mapping); List<Integer> l1authIds =
884
	 * L2L1Mapping.get(authId);
885
	 * 
886
	 * Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>(); Map<Integer,
887
	 * Object> authIdAndAuthUserMap = new LinkedHashMap<>();
888
	 * 
889
	 * Map<Integer, Long> ticketMap =
890
	 * ticketRepository.selectAllNotClosedTicketsGroupByRetailer(); for (Integer
891
	 * l1AuthId : l1authIds) {
892
	 * 
893
	 * double totallmtdAmount = 0; double totalmtdAmount = 0; int totalTicketCount =
894
	 * 0; float totalTodayInvestment = 0; float totalStockInInvestment = 0; double
895
	 * currentMonthRatingAllPartners = 0; Map<Integer, Long> leadCount =
896
	 * leadRepository.selectByAssignAuthIdAndStatus(l1AuthId, LeadStatus.followUp)
897
	 * .stream().collect(Collectors.groupingBy(Lead::getAssignTo,
898
	 * Collectors.counting()));
899
	 * 
900
	 * AuthUser authUser = authRepository.selectById(l1AuthId);
901
	 * 
902
	 * authIdAndAuthUserMap.put(l1AuthId, authUser);
903
	 * 
904
	 * List<Integer> fofoIds = pp.get(l1AuthId);
905
	 * 
906
	 * Map<Integer, PartnerDailyInvestment> partnerInvestentMap =
907
	 * partnerInvestmentService .getInvestment(fofoIds,
908
	 * 0).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
909
	 * 
910
	 * for (Integer fId : fofoIds) { try { PartnerDailyInvestment investment =
911
	 * partnerInvestentMap.get(fId); totalTodayInvestment +=
912
	 * investment.getTotalInvestment(); totalStockInInvestment +=
913
	 * investment.getInStockAmount(); } catch (Exception e) { }
914
	 * 
915
	 * double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
916
	 * curDate.withDayOfMonth(1).minusMonths(1),
917
	 * curDate.plusMonths(1).withDayOfMonth(1));
918
	 * 
919
	 * currentMonthRatingAllPartners += currentMonthRating;
920
	 * 
921
	 * fofoIds.size();
922
	 * 
923
	 * Double lmtdAmount = lmtdSale.get(fId); Double mtdAmount = mtdSale.get(fId);
924
	 * Long ticketCount = ticketMap.get(fId); if (ticketCount != null) {
925
	 * totalTicketCount += ticketCount; }
926
	 * 
927
	 * if (lmtdAmount != null) { totallmtdAmount += lmtdAmount; }
928
	 * 
929
	 * if (mtdAmount != null) { totalmtdAmount += mtdAmount; }
930
	 * 
931
	 * } LOGGER.info("currentMonthRatingAllPartners" +
932
	 * currentMonthRatingAllPartners); LOGGER.info("size" + fofoIds.size()); double
933
	 * totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
934
	 * 
935
	 * LOGGER.info("totalHygieneRating" + totalHygieneRating);
936
	 * 
937
	 * PartnerDetailModel pm = new PartnerDetailModel();
938
	 * pm.setLmtd(totallmtdAmount); pm.setMtd(totalmtdAmount); if
939
	 * (leadCount.get(l1AuthId) != null) {
940
	 * pm.setLeads(leadCount.get(l1AuthId).intValue()); } else { pm.setLeads(0); }
941
	 * 
942
	 * pm.setInvestment(totalTodayInvestment);
943
	 * pm.setStockInInvestment(totalStockInInvestment);
944
	 * pm.setTicket(totalTicketCount); pm.setHygiene((double)
945
	 * Math.round(totalHygieneRating)); authIdAndallValues.put(l1AuthId, pm);
946
	 * 
947
	 * } model.addAttribute("authIdAndallValues", authIdAndallValues);
948
	 * model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
949
	 * LOGGER.info("authIdAndallValues" + authIdAndallValues);
950
	 * 
951
	 * return "auth_user_detail"; }
952
	 */
26418 tejbeer 953
 
26468 amit.gupta 954
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 955
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
956
			throws Exception {
957
 
958
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 959
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 960
 
26468 amit.gupta 961
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
962
		if (authId != 0) {
963
			List<Integer> fofoIds = pp.get(authId);
964
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
965
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 966
		} else {
26418 tejbeer 967
		}
968
 
969
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
970
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
971
 
972
		return "auth_user_partner_detail";
26468 amit.gupta 973
	}
26418 tejbeer 974
 
27509 tejbeer 975
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
976
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model, @RequestParam int warehouseId)
977
			throws Exception {
978
 
27529 tejbeer 979
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = saholicInventoryCISRepository
27509 tejbeer 980
				.selectGroupByWarehouseAndBrand(warehouseId);
981
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
982
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
983
		model.addAttribute("warehouseMap", warehouseMap);
984
		LOGGER.info("warehouseWiseBrandStock" + warehouseWiseBrandStock);
985
		return "warehouse_brand_stock";
986
	}
987
 
27529 tejbeer 988
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
989
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
990
		inventoryService.getItemAvailabilityAndIndent();
991
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
992
		return "response";
993
	}
994
 
27509 tejbeer 995
	@RequestMapping(value = "/getWarehouseWiseBrandItemStock", method = RequestMethod.GET)
996
	public String getWarehouseWiseBrandItemStock(HttpServletRequest request, Model model, @RequestParam int warehouseId,
27529 tejbeer 997
			@RequestParam List<String> brands) throws Exception {
27509 tejbeer 998
 
27529 tejbeer 999
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1000
				.selectWarehouseItemStock(warehouseId, brands);
27509 tejbeer 1001
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1002
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27509 tejbeer 1003
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1004
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1005
		model.addAttribute("warehouseId", warehouseId);
1006
		model.addAttribute("brands", listbrands);
1007
		model.addAttribute("selectedBrand", brands);
27509 tejbeer 1008
		LOGGER.info("warehouseWiseItemStock" + warehouseWiseItemStock);
1009
		return "warehouse_brand_item_stock";
1010
	}
1011
 
26114 amit.gupta 1012
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1013
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1014
		positionRetailers.stream().forEach(x -> {
1015
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1016
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1017
			}
1018
		});
26114 amit.gupta 1019
		return gson.toJson(warehouses);
1020
 
1021
	}
1022
 
26012 amit.gupta 1023
	private List<Menu> prepareMenu(List<Menu> menus) {
1024
		List<Menu> returnMenu = new ArrayList<>();
1025
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1026
		for (Menu menu : menus) {
1027
			if (menu.get_parent() == null) {
26014 amit.gupta 1028
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1029
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1030
				}
1031
			} else {
26012 amit.gupta 1032
				Menu parentMenu = menu.get_parent();
1033
				if (!subMenuMap.containsKey(parentMenu)) {
1034
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1035
				}
26012 amit.gupta 1036
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1037
			}
1038
		}
26012 amit.gupta 1039
		subMenuMap.entrySet().stream().forEach(entry -> {
1040
			entry.getKey().setSubMenus(entry.getValue());
1041
			returnMenu.add(entry.getKey());
1042
		});
1043
		return returnMenu;
26005 amit.gupta 1044
	}
1045
 
24288 amit.gupta 1046
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1047
	private boolean hasGift(int fofoId) {
1048
		try {
24288 amit.gupta 1049
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1050
					.getAvailability() > 0;
24203 amit.gupta 1051
		} catch (ProfitMandiBusinessException e) {
1052
			return false;
1053
		}
1054
	}
24288 amit.gupta 1055
 
22354 ashik.ali 1056
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1057
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1058
		model.addAttribute("appContextPath", request.getContextPath());
1059
		return "contact-us";
1060
	}
23923 amit.gupta 1061
 
25649 tejbeer 1062
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1063
	public String getNotificationsWithType(HttpServletRequest request,
1064
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1065
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1066
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1067
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1068
		int userId = 0;
1069
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1070
		if (isAdmin) {
1071
			userId = loginDetails.getFofoId();
1072
		} else {
1073
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1074
		}
25683 tejbeer 1075
		List<Notification> notifications = null;
1076
 
26086 tejbeer 1077
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1078
				userId, offset, limit);
1079
		LOGGER.info("messageType" + messageType);
1080
		notifications = getNotifications(notificationCampaigns, messageType);
1081
 
25683 tejbeer 1082
		model.addAttribute("notifications", notifications);
1083
 
1084
		LOGGER.info("notifications" + notifications);
1085
		return "notification-template";
1086
	}
1087
 
1088
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1089
			throws ProfitMandiBusinessException {
1090
		List<Notification> notifications = new ArrayList<>();
1091
		Document document = null;
1092
		if (messageType != null) {
1093
			for (NotificationCampaign notificationCampaign : nc) {
1094
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1095
					Notification ns = new Notification();
1096
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1097
							SimpleCampaignParams.class);
1098
					Campaign campaign = new SimpleCampaign(scp);
1099
					LocalDateTime expire = campaign.getExpireTimestamp();
1100
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1101
					ns.setType(campaign.getType());
1102
					ns.setMessage(campaign.getMessage());
1103
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1104
					if (notificationCampaign.getDocumentId() != null) {
1105
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1106
						ns.setDocumentName(document.getDisplayName());
1107
					}
25683 tejbeer 1108
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1109
					ns.setShowImage(campaign.getShowImage());
1110
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1111
					ns.setDocumentId(notificationCampaign.getDocumentId());
1112
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1113
					ns.setCreated(
1114
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1115
									* 1000);
1116
					if (LocalDateTime.now().isAfter(expire)) {
1117
						ns.setExpired(true);
1118
					} else {
1119
						ns.setExpired(false);
1120
					}
1121
					notifications.add(ns);
1122
				}
1123
			}
25683 tejbeer 1124
		} else {
1125
			for (NotificationCampaign notificationCampaign : nc) {
1126
 
1127
				Notification ns = new Notification();
1128
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1129
						SimpleCampaignParams.class);
1130
				Campaign campaign = new SimpleCampaign(scp);
1131
				LocalDateTime expire = campaign.getExpireTimestamp();
1132
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1133
				ns.setType(campaign.getType());
1134
				ns.setMessage(campaign.getMessage());
1135
				ns.setTitle(campaign.getTitle());
1136
				if (notificationCampaign.getDocumentId() != null) {
1137
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1138
					ns.setDocumentName(document.getDisplayName());
1139
				}
1140
				ns.setUrl(campaign.getUrl());
1141
				ns.setShowImage(campaign.getShowImage());
1142
				ns.setImageUrl(campaign.getImageUrl());
1143
				ns.setDocumentId(notificationCampaign.getDocumentId());
1144
				ns.setMessageType(notificationCampaign.getMessageType());
1145
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1146
						* 1000);
1147
				if (LocalDateTime.now().isAfter(expire)) {
1148
					ns.setExpired(true);
1149
				} else {
1150
					ns.setExpired(false);
1151
				}
1152
				notifications.add(ns);
1153
			}
1154
 
25649 tejbeer 1155
		}
25683 tejbeer 1156
		return notifications;
25651 tejbeer 1157
 
1158
	}
25649 tejbeer 1159
 
25651 tejbeer 1160
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1161
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1162
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1163
			throws ProfitMandiBusinessException {
1164
		Document document = documentRepository.selectById(documentId);
1165
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1166
		if (nc.getDocumentId() == null) {
1167
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1168
		}
1169
		if (nc.getDocumentId() != documentId) {
1170
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1171
		}
1172
		return responseSender.ok(document);
25649 tejbeer 1173
	}
1174
 
25651 tejbeer 1175
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1176
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1177
			throws ProfitMandiBusinessException {
1178
 
1179
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1180
 
1181
		if (nc.getDocumentId() == null) {
1182
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1183
		}
1184
 
1185
		Document document = documentRepository.selectById(nc.getDocumentId());
1186
 
1187
		FileInputStream file = null;
1188
		try {
1189
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1190
		} catch (FileNotFoundException e) {
1191
			LOGGER.error("Retailer Document file not found : ", e);
1192
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1193
		}
1194
		// ByteArrayOutputStream byteArrayOutputStream = new
1195
		// ByteArrayOutputStream();
1196
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1197
 
1198
		final HttpHeaders headers = new HttpHeaders();
1199
		String contentType = "";
1200
		if (document.getContentType() == ContentType.JPEG) {
1201
			contentType = "image/jpeg";
1202
		} else if (document.getContentType() == ContentType.PNG) {
1203
			contentType = "image/png";
1204
		} else if (document.getContentType() == ContentType.PDF) {
1205
			contentType = "application/pdf";
1206
		}
1207
		headers.set("Content-Type", contentType);
1208
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1209
		headers.setContentLength(document.getSize());
1210
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1211
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1212
	}
26460 amit.gupta 1213
 
1214
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1215
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1216
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1217
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1218
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1219
			List<Integer> authIds = l2l1.getValue();
1220
			authIds.add(l2l1.getKey());
1221
 
1222
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1223
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1224
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1225
			if (!leads.isEmpty()) {
1226
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1227
			} else {
1228
				authIdAndleadsCountMap.put(auth.getId(), 0);
1229
			}
26422 tejbeer 1230
		}
26468 amit.gupta 1231
 
26460 amit.gupta 1232
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1233
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1234
				.collect(Collectors.toList());
26433 tejbeer 1235
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1236
 
26460 amit.gupta 1237
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1238
 
26460 amit.gupta 1239
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1240
		for (int authUserId : pp.keySet()) {
1241
			if (L2L1Mapping.keySet().contains(authUserId)) {
1242
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1243
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1244
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1245
						.collect(Collectors.toList());
26927 amit.gupta 1246
				LOGGER.info("authUserId {}, partnerDetails {}" + authUserId, partnerDetails);
26460 amit.gupta 1247
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1248
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1249
			}
1250
		}
26997 amit.gupta 1251
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1252
				.collect(Collectors.toList());
26468 amit.gupta 1253
		PartnerDetailModel partnerDetailModel = partnerStatsService
1254
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1255
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1256
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1257
		return authIdAndallValues;
1258
	}
1259
 
21615 kshitij.so 1260
}