Subversion Repositories SmartDukaan

Rev

Rev 27218 | Rev 27351 | 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);
336
		Double lmtdSale = fofoOrderItemRepository
27084 amit.gupta 337
				.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
26012 amit.gupta 338
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false)
339
				.get(fofoId);
25214 amit.gupta 340
 
341
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
342
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 343
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 344
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 345
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 346
		}
25214 amit.gupta 347
 
25653 amit.gupta 348
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 349
 
25664 amit.gupta 350
		int currentRate = (int) (mtdSale / curDate.getDayOfMonth());
25653 amit.gupta 351
 
352
		salesMap.put("requiredType", partnerType.next());
353
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
354
		int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
355
		salesMap.put("requiredRate", requiredRate);
356
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
357
 
25858 amit.gupta 358
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
359
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 360
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 361
 
27218 amit.gupta 362
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate*monthLength);
25653 amit.gupta 363
		salesMap.put("currentRate", currentRate);
364
		salesMap.put("currentType", currentType);
365
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 366
		return salesMap;
367
	}
368
 
25677 amit.gupta 369
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
370
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 371
 
26309 amit.gupta 372
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
25677 amit.gupta 373
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
374
 
375
		mobileBrands.stream().forEach(x -> {
376
			String brand = (String) x.get("name");
377
			if (brandStockPricesMap.containsKey(brand)) {
378
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
379
				brandStockPrice.setBrandUrl((String) x.get("url"));
380
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
381
				brandStockPrices.add(brandStockPrice);
382
			}
383
		});
384
 
385
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
386
				.collect(Collectors.toList());
387
	}
388
 
21615 kshitij.so 389
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 390
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 391
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 392
		String email = loginDetails.getEmailId();
25180 amit.gupta 393
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
394
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 395
 
25274 amit.gupta 396
		model.addAttribute("webApiHost", webApiHost);
397
		model.addAttribute("webApiPort", webApiPort);
