Subversion Repositories SmartDukaan

Rev

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