Subversion Repositories SmartDukaan

Rev

Rev 26458 | Rev 26468 | 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;
26460 amit.gupta 126
 
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));
581
 
26422 tejbeer 582
					authIdAndallValues = this.getL2AuthUserPartnerDetail();
26418 tejbeer 583
				}
584
			}
585
 
26090 amit.gupta 586
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in").contains(email)) {
26029 amit.gupta 587
				menus = menuRepository.selectAll();
588
			} else if (positions.size() > 0) {
589
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L4)).count() > 0) {
26028 amit.gupta 590
					menus = menuRepository.selectAll();
591
				} else {
592
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
593
							.map(x -> x.getMenuId()).collect(Collectors.toList());
594
					LOGGER.info("Menu Ids are {}", menuIds);
595
					if (menuIds.size() > 0) {
596
						menus = menuRepository.selectAllByIds(menuIds);
597
					}
26022 amit.gupta 598
				}
26090 amit.gupta 599
				List<Position> salesPositions = positions.stream()
600
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
601
						.collect(Collectors.toList());
602
				if (salesPositions.size() > 0) {
603
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 604
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 605
						positionRetailers.addAll(customRetailers);
606
					});
607
					model.addAttribute("retailers", gson.toJson(positionRetailers));
608
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 609
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 610
				}
26114 amit.gupta 611
				List<Position> warehousePositions = positions.stream()
612
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
613
						.collect(Collectors.toList());
614
				if (warehousePositions.size() > 0) {
615
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 616
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 617
						positionRetailers.addAll(customRetailers);
618
					});
619
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
620
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 621
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 622
				}
26142 amit.gupta 623
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 624
 
26022 amit.gupta 625
			}
26418 tejbeer 626
			model.addAttribute("authIdAndallValues", authIdAndallValues);
627
			model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
628
 
629
			LOGGER.info("authIdAndallValues1" + authIdAndallValues);
26012 amit.gupta 630
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 631
		}
26028 amit.gupta 632
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 633
		LOGGER.info("menu" + menuList);
26022 amit.gupta 634
		model.addAttribute("menu", menuList);
26012 amit.gupta 635
		return "admin";
636
	}
637
 