398
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 399
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 400
		if (isAdmin) {
26011 amit.gupta 401
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 402
		} else {
25740 amit.gupta 403
			FofoStore fofoStore = null;
25180 amit.gupta 404
			try {
405
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 406
				if (!fofoStore.isActive()) {
407
					return "redirect:/login";
408
				}
25649 tejbeer 409
 
25740 amit.gupta 410
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 411
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 412
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 413
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 414
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 415
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
416
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 417
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 418
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 419
				model.addAttribute("activatedImeis",
420
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
26071 tejbeer 421
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
422
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
423
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
424
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
425
				LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
426
				Double accesoriesStock = currentInventorySnapshotRepository
427
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
428
								Optional.of(false))
429
						.get(loginDetails.getFofoId());
25180 amit.gupta 430
 
26071 tejbeer 431
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
26065 amit.gupta 432
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 433
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 434
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
435
 
436
				LOGGER.info("chartMap" + gson.toJson(cm));
437
				model.addAttribute("chartMap", gson.toJson(cm));
25544 amit.gupta 438
				// this.setInvestments
439
				//
25180 amit.gupta 440
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 441
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
442
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 443
 
444
				// Hardcoded for valentine
445
				// Hardcoded for valentine
26588 tejbeer 446
 
26694 tejbeer 447
				List<Offer> offers = offerRepository.selectOfferByStatus(true);
26588 tejbeer 448
				if (!offers.isEmpty()) {
449
					List<CreateOfferRequest> cors = new ArrayList<>();
450
					for (Offer offer : offers) {
451
 
452
						List<OfferPartner> offerPartners = offerPartnerRepository.selectByOfferId(offer.getId());
453
 
454
						for (OfferPartner offerPartner : offerPartners) {
455
 
456
							if (offerPartner.getFofoId() == loginDetails.getFofoId()) {
457
								if (LocalDateTime.now().isAfter(offer.getStartDateTime())
458
										&& LocalDateTime.now().isBefore(offer.getEndDateTime())) {
26674 tejbeer 459
									LocalDateTime cur = LocalDate.now().minusMonths(2).atStartOfDay();
26619 tejbeer 460
									LOGGER.info("value" + cur);
26588 tejbeer 461
									Map<Integer, Double> value = offerRepository.selectSumOfferByRetailer(
26675 tejbeer 462
											offer.getStartDateTime(), offer.getEndDateTime(), loginDetails.getFofoId(),
463
											offer, true);
26588 tejbeer 464
									CreateOfferRequest createOfferRequest = new CreateOfferRequest();
465
									List<Offermargin> offerMargins = offerMarginRepository
466
											.selectByOfferId(offer.getId());
467
									LOGGER.info("value" + offer.getId());
468
									LOGGER.info("value" + value);
469
									for (Offermargin om : offerMargins) {
26619 tejbeer 470
										if (value.get(loginDetails.getFofoId()) <= om.getValue()) {
26588 tejbeer 471
											createOfferRequest.setMargin(om.getMargin());
26694 tejbeer 472
											createOfferRequest.setValue(om.getValue());
26588 tejbeer 473
											createOfferRequest.setShortAmount(
474
													om.getValue() - value.get(loginDetails.getFofoId()));
26674 tejbeer 475
 
26588 tejbeer 476
											break;
477
										} else {
478
											createOfferRequest.setMargin(om.getMargin());
26675 tejbeer 479
 
26588 tejbeer 480
										}
481
 
482
									}
483
 
484
									createOfferRequest.setName(offer.getName());
485
									createOfferRequest.setDescription(offer.getDescription());
486
									createOfferRequest.setTargetType(offer.getTargetType());
487
									createOfferRequest.setAmountType(offer.getAmountType());
26694 tejbeer 488
									createOfferRequest.setStartDateTime(offer.getStartDateTime().toLocalDate());
489
									createOfferRequest.setEndDateTime(offer.getEndDateTime().toLocalDate());
26588 tejbeer 490
									createOfferRequest.setTotalSale(value.get(loginDetails.getFofoId()));
491
									cors.add(createOfferRequest);
492
 
493
									model.addAttribute("sales", value.get(loginDetails.getFofoId()));
494
								}
495
							}
496
 
497
						}
26327 amit.gupta 498
					}
26588 tejbeer 499
					model.addAttribute("offers", cors);
500
 
26674 tejbeer 501
				}
26588 tejbeer 502
 
25180 amit.gupta 503
			} catch (ProfitMandiBusinessException e) {
504
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
505
 
506
			}
22481 ashik.ali 507
		}
25649 tejbeer 508
 
509
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 510
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 511
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
512
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 513
				currentMonthEnd) / 2;
25747 amit.gupta 514
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
515
				currentMonthStart) / 2;
516
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 517
				currentMonthEnd) / 2;
518
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
519
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
520
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 521
 
25653 amit.gupta 522
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
523
				currentMonthEnd);
25651 tejbeer 524
 
25653 amit.gupta 525
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
526
				currentMonthStart, currentMonthEnd);
527
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
528
			invalidHygieneCount = 1;
529
		}
530
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 531
 
25197 amit.gupta 532
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
533
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27229 amit.gupta 534
		if(loginDetails.isReadOnly()) {
535
			return "dashboard-readonly";
536
		} else {
537
			return "dashboard1";
538
		}
21615 kshitij.so 539
	}
23923 amit.gupta 540
 
26055 tejbeer 541
	private ChartModel getBrandChart(int fofoId) {
542
 
543
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
544
 
545
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
546
 
547
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
548
 
549
		Map<String, Double> brandwisesale = fofoOrderItemRepository
550
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 551
 
552
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
553
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
554
 
555
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
556
 
26055 tejbeer 557
		LOGGER.info("brandwisesale" + brandwisesale);
558
 
559
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
560
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
561
 
26244 tejbeer 562
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
563
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
564
				Optional.of(false));
565
		LOGGER.info("accesorieslmtdsale" + accesorieslmtdsale);
