Subversion Repositories SmartDukaan

Rev

Rev 27398 | Rev 27474 | 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
								 */
27398 tejbeer 465
								int todayMonth = LocalDateTime.now().getMonthValue();
466
								if (todayMonth == offer.getStartDateTime().getMonthValue()
467
										|| todayMonth == offer.getEndDateTime().getMonthValue()) {
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
									}
27360 tejbeer 492
									createOfferRequest.setId(offer.getId());
26588 tejbeer 493
 
494
									createOfferRequest.setName(offer.getName());
495
									createOfferRequest.setDescription(offer.getDescription());
496
									createOfferRequest.setTargetType(offer.getTargetType());
497
									createOfferRequest.setAmountType(offer.getAmountType());
26694 tejbeer 498
									createOfferRequest.setStartDateTime(offer.getStartDateTime().toLocalDate());
499
									createOfferRequest.setEndDateTime(offer.getEndDateTime().toLocalDate());
26588 tejbeer 500
									createOfferRequest.setTotalSale(value.get(loginDetails.getFofoId()));
27352 tejbeer 501
									createOfferRequest.setOfferMargin(offerMargins);
26588 tejbeer 502
									cors.add(createOfferRequest);
503
 
504
									model.addAttribute("sales", value.get(loginDetails.getFofoId()));
505
								}
506
							}
507
 
508
						}
26327 amit.gupta 509
					}
26588 tejbeer 510
					model.addAttribute("offers", cors);
511
 
26674 tejbeer 512
				}
26588 tejbeer 513
 
25180 amit.gupta 514
			} catch (ProfitMandiBusinessException e) {
515
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
516
 
517
			}
22481 ashik.ali 518
		}
25649 tejbeer 519
 
520
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 521
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 522
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
523
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 524
				currentMonthEnd) / 2;
25747 amit.gupta 525
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
526
				currentMonthStart) / 2;
527
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 528
				currentMonthEnd) / 2;
529
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
530
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
531
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 532
 
25653 amit.gupta 533
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
534
				currentMonthEnd);
25651 tejbeer 535
 
25653 amit.gupta 536
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
537
				currentMonthStart, currentMonthEnd);
538
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
539
			invalidHygieneCount = 1;
540
		}
541
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 542
 
25197 amit.gupta 543
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
544
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27352 tejbeer 545
		if (loginDetails.isReadOnly()) {
27229 amit.gupta 546
			return "dashboard-readonly";
547
		} else {
548
			return "dashboard1";
549
		}
21615 kshitij.so 550
	}
23923 amit.gupta 551
 
27355 tejbeer 552
	@RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
553
	public String getOfferMargins(HttpServletRequest request,
554
			@RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
555
		Offer offer = offerRepository.selectById(offerId);
556
 
557
		LOGGER.info("offerId" + offer.getId());
558
 
559
		Map<Integer, Double> value = offerRepository.selectSumOfferByRetailer(offer.getStartDateTime(),
560
				offer.getEndDateTime(), 0, offer, true);
561
 
562
		LOGGER.info("value" + value);
563
		List<Offermargin> offerMargin = offerMarginRepository.selectByOfferId(offerId);
564
 
565
		ItemTypeParams scp = gson.fromJson(offer.getItemParam(), ItemTypeParams.class);
566
		if (offer.getItemCriteria().equals(ItemCriteriaType.Multiple_Brand)) {
567
			List<String> brands = scp.getBrands();
568
			model.addAttribute("brands", brands);
569
		}
570
		if (offer.getItemCriteria().equals(ItemCriteriaType.Item_Model)) {
571
			List<Integer> catalogIds = scp.getCatalogId();
572
			List<Item> newList = new ArrayList<>();
573
			Set<Integer> catalogId = new HashSet<>();
574
			List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds.stream().collect(Collectors.toSet()));
575
			for (Item item : items) {
576
				if (catalogId.add(item.getCatalogItemId())) {
577
					newList.add(item);
578
				}
579
			}
580
			model.addAttribute("items", newList);
581
		}
582
 
583
		model.addAttribute("offerMargin", offerMargin);
584
		model.addAttribute("offer", offer);