26460 amit.gupta 638
/*	@RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET)
26418 tejbeer 639
	public String L1AuthUsersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
640
			throws Exception {
641
 
642
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
643
 
644
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
645
		Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
646
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
647
		Map<Integer, Double> mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),
648
				curDate.with(LocalTime.MAX), 0, false);
649
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL1L2Mapping();
650
 
651
		LOGGER.info("L2L1Mapping" + L2L1Mapping);
652
		List<Integer> l1authIds = L2L1Mapping.get(authId);
653
 
654
		Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>();
655
		Map<Integer, Object> authIdAndAuthUserMap = new LinkedHashMap<>();
656
 
657
		Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();
26453 amit.gupta 658
		for (Integer l1AuthId : l1authIds) {
26418 tejbeer 659
 
660
			double totallmtdAmount = 0;
661
			double totalmtdAmount = 0;
662
			int totalTicketCount = 0;
663
			float totalTodayInvestment = 0;
664
			float totalStockInInvestment = 0;
665
			double currentMonthRatingAllPartners = 0;
26453 amit.gupta 666
			Map<Integer, Long> leadCount = leadRepository.selectByAssignAuthIdAndStatus(l1AuthId, LeadStatus.followUp)
26418 tejbeer 667
					.stream().collect(Collectors.groupingBy(Lead::getAssignTo, Collectors.counting()));
668
 
26453 amit.gupta 669
			AuthUser authUser = authRepository.selectById(l1AuthId);
26418 tejbeer 670
 
26453 amit.gupta 671
			authIdAndAuthUserMap.put(l1AuthId, authUser);
26418 tejbeer 672
 
26453 amit.gupta 673
			List<Integer> fofoIds = pp.get(l1AuthId);
26418 tejbeer 674
 
26460 amit.gupta 675
			Map<Integer, PartnerDailyInvestment> partnerInvestentMap = partnerInvestmentService
676
					.getInvestment(fofoIds, 0).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
677
 
26418 tejbeer 678
			for (Integer fId : fofoIds) {
26445 amit.gupta 679
				try {
26455 amit.gupta 680
					PartnerDailyInvestment investment = partnerInvestentMap.get(fId);
26445 amit.gupta 681
					totalTodayInvestment += investment.getTotalInvestment();
682
					totalStockInInvestment += investment.getInStockAmount();
26460 amit.gupta 683
				} catch (Exception e) {
26445 amit.gupta 684
				}
26418 tejbeer 685
 
686
				double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
687
						curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));
688
 
689
				currentMonthRatingAllPartners += currentMonthRating;
690
 
691
				fofoIds.size();
692
 
693
				Double lmtdAmount = lmtdSale.get(fId);
694
				Double mtdAmount = mtdSale.get(fId);
695
				Long ticketCount = ticketMap.get(fId);
696
				if (ticketCount != null) {
697
					totalTicketCount += ticketCount;
698
				}
699
 
700
				if (lmtdAmount != null) {
701
					totallmtdAmount += lmtdAmount;
702
				}
703
 
704
				if (mtdAmount != null) {
705
					totalmtdAmount += mtdAmount;
706
				}
707
 
708
			}
709
			LOGGER.info("currentMonthRatingAllPartners" + currentMonthRatingAllPartners);
710
			LOGGER.info("size" + fofoIds.size());
711
			double totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
712
 
713
			LOGGER.info("totalHygieneRating" + totalHygieneRating);
714
 
715
			PartnerDetailModel pm = new PartnerDetailModel();
716
			pm.setLmtd(totallmtdAmount);
717
			pm.setMtd(totalmtdAmount);
26453 amit.gupta 718
			if (leadCount.get(l1AuthId) != null) {
719
				pm.setLeads(leadCount.get(l1AuthId).intValue());
26418 tejbeer 720
			} else {
721
				pm.setLeads(0);
722
			}
723
 
724
			pm.setInvestment(totalTodayInvestment);
725
			pm.setStockInInvestment(totalStockInInvestment);
726
			pm.setTicket(totalTicketCount);
727
			pm.setHygiene((double) Math.round(totalHygieneRating));
26453 amit.gupta 728
			authIdAndallValues.put(l1AuthId, pm);
26418 tejbeer 729
 
730
		}
731
		model.addAttribute("authIdAndallValues", authIdAndallValues);
732
		model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
733
		LOGGER.info("authIdAndallValues" + authIdAndallValues);
734
 
735
		return "auth_user_detail";
26460 amit.gupta 736
	}*/
26418 tejbeer 737
 
26460 amit.gupta 738
/*	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 739
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
740
			throws Exception {
741
 
742
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
743
		List<Integer> fofoIds = pp.get(authId);
744
		Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();
745
		Map<Integer, Object> fofoIdAndallValues = new LinkedHashMap<>();
746
		Map<Integer, Object> fofoIdAndPartnerMap = new LinkedHashMap<>();
747
		for (Integer fofoId : fofoIds) {
748
 
749
			CustomRetailer cr = retailerService.getFofoRetailer(fofoId);
750
			fofoIdAndPartnerMap.put(fofoId, cr);
751
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
752
			Double lmtdSale = fofoOrderItemRepository
753
					.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
754
							curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false)
755
					.get(fofoId);
756
			Double mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),
757
					curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
758
			Map<String, Object> investmentMap = this.getInvestments(fofoId);
759
			double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId,
760
					curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));
761
 
762
			Long ticketCount = ticketMap.get(fofoId);
763
 
764
			float totalTodayInvestment = (float) investmentMap.get("today");
765
			float totalStockInInvestment = (float) investmentMap.get("inStock");
766
 
767
			PartnerDetailModel pm = new PartnerDetailModel();
768
			pm.setLmtd(lmtdSale);
769
			pm.setMtd(mtdSale);
770
			pm.setInvestment(totalTodayInvestment);
771
			pm.setStockInInvestment(totalStockInInvestment);
772
			if (ticketCount != null) {
773
				pm.setTicket(ticketCount.intValue());
774
			} else {
775
				pm.setTicket(0);
776
			}
777
			pm.setHygiene((double) Math.round(currentMonthRating));
778
			fofoIdAndallValues.put(fofoId, pm);
779
		}
780
 
781
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
782
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
783
 
784
		return "auth_user_partner_detail";
26460 amit.gupta 785
	}*/