26055 tejbeer 566
		ChartModel cm = new ChartModel();
567
 
568
		List<String> labels = new ArrayList<>();
569
		labels.addAll(brandwisesale.keySet());
26244 tejbeer 570
		labels.add("accessories");
26055 tejbeer 571
		List<Double> values = new ArrayList<>();
572
		values.addAll(brandwisesale.values());
26244 tejbeer 573
		values.addAll(accesoriesmtdsale.values());
26055 tejbeer 574
 
575
		List<Double> lmtdValues = new ArrayList<>();
576
		lmtdValues.addAll(lmtdBrandWiseSale.values());
26244 tejbeer 577
		lmtdValues.addAll(accesorieslmtdsale.values());
26055 tejbeer 578
 
579
		DatasetModel dsm = new DatasetModel();
580
		dsm.setLabel("mtd sales");
581
 
582
		List<String> backgroundColor = new ArrayList<>();
583
		for (Entry<String, Double> bs : brandwisesale.entrySet()) {
584
			backgroundColor.add("#3e95cd");
585
		}
26244 tejbeer 586
		backgroundColor.add("#3e95cd");
26055 tejbeer 587
		dsm.setBackgroundColor(backgroundColor);
588
		dsm.setData(values);
589
 
590
		DatasetModel lmtddsm = new DatasetModel();
591
		lmtddsm.setLabel("lmtd sales");
592
 
593
		List<String> background = new ArrayList<>();
594
		for (Entry<String, Double> bs : lmtdBrandWiseSale.entrySet()) {
595
			background.add("#8e5ea2");
596
		}
26244 tejbeer 597
		background.add("#8e5ea2");
26055 tejbeer 598
		lmtddsm.setBackgroundColor(background);
599
		lmtddsm.setData(lmtdValues);
600
 
601
		List<DatasetModel> datasets = new ArrayList<>();
602
		datasets.add(dsm);
603
		datasets.add(lmtddsm);
604
 
605
		DataModel dm = new DataModel();
606
		dm.setDatasets(datasets);
607
		dm.setLabels(labels);
608
 
609
		LegendModel lm = new LegendModel();
610
		lm.setDisplay(true);
611
 
612
		TitleModel tm = new TitleModel();
613
		tm.setText("Brand Wise Sale Graph");
614
		tm.setDisplay(true);
615
 
616
		OptionsModel om = new OptionsModel();
617
		om.setLegend(lm);
618
		om.setTitle(tm);
619
 
620
		cm.setType("bar");
621
		cm.setData(dm);
622
		cm.setOptions(om);
623
 
624
		return cm;
625
 
626
	}
627
 
26418 tejbeer 628
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 629
		List<Menu> menus = null;
26011 amit.gupta 630
		try {
631
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
632
			List<Position> positions = positionRepository.selectAll(authUser.getId());
26418 tejbeer 633
			Map<Integer, AuthUser> authIdAndAuthUserMap = null;
26460 amit.gupta 634
			Map<Integer, PartnerDetailModel> authIdAndallValues = null;
26418 tejbeer 635
			if (positions.size() > 0) {
27106 amit.gupta 636
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L3) 
637
					|| x.getEscalationType().equals(EscalationType.L4) 
638
					|| x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26418 tejbeer 639
 
640
					authIdAndAuthUserMap = authRepository.selectAllActiveUser().stream()
641
							.collect(Collectors.toMap(x -> x.getId(), x -> x));
26588 tejbeer 642
 
26997 amit.gupta 643
					AuthUser unmappedAuthUser = new AuthUser();
644
					unmappedAuthUser.setFirstName("Unmapped");
645
					unmappedAuthUser.setLastName("Partners");
26999 amit.gupta 646
					authIdAndAuthUserMap.put(-1, unmappedAuthUser);
26997 amit.gupta 647
 
26468 amit.gupta 648
					AuthUser dummyAuthUser = new AuthUser();
649
					dummyAuthUser.setFirstName("Total");
650
					dummyAuthUser.setLastName("Values");
651
					authIdAndAuthUserMap.put(0, dummyAuthUser);
26997 amit.gupta 652
 
26422 tejbeer 653
					authIdAndallValues = this.getL2AuthUserPartnerDetail();
26418 tejbeer 654
				}
