Subversion Repositories SmartDukaan

Rev

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