Subversion Repositories SmartDukaan

Rev

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