655
			}
656
 
27111 amit.gupta 657
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in").contains(email)) {
26029 amit.gupta 658
				menus = menuRepository.selectAll();
659
			} else if (positions.size() > 0) {
27108 amit.gupta 660
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 661
					menus = menuRepository.selectAll();
662
				} else {
663
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
664
							.map(x -> x.getMenuId()).collect(Collectors.toList());
665
					LOGGER.info("Menu Ids are {}", menuIds);
666
					if (menuIds.size() > 0) {
667
						menus = menuRepository.selectAllByIds(menuIds);
668
					}
26022 amit.gupta 669
				}
26090 amit.gupta 670
				List<Position> salesPositions = positions.stream()
671
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
672
						.collect(Collectors.toList());
673
				if (salesPositions.size() > 0) {
674
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 675
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 676
						positionRetailers.addAll(customRetailers);
677
					});
678
					model.addAttribute("retailers", gson.toJson(positionRetailers));
679
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 680
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 681
				}
26114 amit.gupta 682
				List<Position> warehousePositions = positions.stream()
683
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
684
						.collect(Collectors.toList());
685
				if (warehousePositions.size() > 0) {
686
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 687
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 688
						positionRetailers.addAll(customRetailers);
689
					});
690
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
691
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 692
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 693
				}
26142 amit.gupta 694
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 695
 
26022 amit.gupta 696
			}
26418 tejbeer 697
			model.addAttribute("authIdAndallValues", authIdAndallValues);
698
			model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
699
 
26012 amit.gupta 700
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 701
		}
26028 amit.gupta 702
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 703
		LOGGER.info("menu" + menuList);
26022 amit.gupta 704
		model.addAttribute("menu", menuList);
26012 amit.gupta 705
		return "admin";
706
	}
707
 