585
 
586
		return "offer_margin_detail_partner";
587
 
588
	}
589
 
26055 tejbeer 590
	private ChartModel getBrandChart(int fofoId) {
591
 
592
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
593
 
594
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
595
 
596
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
597
 
598
		Map<String, Double> brandwisesale = fofoOrderItemRepository
599
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 600
 
601
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
602
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
603
 
604
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
605
 
26055 tejbeer 606
		LOGGER.info("brandwisesale" + brandwisesale);
607
 
608
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
609
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
610
 
26244 tejbeer 611
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
612
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
613
				Optional.of(false));
614
		LOGGER.info("accesorieslmtdsale" + accesorieslmtdsale);
26055 tejbeer 615
		ChartModel cm = new ChartModel();
616
 
617
		List<String> labels = new ArrayList<>();
618
		labels.addAll(brandwisesale.keySet());
26244 tejbeer 619
		labels.add("accessories");
26055 tejbeer 620
		List<Double> values = new ArrayList<>();
621
		values.addAll(brandwisesale.values());
26244 tejbeer 622
		values.addAll(accesoriesmtdsale.values());
26055 tejbeer 623
 
624
		List<Double> lmtdValues = new ArrayList<>();
625
		lmtdValues.addAll(lmtdBrandWiseSale.values());
26244 tejbeer 626
		lmtdValues.addAll(accesorieslmtdsale.values());
26055 tejbeer 627
 
628
		DatasetModel dsm = new DatasetModel();
629
		dsm.setLabel("mtd sales");
630
 
631
		List<String> backgroundColor = new ArrayList<>();
632
		for (Entry<String, Double> bs : brandwisesale.entrySet()) {
633
			backgroundColor.add("#3e95cd");
634
		}
26244 tejbeer 635
		backgroundColor.add("#3e95cd");
26055 tejbeer 636
		dsm.setBackgroundColor(backgroundColor);
637
		dsm.setData(values);
638
 
639
		DatasetModel lmtddsm = new DatasetModel();
640
		lmtddsm.setLabel("lmtd sales");
641
 
642
		List<String> background = new ArrayList<>();
643
		for (Entry<String, Double> bs : lmtdBrandWiseSale.entrySet()) {
644
			background.add("#8e5ea2");
645
		}
26244 tejbeer 646
		background.add("#8e5ea2");
26055 tejbeer 647
		lmtddsm.setBackgroundColor(background);
648
		lmtddsm.setData(lmtdValues);
649
 
650
		List<DatasetModel> datasets = new ArrayList<>();
651
		datasets.add(dsm);
652
		datasets.add(lmtddsm);
653
 
654
		DataModel dm = new DataModel();
655
		dm.setDatasets(datasets);
656
		dm.setLabels(labels);
657
 
658
		LegendModel lm = new LegendModel();
659
		lm.setDisplay(true);
660
 
661
		TitleModel tm = new TitleModel();
662
		tm.setText("Brand Wise Sale Graph");
663
		tm.setDisplay(true);
664
 
665
		OptionsModel om = new OptionsModel();
666
		om.setLegend(lm);
667
		om.setTitle(tm);
668
 
669
		cm.setType("bar");
670
		cm.setData(dm);
671
		cm.setOptions(om);
672
 
673
		return cm;
674
 
675
	}
676
 
26418 tejbeer 677
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 678
		List<Menu> menus = null;
