Subversion Repositories SmartDukaan

Rev

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