26468 amit.gupta 708
	/*
709
	 * @RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET) public
710
	 * String L1AuthUsersDetail(HttpServletRequest request, Model
711
	 * model, @RequestParam int authId) throws Exception {
712
	 * 
713
	 * Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
714
	 * 
715
	 * LocalDateTime curDate = LocalDate.now().atStartOfDay(); Map<Integer, Double>
716
	 * lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
717
	 * curDate.withDayOfMonth(1).minusMonths(1),
718
	 * curDate.with(LocalTime.MAX).minusMonths(1), 0, false); Map<Integer, Double>
719
	 * mtdSale =
720
	 * fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth
721
	 * (1), curDate.with(LocalTime.MAX), 0, false); Map<Integer, List<Integer>>
722
	 * L2L1Mapping = csService.getL1L2Mapping();
723
	 * 
724
	 * LOGGER.info("L2L1Mapping" + L2L1Mapping); List<Integer> l1authIds =
725
	 * L2L1Mapping.get(authId);
726
	 * 
727
	 * Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>(); Map<Integer,
728
	 * Object> authIdAndAuthUserMap = new LinkedHashMap<>();
729
	 * 
730
	 * Map<Integer, Long> ticketMap =
731
	 * ticketRepository.selectAllNotClosedTicketsGroupByRetailer(); for (Integer
732
	 * l1AuthId : l1authIds) {
733
	 * 
734
	 * double totallmtdAmount = 0; double totalmtdAmount = 0; int totalTicketCount =
735
	 * 0; float totalTodayInvestment = 0; float totalStockInInvestment = 0; double
736
	 * currentMonthRatingAllPartners = 0; Map<Integer, Long> leadCount =
737
	 * leadRepository.selectByAssignAuthIdAndStatus(l1AuthId, LeadStatus.followUp)
738
	 * .stream().collect(Collectors.groupingBy(Lead::getAssignTo,
739
	 * Collectors.counting()));
740
	 * 
741
	 * AuthUser authUser = authRepository.selectById(l1AuthId);
742
	 * 
743
	 * authIdAndAuthUserMap.put(l1AuthId, authUser);
744
	 * 
745
	 * List<Integer> fofoIds = pp.get(l1AuthId);
746
	 * 
747
	 * Map<Integer, PartnerDailyInvestment> partnerInvestentMap =
748
	 * partnerInvestmentService .getInvestment(fofoIds,
749
	 * 0).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
750
	 * 
751
	 * for (Integer fId : fofoIds) { try { PartnerDailyInvestment investment =
752
	 * partnerInvestentMap.get(fId); totalTodayInvestment +=
753
	 * investment.getTotalInvestment(); totalStockInInvestment +=
754
	 * investment.getInStockAmount(); } catch (Exception e) { }
755
	 * 
756
	 * double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
757
	 * curDate.withDayOfMonth(1).minusMonths(1),
758
	 * curDate.plusMonths(1).withDayOfMonth(1));
759
	 * 
760
	 * currentMonthRatingAllPartners += currentMonthRating;
761
	 * 
762
	 * fofoIds.size();
763
	 * 
764
	 * Double lmtdAmount = lmtdSale.get(fId); Double mtdAmount = mtdSale.get(fId);
765
	 * Long ticketCount = ticketMap.get(fId); if (ticketCount != null) {
766
	 * totalTicketCount += ticketCount; }
767
	 * 
768
	 * if (lmtdAmount != null) { totallmtdAmount += lmtdAmount; }
769
	 * 
770
	 * if (mtdAmount != null) { totalmtdAmount += mtdAmount; }
771
	 * 
772
	 * } LOGGER.info("currentMonthRatingAllPartners" +
773
	 * currentMonthRatingAllPartners); LOGGER.info("size" + fofoIds.size()); double
774
	 * totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
775
	 * 
776
	 * LOGGER.info("totalHygieneRating" + totalHygieneRating);
777
	 * 
778
	 * PartnerDetailModel pm = new PartnerDetailModel();
779
	 * pm.setLmtd(totallmtdAmount); pm.setMtd(totalmtdAmount); if
780
	 * (leadCount.get(l1AuthId) != null) {
781
	 * pm.setLeads(leadCount.get(l1AuthId).intValue()); } else { pm.setLeads(0); }
782
	 * 
783
	 * pm.setInvestment(totalTodayInvestment);
784
	 * pm.setStockInInvestment(totalStockInInvestment);
785
	 * pm.setTicket(totalTicketCount); pm.setHygiene((double)
786
	 * Math.round(totalHygieneRating)); authIdAndallValues.put(l1AuthId, pm);
787
	 * 
788
	 * } model.addAttribute("authIdAndallValues", authIdAndallValues);
789
	 * model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
790
	 * LOGGER.info("authIdAndallValues" + authIdAndallValues);
791
	 * 
792
	 * return "auth_user_detail"; }
793
	 */
26418 tejbeer 794
 
26468 amit.gupta 795
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 796
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
797
			throws Exception {
798
 
799
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 800
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 801
 
26468 amit.gupta 802
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
803
		if (authId != 0) {
804
			List<Integer> fofoIds = pp.get(authId);
805
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
806
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 807
		} else {
26418 tejbeer 808
		}
809
 
810
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
811
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
812
 
813
		return "auth_user_partner_detail";
26468 amit.gupta 814
	}
26418 tejbeer 815
 
26114 amit.gupta 816
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
817
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 818
		positionRetailers.stream().forEach(x -> {
819
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 820
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
821
			}
822
		});
26114 amit.gupta 823
		return gson.toJson(warehouses);
824
 
825
	}
826
 