26011 amit.gupta 679
		try {
680
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
681
			List<Position> positions = positionRepository.selectAll(authUser.getId());
26418 tejbeer 682
			Map<Integer, AuthUser> authIdAndAuthUserMap = null;
26460 amit.gupta 683
			Map<Integer, PartnerDetailModel> authIdAndallValues = null;
26418 tejbeer 684
			if (positions.size() > 0) {
27352 tejbeer 685
				if (positions.stream()
686
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
687
								|| x.getEscalationType().equals(EscalationType.L4)
688
								|| x.getEscalationType().equals(EscalationType.L5))
689
						.count() > 0) {
26418 tejbeer 690
 
691
					authIdAndAuthUserMap = authRepository.selectAllActiveUser().stream()
692
							.collect(Collectors.toMap(x -> x.getId(), x -> x));
26588 tejbeer 693
 
26997 amit.gupta 694
					AuthUser unmappedAuthUser = new AuthUser();
695
					unmappedAuthUser.setFirstName("Unmapped");
696
					unmappedAuthUser.setLastName("Partners");
26999 amit.gupta 697
					authIdAndAuthUserMap.put(-1, unmappedAuthUser);
26997 amit.gupta 698
 
26468 amit.gupta 699
					AuthUser dummyAuthUser = new AuthUser();
700
					dummyAuthUser.setFirstName("Total");
701
					dummyAuthUser.setLastName("Values");
702
					authIdAndAuthUserMap.put(0, dummyAuthUser);
27352 tejbeer 703
 
26422 tejbeer 704
					authIdAndallValues = this.getL2AuthUserPartnerDetail();
26418 tejbeer 705
				}
706
			}
707
 
27415 tejbeer 708
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
709
					.contains(email)) {
26029 amit.gupta 710
				menus = menuRepository.selectAll();
711
			} else if (positions.size() > 0) {
27108 amit.gupta 712
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 713
					menus = menuRepository.selectAll();
714
				} else {
715
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
716
							.map(x -> x.getMenuId()).collect(Collectors.toList());
717
					LOGGER.info("Menu Ids are {}", menuIds);
718
					if (menuIds.size() > 0) {
719
						menus = menuRepository.selectAllByIds(menuIds);
720
					}
26022 amit.gupta 721
				}
26090 amit.gupta 722
				List<Position> salesPositions = positions.stream()
723
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
724
						.collect(Collectors.toList());
725
				if (salesPositions.size() > 0) {
726
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 727
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 728
						positionRetailers.addAll(customRetailers);
729
					});
730
					model.addAttribute("retailers", gson.toJson(positionRetailers));
731
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 732
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 733
				}
26114 amit.gupta 734
				List<Position> warehousePositions = positions.stream()
735
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
736
						.collect(Collectors.toList());
737
				if (warehousePositions.size() > 0) {
738
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 739
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 740
						positionRetailers.addAll(customRetailers);
741
					});
742
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
743
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 744
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 745
				}
26142 amit.gupta 746
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 747
 
26022 amit.gupta 748
			}
26418 tejbeer 749
			model.addAttribute("authIdAndallValues", authIdAndallValues);
750
			model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
751
 
26012 amit.gupta 752
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 753
		}
26028 amit.gupta 754
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 755
		LOGGER.info("menu" + menuList);
26022 amit.gupta 756
		model.addAttribute("menu", menuList);
26012 amit.gupta 757
		return "admin";
758
	}
759
 