26418 tejbeer 786
 
26114 amit.gupta 787
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
788
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 789
		positionRetailers.stream().forEach(x -> {
790
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 791
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
792
			}
793
		});
26114 amit.gupta 794
		return gson.toJson(warehouses);
795
 
796
	}
797
 
26012 amit.gupta 798
	private List<Menu> prepareMenu(List<Menu> menus) {
799
		List<Menu> returnMenu = new ArrayList<>();
800
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
801
		for (Menu menu : menus) {
802
			if (menu.get_parent() == null) {
26014 amit.gupta 803
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 804
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 805
				}
806
			} else {
26012 amit.gupta 807
				Menu parentMenu = menu.get_parent();
808
				if (!subMenuMap.containsKey(parentMenu)) {
809
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 810
				}
26012 amit.gupta 811
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 812
			}
813
		}
26012 amit.gupta 814
		subMenuMap.entrySet().stream().forEach(entry -> {
815
			entry.getKey().setSubMenus(entry.getValue());
816
			returnMenu.add(entry.getKey());
817
		});
818
		return returnMenu;
26005 amit.gupta 819
	}
820
 
24288 amit.gupta 821
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 822
	private boolean hasGift(int fofoId) {
823
		try {
24288 amit.gupta 824
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
825
					.getAvailability() > 0;
24203 amit.gupta 826
		} catch (ProfitMandiBusinessException e) {
827
			return false;
828
		}
829
	}
24288 amit.gupta 830
 
22354 ashik.ali 831
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 832
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 833
		model.addAttribute("appContextPath", request.getContextPath());
834
		return "contact-us";
835
	}
23923 amit.gupta 836
 
25649 tejbeer 837
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 838
	public String getNotificationsWithType(HttpServletRequest request,
839
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 840
			@RequestParam(name = "offset", defaultValue = "0") int offset,
841
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
842
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 843
		int userId = 0;
844
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
845
		if (isAdmin) {
846
			userId = loginDetails.getFofoId();
847
		} else {
848
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
849
		}
25683 tejbeer 850
		List<Notification> notifications = null;
851
 
26086 tejbeer 852
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
853
				userId, offset, limit);
854
		LOGGER.info("messageType" + messageType);
855
		notifications = getNotifications(notificationCampaigns, messageType);
856
 
25683 tejbeer 857
		model.addAttribute("notifications", notifications);
858
 
859
		LOGGER.info("notifications" + notifications);
860
		return "notification-template";
861
	}
862
 
863
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
864
			throws ProfitMandiBusinessException {
865
		List<Notification> notifications = new ArrayList<>();
866
		Document document = null;
867
		if (messageType != null) {
868
			for (NotificationCampaign notificationCampaign : nc) {
869
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 870
					Notification ns = new Notification();
871
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
872
							SimpleCampaignParams.class);
873
					Campaign campaign = new SimpleCampaign(scp);
874
					LocalDateTime expire = campaign.getExpireTimestamp();
875
					ns.setCid(Integer.toString(notificationCampaign.getId()));
876
					ns.setType(campaign.getType());
877
					ns.setMessage(campaign.getMessage());
878
					ns.setTitle(campaign.getTitle());
25651 tejbeer 879
					if (notificationCampaign.getDocumentId() != null) {
880
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
881
						ns.setDocumentName(document.getDisplayName());
882
					}
25683 tejbeer 883
					ns.setUrl(campaign.getUrl());
25649 tejbeer 884
					ns.setShowImage(campaign.getShowImage());
885
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 886
					ns.setDocumentId(notificationCampaign.getDocumentId());
887
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 888
					ns.setCreated(
889
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
890
									* 1000);
891
					if (LocalDateTime.now().isAfter(expire)) {
892
						ns.setExpired(true);
893
					} else {
894
						ns.setExpired(false);
895
					}
896
					notifications.add(ns);
897
				}
898
			}