26012 amit.gupta 827
	private List<Menu> prepareMenu(List<Menu> menus) {
828
		List<Menu> returnMenu = new ArrayList<>();
829
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
830
		for (Menu menu : menus) {
831
			if (menu.get_parent() == null) {
26014 amit.gupta 832
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 833
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 834
				}
835
			} else {
26012 amit.gupta 836
				Menu parentMenu = menu.get_parent();
837
				if (!subMenuMap.containsKey(parentMenu)) {
838
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 839
				}
26012 amit.gupta 840
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 841
			}
842
		}
26012 amit.gupta 843
		subMenuMap.entrySet().stream().forEach(entry -> {
844
			entry.getKey().setSubMenus(entry.getValue());
845
			returnMenu.add(entry.getKey());
846
		});
847
		return returnMenu;
26005 amit.gupta 848
	}
849
 
24288 amit.gupta 850
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 851
	private boolean hasGift(int fofoId) {
852
		try {
24288 amit.gupta 853
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
854
					.getAvailability() > 0;
24203 amit.gupta 855
		} catch (ProfitMandiBusinessException e) {
856
			return false;
857
		}
858
	}
24288 amit.gupta 859
 
22354 ashik.ali 860
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 861
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 862
		model.addAttribute("appContextPath", request.getContextPath());
863
		return "contact-us";
864
	}
23923 amit.gupta 865
 
25649 tejbeer 866
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 867
	public String getNotificationsWithType(HttpServletRequest request,
868
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 869
			@RequestParam(name = "offset", defaultValue = "0") int offset,
870
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
871
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 872
		int userId = 0;
873
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
874
		if (isAdmin) {
875
			userId = loginDetails.getFofoId();
876
		} else {
877
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
878
		}
25683 tejbeer 879
		List<Notification> notifications = null;
880
 
26086 tejbeer 881
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
882
				userId, offset, limit);
883
		LOGGER.info("messageType" + messageType);
884
		notifications = getNotifications(notificationCampaigns, messageType);
885
 
25683 tejbeer 886
		model.addAttribute("notifications", notifications);
887
 
888
		LOGGER.info("notifications" + notifications);
889
		return "notification-template";
890
	}
891
 
892
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
893
			throws ProfitMandiBusinessException {
894
		List<Notification> notifications = new ArrayList<>();
895
		Document document = null;
896
		if (messageType != null) {
897
			for (NotificationCampaign notificationCampaign : nc) {
898
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 899
					Notification ns = new Notification();
900
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
901
							SimpleCampaignParams.class);
902
					Campaign campaign = new SimpleCampaign(scp);
903
					LocalDateTime expire = campaign.getExpireTimestamp();
904
					ns.setCid(Integer.toString(notificationCampaign.getId()));
905
					ns.setType(campaign.getType());
906
					ns.setMessage(campaign.getMessage());
907
					ns.setTitle(campaign.getTitle());
25651 tejbeer 908
					if (notificationCampaign.getDocumentId() != null) {
909
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
910
						ns.setDocumentName(document.getDisplayName());
911
					}
25683 tejbeer 912
					ns.setUrl(campaign.getUrl());
25649 tejbeer 913
					ns.setShowImage(campaign.getShowImage());
914
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 915
					ns.setDocumentId(notificationCampaign.getDocumentId());
916
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 917
					ns.setCreated(
918
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
919
									* 1000);
920
					if (LocalDateTime.now().isAfter(expire)) {
921
						ns.setExpired(true);
922
					} else {
923
						ns.setExpired(false);
924
					}
925
					notifications.add(ns);
926
				}
927
			}
25683 tejbeer 928
		} else {
929
			for (NotificationCampaign notificationCampaign : nc) {
930
 
931
				Notification ns = new Notification();
932
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
933
						SimpleCampaignParams.class);
934
				Campaign campaign = new SimpleCampaign(scp);
935
				LocalDateTime expire = campaign.getExpireTimestamp();
936
				ns.setCid(Integer.toString(notificationCampaign.getId()));
937
				ns.setType(campaign.getType());
938
				ns.setMessage(campaign.getMessage());
939
				ns.setTitle(campaign.getTitle());
940
				if (notificationCampaign.getDocumentId() != null) {
941
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
942
					ns.setDocumentName(document.getDisplayName());
943
				}
944
				ns.setUrl(campaign.getUrl());
945
				ns.setShowImage(campaign.getShowImage());
946
				ns.setImageUrl(campaign.getImageUrl());
947
				ns.setDocumentId(notificationCampaign.getDocumentId());
948
				ns.setMessageType(notificationCampaign.getMessageType());
949
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
950
						* 1000);