26468 amit.gupta 760
	/*
761
	 * @RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET) public
762
	 * String L1AuthUsersDetail(HttpServletRequest request, Model
763
	 * model, @RequestParam int authId) throws Exception {
764
	 * 
765
	 * Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
766
	 * 
767
	 * LocalDateTime curDate = LocalDate.now().atStartOfDay(); Map<Integer, Double>
768
	 * lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
769
	 * curDate.withDayOfMonth(1).minusMonths(1),
770
	 * curDate.with(LocalTime.MAX).minusMonths(1), 0, false); Map<Integer, Double>
771
	 * mtdSale =
772
	 * fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth
773
	 * (1), curDate.with(LocalTime.MAX), 0, false); Map<Integer, List<Integer>>
774
	 * L2L1Mapping = csService.getL1L2Mapping();
775
	 * 
776
	 * LOGGER.info("L2L1Mapping" + L2L1Mapping); List<Integer> l1authIds =
777
	 * L2L1Mapping.get(authId);
778
	 * 
779
	 * Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>(); Map<Integer,
780
	 * Object> authIdAndAuthUserMap = new LinkedHashMap<>();
781
	 * 
782
	 * Map<Integer, Long> ticketMap =
783
	 * ticketRepository.selectAllNotClosedTicketsGroupByRetailer(); for (Integer
784
	 * l1AuthId : l1authIds) {
785
	 * 
786
	 * double totallmtdAmount = 0; double totalmtdAmount = 0; int totalTicketCount =
787
	 * 0; float totalTodayInvestment = 0; float totalStockInInvestment = 0; double
788
	 * currentMonthRatingAllPartners = 0; Map<Integer, Long> leadCount =
789
	 * leadRepository.selectByAssignAuthIdAndStatus(l1AuthId, LeadStatus.followUp)
790
	 * .stream().collect(Collectors.groupingBy(Lead::getAssignTo,
791
	 * Collectors.counting()));
792
	 * 
793
	 * AuthUser authUser = authRepository.selectById(l1AuthId);
794
	 * 
795
	 * authIdAndAuthUserMap.put(l1AuthId, authUser);
796
	 * 
797
	 * List<Integer> fofoIds = pp.get(l1AuthId);
798
	 * 
799
	 * Map<Integer, PartnerDailyInvestment> partnerInvestentMap =
800
	 * partnerInvestmentService .getInvestment(fofoIds,
801
	 * 0).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
802
	 * 
803
	 * for (Integer fId : fofoIds) { try { PartnerDailyInvestment investment =
804
	 * partnerInvestentMap.get(fId); totalTodayInvestment +=
805
	 * investment.getTotalInvestment(); totalStockInInvestment +=
806
	 * investment.getInStockAmount(); } catch (Exception e) { }
807
	 * 
808
	 * double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
809
	 * curDate.withDayOfMonth(1).minusMonths(1),
810
	 * curDate.plusMonths(1).withDayOfMonth(1));
811
	 * 
812
	 * currentMonthRatingAllPartners += currentMonthRating;
813
	 * 
814
	 * fofoIds.size();
815
	 * 
816
	 * Double lmtdAmount = lmtdSale.get(fId); Double mtdAmount = mtdSale.get(fId);
817
	 * Long ticketCount = ticketMap.get(fId); if (ticketCount != null) {
818
	 * totalTicketCount += ticketCount; }
819
	 * 
820
	 * if (lmtdAmount != null) { totallmtdAmount += lmtdAmount; }
821
	 * 
822
	 * if (mtdAmount != null) { totalmtdAmount += mtdAmount; }
823
	 * 
824
	 * } LOGGER.info("currentMonthRatingAllPartners" +
825
	 * currentMonthRatingAllPartners); LOGGER.info("size" + fofoIds.size()); double
826
	 * totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
827
	 * 
828
	 * LOGGER.info("totalHygieneRating" + totalHygieneRating);
829
	 * 
830
	 * PartnerDetailModel pm = new PartnerDetailModel();
831
	 * pm.setLmtd(totallmtdAmount); pm.setMtd(totalmtdAmount); if
832
	 * (leadCount.get(l1AuthId) != null) {
833
	 * pm.setLeads(leadCount.get(l1AuthId).intValue()); } else { pm.setLeads(0); }
834
	 * 
835
	 * pm.setInvestment(totalTodayInvestment);
836
	 * pm.setStockInInvestment(totalStockInInvestment);
837
	 * pm.setTicket(totalTicketCount); pm.setHygiene((double)
838
	 * Math.round(totalHygieneRating)); authIdAndallValues.put(l1AuthId, pm);
839
	 * 
840
	 * } model.addAttribute("authIdAndallValues", authIdAndallValues);
841
	 * model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
842
	 * LOGGER.info("authIdAndallValues" + authIdAndallValues);
843
	 * 
844
	 * return "auth_user_detail"; }
845
	 */
26418 tejbeer 846
 
26468 amit.gupta 847
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 848
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
849
			throws Exception {
850
 
851
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 852
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 853
 
26468 amit.gupta 854
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
855
		if (authId != 0) {
856
			List<Integer> fofoIds = pp.get(authId);
857
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
858
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 859
		} else {
26418 tejbeer 860
		}
861
 
862
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
863
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
864
 
865
		return "auth_user_partner_detail";
26468 amit.gupta 866
	}
26418 tejbeer 867
 
26114 amit.gupta 868
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
869
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 870
		positionRetailers.stream().forEach(x -> {
871
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 872
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
873
			}
874
		});
