Subversion Repositories SmartDukaan

Rev

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