951
				if (LocalDateTime.now().isAfter(expire)) {
952
					ns.setExpired(true);
953
				} else {
954
					ns.setExpired(false);
955
				}
956
				notifications.add(ns);
957
			}
958
 
25649 tejbeer 959
		}
25683 tejbeer 960
		return notifications;
25651 tejbeer 961
 
962
	}
25649 tejbeer 963
 
25651 tejbeer 964
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
965
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
966
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
967
			throws ProfitMandiBusinessException {
968
		Document document = documentRepository.selectById(documentId);
969
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
970
		if (nc.getDocumentId() == null) {
971
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
972
		}
973
		if (nc.getDocumentId() != documentId) {
974
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
975
		}
976
		return responseSender.ok(document);
25649 tejbeer 977
	}
978
 
25651 tejbeer 979
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
980
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
981
			throws ProfitMandiBusinessException {
982
 
983
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
984
 
985
		if (nc.getDocumentId() == null) {
986
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
987
		}
988
 
989
		Document document = documentRepository.selectById(nc.getDocumentId());
990
 
991
		FileInputStream file = null;
992
		try {
993
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
994
		} catch (FileNotFoundException e) {
995
			LOGGER.error("Retailer Document file not found : ", e);
996
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
997
		}
998
		// ByteArrayOutputStream byteArrayOutputStream = new
999
		// ByteArrayOutputStream();
1000
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1001
 
1002
		final HttpHeaders headers = new HttpHeaders();
1003
		String contentType = "";
1004
		if (document.getContentType() == ContentType.JPEG) {
1005
			contentType = "image/jpeg";
1006
		} else if (document.getContentType() == ContentType.PNG) {
1007
			contentType = "image/png";
1008
		} else if (document.getContentType() == ContentType.PDF) {
1009
			contentType = "application/pdf";
1010
		}
1011
		headers.set("Content-Type", contentType);
1012
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1013
		headers.setContentLength(document.getSize());
1014
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1015
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1016
	}
26460 amit.gupta 1017
 
1018
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1019
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1020
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1021
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1022
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1023
			List<Integer> authIds = l2l1.getValue();
1024
			authIds.add(l2l1.getKey());
1025
 
1026
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1027
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1028
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1029
			if (!leads.isEmpty()) {
1030
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1031
			} else {
1032
				authIdAndleadsCountMap.put(auth.getId(), 0);
1033
			}
26422 tejbeer 1034
		}
26468 amit.gupta 1035
 
26460 amit.gupta 1036
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
26997 amit.gupta 1037
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x->x.getKey()).collect(Collectors.toList());
26433 tejbeer 1038
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1039
 
26460 amit.gupta 1040
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1041
 
26460 amit.gupta 1042
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1043
		for (int authUserId : pp.keySet()) {
1044
			if (L2L1Mapping.keySet().contains(authUserId)) {
1045
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1046
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1047
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1048
						.collect(Collectors.toList());
26927 amit.gupta 1049
				LOGGER.info("authUserId {}, partnerDetails {}" + authUserId, partnerDetails);
26460 amit.gupta 1050
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1051
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1052
			}
1053
		}
26997 amit.gupta 1054
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1055
				.collect(Collectors.toList());
26468 amit.gupta 1056
		PartnerDetailModel partnerDetailModel = partnerStatsService
1057
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1058
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1059
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1060
		return authIdAndallValues;
1061
	}
1062
 
21615 kshitij.so 1063
}