26114 amit.gupta 875
		return gson.toJson(warehouses);
876
 
877
	}
878
 
26012 amit.gupta 879
	private List<Menu> prepareMenu(List<Menu> menus) {
880
		List<Menu> returnMenu = new ArrayList<>();
881
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
882
		for (Menu menu : menus) {
883
			if (menu.get_parent() == null) {
26014 amit.gupta 884
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 885
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 886
				}
887
			} else {
26012 amit.gupta 888
				Menu parentMenu = menu.get_parent();
889
				if (!subMenuMap.containsKey(parentMenu)) {
890
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 891
				}
26012 amit.gupta 892
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 893
			}
894
		}
26012 amit.gupta 895
		subMenuMap.entrySet().stream().forEach(entry -> {
896
			entry.getKey().setSubMenus(entry.getValue());
897
			returnMenu.add(entry.getKey());
898
		});
899
		return returnMenu;
26005 amit.gupta 900
	}
901
 
24288 amit.gupta 902
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 903
	private boolean hasGift(int fofoId) {
904
		try {
24288 amit.gupta 905
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
906
					.getAvailability() > 0;
24203 amit.gupta 907
		} catch (ProfitMandiBusinessException e) {
908
			return false;
909
		}
910
	}
24288 amit.gupta 911
 
22354 ashik.ali 912
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 913
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 914
		model.addAttribute("appContextPath", request.getContextPath());
915
		return "contact-us";
916
	}
23923 amit.gupta 917
 
25649 tejbeer 918
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 919
	public String getNotificationsWithType(HttpServletRequest request,
920
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 921
			@RequestParam(name = "offset", defaultValue = "0") int offset,
922
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
923
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 924
		int userId = 0;
925
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
926
		if (isAdmin) {
927
			userId = loginDetails.getFofoId();
928
		} else {
929
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
930
		}
25683 tejbeer 931
		List<Notification> notifications = null;
932
 
26086 tejbeer 933
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
934
				userId, offset, limit);
935
		LOGGER.info("messageType" + messageType);
936
		notifications = getNotifications(notificationCampaigns, messageType);
937
 
25683 tejbeer 938
		model.addAttribute("notifications", notifications);
939
 
940
		LOGGER.info("notifications" + notifications);
941
		return "notification-template";
942
	}
943
 
944
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
945
			throws ProfitMandiBusinessException {
946
		List<Notification> notifications = new ArrayList<>();
947
		Document document = null;
948
		if (messageType != null) {
949
			for (NotificationCampaign notificationCampaign : nc) {
950
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 951
					Notification ns = new Notification();
952
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
953
							SimpleCampaignParams.class);
954
					Campaign campaign = new SimpleCampaign(scp);
955
					LocalDateTime expire = campaign.getExpireTimestamp();
956
					ns.setCid(Integer.toString(notificationCampaign.getId()));
957
					ns.setType(campaign.getType());
958
					ns.setMessage(campaign.getMessage());
959
					ns.setTitle(campaign.getTitle());
25651 tejbeer 960
					if (notificationCampaign.getDocumentId() != null) {
961
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
962
						ns.setDocumentName(document.getDisplayName());
963
					}
25683 tejbeer 964
					ns.setUrl(campaign.getUrl());
25649 tejbeer 965
					ns.setShowImage(campaign.getShowImage());
966
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 967
					ns.setDocumentId(notificationCampaign.getDocumentId());
968
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 969
					ns.setCreated(
970
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
971
									* 1000);
972
					if (LocalDateTime.now().isAfter(expire)) {
973
						ns.setExpired(true);
974
					} else {
975
						ns.setExpired(false);
976
					}
977
					notifications.add(ns);
978
				}
979
			}
