Subversion Repositories SmartDukaan

Rev

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