25683 tejbeer 899
		} else {
900
			for (NotificationCampaign notificationCampaign : nc) {
901
 
902
				Notification ns = new Notification();
903
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
904
						SimpleCampaignParams.class);
905
				Campaign campaign = new SimpleCampaign(scp);
906
				LocalDateTime expire = campaign.getExpireTimestamp();
907
				ns.setCid(Integer.toString(notificationCampaign.getId()));
908
				ns.setType(campaign.getType());
909
				ns.setMessage(campaign.getMessage());
910
				ns.setTitle(campaign.getTitle());
911
				if (notificationCampaign.getDocumentId() != null) {
912
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
913
					ns.setDocumentName(document.getDisplayName());
914
				}
915
				ns.setUrl(campaign.getUrl());
916
				ns.setShowImage(campaign.getShowImage());
917
				ns.setImageUrl(campaign.getImageUrl());
918
				ns.setDocumentId(notificationCampaign.getDocumentId());
919
				ns.setMessageType(notificationCampaign.getMessageType());
920
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
921
						* 1000);
922
				if (LocalDateTime.now().isAfter(expire)) {
923
					ns.setExpired(true);
924
				} else {
925
					ns.setExpired(false);
926
				}
927
				notifications.add(ns);
928
			}
929
 
25649 tejbeer 930
		}
25683 tejbeer 931
		return notifications;
25651 tejbeer 932
 
933
	}
25649 tejbeer 934
 
25651 tejbeer 935
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
936
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
937
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
938
			throws ProfitMandiBusinessException {
939
		Document document = documentRepository.selectById(documentId);
940
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
941
		if (nc.getDocumentId() == null) {
942
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
943
		}
944
		if (nc.getDocumentId() != documentId) {
945
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
946
		}
947
		return responseSender.ok(document);
25649 tejbeer 948
	}
949
 
25651 tejbeer 950
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
951
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
952
			throws ProfitMandiBusinessException {
953
 
954
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
955
 
956
		if (nc.getDocumentId() == null) {
957
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
958
		}
959
 
960
		Document document = documentRepository.selectById(nc.getDocumentId());
961
 
962
		FileInputStream file = null;
963
		try {
964
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
965
		} catch (FileNotFoundException e) {
966
			LOGGER.error("Retailer Document file not found : ", e);
967
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
968
		}
969
		// ByteArrayOutputStream byteArrayOutputStream = new
970
		// ByteArrayOutputStream();
971
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
972
 
973
		final HttpHeaders headers = new HttpHeaders();
974
		String contentType = "";
975
		if (document.getContentType() == ContentType.JPEG) {
976
			contentType = "image/jpeg";
977
		} else if (document.getContentType() == ContentType.PNG) {
978
			contentType = "image/png";
979
		} else if (document.getContentType() == ContentType.PDF) {
980
			contentType = "application/pdf";
981
		}
982
		headers.set("Content-Type", contentType);
983
		headers.set("Content-disposition", "inline; filename=" + document.getName());
984
		headers.setContentLength(document.getSize());
985
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
986
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
987
	}
26460 amit.gupta 988
 
989
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26422 tejbeer 990
		List<Position> pos = positionRepository.selectPositionbyCategoryIdAndEscalationType(
991
				ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
25651 tejbeer 992
 
26445 amit.gupta 993
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26422 tejbeer 994
 
26460 amit.gupta 995
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 996
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
997
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
998
			List<Integer> authIds = l2l1.getValue();
999
			authIds.add(l2l1.getKey());
1000
 
1001
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1002
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1003
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1004
			if (!leads.isEmpty()) {
1005
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1006
			} else {
1007
				authIdAndleadsCountMap.put(auth.getId(), 0);
1008
			}
26422 tejbeer 1009
		}
26433 tejbeer 1010
 
26460 amit.gupta 1011
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1012
 
26433 tejbeer 1013
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1014
 
26460 amit.gupta 1015
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1016
 
26460 amit.gupta 1017
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1018
		for (int authUserId : pp.keySet()) {
1019
			if (L2L1Mapping.keySet().contains(authUserId)) {
1020
				List<Integer> fofoIds = pp.get(authUserId);
1021
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x->partnerStats.get(x)).collect(Collectors.toList());
1022
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1023
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1024
			}
1025
		}
26460 amit.gupta 1026
		PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(new ArrayList<>(partnerStats.values()));
1027
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1028
		return authIdAndallValues;
1029
	}
1030
 
21615 kshitij.so 1031
}