25683 tejbeer 980
		} else {
981
			for (NotificationCampaign notificationCampaign : nc) {
982
 
983
				Notification ns = new Notification();
984
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
985
						SimpleCampaignParams.class);
986
				Campaign campaign = new SimpleCampaign(scp);
987
				LocalDateTime expire = campaign.getExpireTimestamp();
988
				ns.setCid(Integer.toString(notificationCampaign.getId()));
989
				ns.setType(campaign.getType());
990
				ns.setMessage(campaign.getMessage());
991
				ns.setTitle(campaign.getTitle());
992
				if (notificationCampaign.getDocumentId() != null) {
993
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
994
					ns.setDocumentName(document.getDisplayName());
995
				}
996
				ns.setUrl(campaign.getUrl());
997
				ns.setShowImage(campaign.getShowImage());
998
				ns.setImageUrl(campaign.getImageUrl());
999
				ns.setDocumentId(notificationCampaign.getDocumentId());
1000
				ns.setMessageType(notificationCampaign.getMessageType());
1001
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1002
						* 1000);
1003
				if (LocalDateTime.now().isAfter(expire)) {
1004
					ns.setExpired(true);
1005
				} else {
1006
					ns.setExpired(false);
1007
				}
1008
				notifications.add(ns);
1009
			}
1010
 
25649 tejbeer 1011
		}
25683 tejbeer 1012
		return notifications;
25651 tejbeer 1013
 
1014
	}
25649 tejbeer 1015
 
25651 tejbeer 1016
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1017
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1018
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1019
			throws ProfitMandiBusinessException {
1020
		Document document = documentRepository.selectById(documentId);
1021
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1022
		if (nc.getDocumentId() == null) {
1023
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1024
		}
1025
		if (nc.getDocumentId() != documentId) {
1026
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1027
		}
1028
		return responseSender.ok(document);
25649 tejbeer 1029
	}
1030
 
25651 tejbeer 1031
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1032
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1033
			throws ProfitMandiBusinessException {
1034
 
1035
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1036
 
1037
		if (nc.getDocumentId() == null) {
1038
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1039
		}
1040
 
1041
		Document document = documentRepository.selectById(nc.getDocumentId());
1042
 
1043
		FileInputStream file = null;
1044
		try {
1045
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1046
		} catch (FileNotFoundException e) {
1047
			LOGGER.error("Retailer Document file not found : ", e);
1048
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1049
		}
1050
		// ByteArrayOutputStream byteArrayOutputStream = new
1051
		// ByteArrayOutputStream();
1052
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1053
 
1054
		final HttpHeaders headers = new HttpHeaders();
1055
		String contentType = "";
1056
		if (document.getContentType() == ContentType.JPEG) {
1057
			contentType = "image/jpeg";
1058
		} else if (document.getContentType() == ContentType.PNG) {
1059
			contentType = "image/png";
1060
		} else if (document.getContentType() == ContentType.PDF) {
1061
			contentType = "application/pdf";
1062
		}
1063
		headers.set("Content-Type", contentType);
1064
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1065
		headers.setContentLength(document.getSize());
1066
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1067
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1068
	}
26460 amit.gupta 1069
 
1070
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1071
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1072
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1073
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1074
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1075
			List<Integer> authIds = l2l1.getValue();
1076
			authIds.add(l2l1.getKey());
1077
 
1078
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1079
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1080
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1081
			if (!leads.isEmpty()) {
1082
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1083
			} else {
1084
				authIdAndleadsCountMap.put(auth.getId(), 0);
1085
			}
26422 tejbeer 1086
		}
26468 amit.gupta 1087
 
26460 amit.gupta 1088
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1089
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1090
				.collect(Collectors.toList());
26433 tejbeer 1091
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1092
 
26460 amit.gupta 1093
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1094
 
26460 amit.gupta 1095
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1096
		for (int authUserId : pp.keySet()) {
1097
			if (L2L1Mapping.keySet().contains(authUserId)) {
1098
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1099
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1100
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1101
						.collect(Collectors.toList());
26927 amit.gupta 1102
				LOGGER.info("authUserId {}, partnerDetails {}" + authUserId, partnerDetails);
26460 amit.gupta 1103
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1104
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1105
			}
1106
		}
26997 amit.gupta 1107
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1108
				.collect(Collectors.toList());
26468 amit.gupta 1109
		PartnerDetailModel partnerDetailModel = partnerStatsService
1110
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1111
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1112
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1113
		return authIdAndallValues;
1114
	}
1115
 
21615 kshitij.so 1116
}