Subversion Repositories SmartDukaan

Rev

Rev 27548 | Rev 27555 | 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
 
27529 tejbeer 805
					warehouseStockMap = saholicInventoryCISRepository.selectGroupByWarehouse().stream()
27509 tejbeer 806
							.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
27352 tejbeer 807
 
27539 tejbeer 808
					List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
809
							.selectGroupByWarehouse();
810
					if (!warehouseStocks.isEmpty()) {
811
						for (WarehouseWiseStockModel warehouseStock : warehouseStocks) {
812
							stockValue += warehouseStock.getStockValue();
813
							stockQty += warehouseStock.getStockQty();
814
							pendingIndent += warehouseStock.getPendingIndent();
27542 tejbeer 815
							tertiary += warehouseStock.getTertiary();
27539 tejbeer 816
						}
817
						WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
818
						ws.setStockQty(stockQty);
819
						ws.setStockValue(stockValue);
820
						ws.setPendingIndent(pendingIndent);
27542 tejbeer 821
						ws.setTertiary(tertiary);
27539 tejbeer 822
						ws.setWarehouseId(0);
823
						warehouseStockMap.put(0, ws);
824
 
825
					}
826
 
27529 tejbeer 827
					rct = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
27509 tejbeer 828
					LOGGER.info("warehouseStockMap" + warehouseStockMap);
27545 tejbeer 829
					warehousePartnerDetailMap = this.getWarehousePartnerDetail();
830
					LOGGER.info("warehousePartnerDetailMap" + warehousePartnerDetailMap);
27552 tejbeer 831
 
26418 tejbeer 832
				}
833
			}
834
 
27415 tejbeer 835
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
836
					.contains(email)) {
26029 amit.gupta 837
				menus = menuRepository.selectAll();
838
			} else if (positions.size() > 0) {
27108 amit.gupta 839
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 840
					menus = menuRepository.selectAll();
841
				} else {
842
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
843
							.map(x -> x.getMenuId()).collect(Collectors.toList());
844
					LOGGER.info("Menu Ids are {}", menuIds);
845
					if (menuIds.size() > 0) {
846
						menus = menuRepository.selectAllByIds(menuIds);
847
					}
26022 amit.gupta 848
				}
26090 amit.gupta 849
				List<Position> salesPositions = positions.stream()
850
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
851
						.collect(Collectors.toList());
852
				if (salesPositions.size() > 0) {
853
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 854
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 855
						positionRetailers.addAll(customRetailers);
856
					});
857
					model.addAttribute("retailers", gson.toJson(positionRetailers));
858
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 859
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 860
				}
26114 amit.gupta 861
				List<Position> warehousePositions = positions.stream()
862
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
863
						.collect(Collectors.toList());
864
				if (warehousePositions.size() > 0) {
865
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 866
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 867
						positionRetailers.addAll(customRetailers);
868
					});
869
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
870
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 871
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 872
				}
26142 amit.gupta 873
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 874
 
26022 amit.gupta 875
			}
27539 tejbeer 876
			LOGGER.info("warehouseMap" + wm);
27529 tejbeer 877
			model.addAttribute("reporticoDate", rct);
27552 tejbeer 878
 
27545 tejbeer 879
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 880
			model.addAttribute("warehouseMap", wm);
27509 tejbeer 881
			model.addAttribute("warehouseStockMap", warehouseStockMap);
26012 amit.gupta 882
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 883
		}
26028 amit.gupta 884
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 885
		LOGGER.info("menu" + menuList);
26022 amit.gupta 886
		model.addAttribute("menu", menuList);
26012 amit.gupta 887
		return "admin";
888
	}
889
 
26468 amit.gupta 890
	/*
891
	 * @RequestMapping(value = "/getL1AuthUser", method = RequestMethod.GET) public
892
	 * String L1AuthUsersDetail(HttpServletRequest request, Model
893
	 * model, @RequestParam int authId) throws Exception {
894
	 * 
895
	 * Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
896
	 * 
897
	 * LocalDateTime curDate = LocalDate.now().atStartOfDay(); Map<Integer, Double>
898
	 * lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
899
	 * curDate.withDayOfMonth(1).minusMonths(1),
900
	 * curDate.with(LocalTime.MAX).minusMonths(1), 0, false); Map<Integer, Double>
901
	 * mtdSale =
902
	 * fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth
903
	 * (1), curDate.with(LocalTime.MAX), 0, false); Map<Integer, List<Integer>>
904
	 * L2L1Mapping = csService.getL1L2Mapping();
905
	 * 
906
	 * LOGGER.info("L2L1Mapping" + L2L1Mapping); List<Integer> l1authIds =
907
	 * L2L1Mapping.get(authId);
908
	 * 
909
	 * Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>(); Map<Integer,
910
	 * Object> authIdAndAuthUserMap = new LinkedHashMap<>();
911
	 * 
912
	 * Map<Integer, Long> ticketMap =
913
	 * ticketRepository.selectAllNotClosedTicketsGroupByRetailer(); for (Integer
914
	 * l1AuthId : l1authIds) {
915
	 * 
916
	 * double totallmtdAmount = 0; double totalmtdAmount = 0; int totalTicketCount =
917
	 * 0; float totalTodayInvestment = 0; float totalStockInInvestment = 0; double
918
	 * currentMonthRatingAllPartners = 0; Map<Integer, Long> leadCount =
919
	 * leadRepository.selectByAssignAuthIdAndStatus(l1AuthId, LeadStatus.followUp)
920
	 * .stream().collect(Collectors.groupingBy(Lead::getAssignTo,
921
	 * Collectors.counting()));
922
	 * 
923
	 * AuthUser authUser = authRepository.selectById(l1AuthId);
924
	 * 
925
	 * authIdAndAuthUserMap.put(l1AuthId, authUser);
926
	 * 
927
	 * List<Integer> fofoIds = pp.get(l1AuthId);
928
	 * 
929
	 * Map<Integer, PartnerDailyInvestment> partnerInvestentMap =
930
	 * partnerInvestmentService .getInvestment(fofoIds,
931
	 * 0).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
932
	 * 
933
	 * for (Integer fId : fofoIds) { try { PartnerDailyInvestment investment =
934
	 * partnerInvestentMap.get(fId); totalTodayInvestment +=
935
	 * investment.getTotalInvestment(); totalStockInInvestment +=
936
	 * investment.getInStockAmount(); } catch (Exception e) { }
937
	 * 
938
	 * double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
939
	 * curDate.withDayOfMonth(1).minusMonths(1),
940
	 * curDate.plusMonths(1).withDayOfMonth(1));
941
	 * 
942
	 * currentMonthRatingAllPartners += currentMonthRating;
943
	 * 
944
	 * fofoIds.size();
945
	 * 
946
	 * Double lmtdAmount = lmtdSale.get(fId); Double mtdAmount = mtdSale.get(fId);
947
	 * Long ticketCount = ticketMap.get(fId); if (ticketCount != null) {
948
	 * totalTicketCount += ticketCount; }
949
	 * 
950
	 * if (lmtdAmount != null) { totallmtdAmount += lmtdAmount; }
951
	 * 
952
	 * if (mtdAmount != null) { totalmtdAmount += mtdAmount; }
953
	 * 
954
	 * } LOGGER.info("currentMonthRatingAllPartners" +
955
	 * currentMonthRatingAllPartners); LOGGER.info("size" + fofoIds.size()); double
956
	 * totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
957
	 * 
958
	 * LOGGER.info("totalHygieneRating" + totalHygieneRating);
959
	 * 
960
	 * PartnerDetailModel pm = new PartnerDetailModel();
961
	 * pm.setLmtd(totallmtdAmount); pm.setMtd(totalmtdAmount); if
962
	 * (leadCount.get(l1AuthId) != null) {
963
	 * pm.setLeads(leadCount.get(l1AuthId).intValue()); } else { pm.setLeads(0); }
964
	 * 
965
	 * pm.setInvestment(totalTodayInvestment);
966
	 * pm.setStockInInvestment(totalStockInInvestment);
967
	 * pm.setTicket(totalTicketCount); pm.setHygiene((double)
968
	 * Math.round(totalHygieneRating)); authIdAndallValues.put(l1AuthId, pm);
969
	 * 
970
	 * } model.addAttribute("authIdAndallValues", authIdAndallValues);
971
	 * model.addAttribute("authIdAndAuthUserMap", authIdAndAuthUserMap);
972
	 * LOGGER.info("authIdAndallValues" + authIdAndallValues);
973
	 * 
974
	 * return "auth_user_detail"; }
975
	 */
26418 tejbeer 976
 
26468 amit.gupta 977
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 978
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
979
			throws Exception {
980
 
981
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 982
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 983
 
26468 amit.gupta 984
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
985
		if (authId != 0) {
986
			List<Integer> fofoIds = pp.get(authId);
987
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
988
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 989
		} else {
26418 tejbeer 990
		}
991
 
992
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
993
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
994
 
995
		return "auth_user_partner_detail";
26468 amit.gupta 996
	}
26418 tejbeer 997
 
27545 tejbeer 998
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
999
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1000
			throws Exception {
1001
 
1002
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1003
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1004
		if (warehouseId != 0) {
1005
 
1006
			List<Integer> fofoIds = fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1007
					.map(x -> x.getId()).collect(Collectors.toList());
1008
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1009
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1010
		} else {
1011
		}
1012
 
1013
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1014
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1015
 
1016
		return "auth_user_partner_detail";
1017
	}
1018
 
27509 tejbeer 1019
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27542 tejbeer 1020
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1021
			throws Exception {
27509 tejbeer 1022
 
27529 tejbeer 1023
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = saholicInventoryCISRepository
27509 tejbeer 1024
				.selectGroupByWarehouseAndBrand(warehouseId);
27542 tejbeer 1025
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1026
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1027
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1028
		model.addAttribute("warehouseMap", warehouseMap);
1029
		LOGGER.info("warehouseWiseBrandStock" + warehouseWiseBrandStock);
1030
		return "warehouse_brand_stock";
1031
	}
1032
 
27529 tejbeer 1033
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1034
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1035
		inventoryService.getItemAvailabilityAndIndent();
1036
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1037
		return "response";
1038
	}
1039
 
27539 tejbeer 1040
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1041
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1042
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1043
			throws Exception {
27509 tejbeer 1044
 
1045
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1046
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1047
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1048
 
27509 tejbeer 1049
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1050
		model.addAttribute("brands", listbrands);
27538 tejbeer 1051
		model.addAttribute("listCategory", listCategory);
1052
 
27529 tejbeer 1053
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1054
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1055
		model.addAttribute("selectedCategory", category);
1056
 
27509 tejbeer 1057
		return "warehouse_brand_item_stock";
1058
	}
1059
 
27538 tejbeer 1060
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1061
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1062
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1063
			throws Exception {
27539 tejbeer 1064
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1065
		if (warehouseId.contains(0)) {
1066
			warehouseId.addAll(warehouseMap.keySet());
1067
		}
27538 tejbeer 1068
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1069
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1070
 
27538 tejbeer 1071
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1072
		model.addAttribute("warehouseMap", warehouseMap);
1073
 
1074
		LOGGER.info("warehouseWiseItemStock" + warehouseWiseItemStock);
1075
		return "warehouse_item_details";
1076
	}
1077
 
26114 amit.gupta 1078
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1079
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1080
		positionRetailers.stream().forEach(x -> {
1081
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1082
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1083
			}
1084
		});
26114 amit.gupta 1085
		return gson.toJson(warehouses);
1086
 
1087
	}
1088
 
26012 amit.gupta 1089
	private List<Menu> prepareMenu(List<Menu> menus) {
1090
		List<Menu> returnMenu = new ArrayList<>();
1091
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1092
		for (Menu menu : menus) {
1093
			if (menu.get_parent() == null) {
26014 amit.gupta 1094
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1095
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1096
				}
1097
			} else {
26012 amit.gupta 1098
				Menu parentMenu = menu.get_parent();
1099
				if (!subMenuMap.containsKey(parentMenu)) {
1100
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1101
				}
26012 amit.gupta 1102
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1103
			}
1104
		}
26012 amit.gupta 1105
		subMenuMap.entrySet().stream().forEach(entry -> {
1106
			entry.getKey().setSubMenus(entry.getValue());
1107
			returnMenu.add(entry.getKey());
1108
		});
1109
		return returnMenu;
26005 amit.gupta 1110
	}
1111
 
24288 amit.gupta 1112
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1113
	private boolean hasGift(int fofoId) {
1114
		try {
24288 amit.gupta 1115
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1116
					.getAvailability() > 0;
24203 amit.gupta 1117
		} catch (ProfitMandiBusinessException e) {
1118
			return false;
1119
		}
1120
	}
24288 amit.gupta 1121
 
22354 ashik.ali 1122
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1123
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1124
		model.addAttribute("appContextPath", request.getContextPath());
1125
		return "contact-us";
1126
	}
23923 amit.gupta 1127
 
25649 tejbeer 1128
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1129
	public String getNotificationsWithType(HttpServletRequest request,
1130
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1131
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1132
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1133
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1134
		int userId = 0;
1135
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1136
		if (isAdmin) {
1137
			userId = loginDetails.getFofoId();
1138
		} else {
1139
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1140
		}
25683 tejbeer 1141
		List<Notification> notifications = null;
1142
 
26086 tejbeer 1143
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1144
				userId, offset, limit);
1145
		LOGGER.info("messageType" + messageType);
1146
		notifications = getNotifications(notificationCampaigns, messageType);
1147
 
25683 tejbeer 1148
		model.addAttribute("notifications", notifications);
1149
 
1150
		LOGGER.info("notifications" + notifications);
1151
		return "notification-template";
1152
	}
1153
 
1154
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1155
			throws ProfitMandiBusinessException {
1156
		List<Notification> notifications = new ArrayList<>();
1157
		Document document = null;
1158
		if (messageType != null) {
1159
			for (NotificationCampaign notificationCampaign : nc) {
1160
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1161
					Notification ns = new Notification();
1162
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1163
							SimpleCampaignParams.class);
1164
					Campaign campaign = new SimpleCampaign(scp);
1165
					LocalDateTime expire = campaign.getExpireTimestamp();
1166
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1167
					ns.setType(campaign.getType());
1168
					ns.setMessage(campaign.getMessage());
1169
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1170
					if (notificationCampaign.getDocumentId() != null) {
1171
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1172
						ns.setDocumentName(document.getDisplayName());
1173
					}
25683 tejbeer 1174
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1175
					ns.setShowImage(campaign.getShowImage());
1176
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1177
					ns.setDocumentId(notificationCampaign.getDocumentId());
1178
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1179
					ns.setCreated(
1180
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1181
									* 1000);
1182
					if (LocalDateTime.now().isAfter(expire)) {
1183
						ns.setExpired(true);
1184
					} else {
1185
						ns.setExpired(false);
1186
					}
1187
					notifications.add(ns);
1188
				}
1189
			}
25683 tejbeer 1190
		} else {
1191
			for (NotificationCampaign notificationCampaign : nc) {
1192
 
1193
				Notification ns = new Notification();
1194
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1195
						SimpleCampaignParams.class);
1196
				Campaign campaign = new SimpleCampaign(scp);
1197
				LocalDateTime expire = campaign.getExpireTimestamp();
1198
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1199
				ns.setType(campaign.getType());
1200
				ns.setMessage(campaign.getMessage());
1201
				ns.setTitle(campaign.getTitle());
1202
				if (notificationCampaign.getDocumentId() != null) {
1203
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1204
					ns.setDocumentName(document.getDisplayName());
1205
				}
1206
				ns.setUrl(campaign.getUrl());
1207
				ns.setShowImage(campaign.getShowImage());
1208
				ns.setImageUrl(campaign.getImageUrl());
1209
				ns.setDocumentId(notificationCampaign.getDocumentId());
1210
				ns.setMessageType(notificationCampaign.getMessageType());
1211
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1212
						* 1000);
1213
				if (LocalDateTime.now().isAfter(expire)) {
1214
					ns.setExpired(true);
1215
				} else {
1216
					ns.setExpired(false);
1217
				}
1218
				notifications.add(ns);
1219
			}
1220
 
25649 tejbeer 1221
		}
25683 tejbeer 1222
		return notifications;
25651 tejbeer 1223
 
1224
	}
25649 tejbeer 1225
 
25651 tejbeer 1226
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1227
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1228
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1229
			throws ProfitMandiBusinessException {
1230
		Document document = documentRepository.selectById(documentId);
1231
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1232
		if (nc.getDocumentId() == null) {
1233
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1234
		}
1235
		if (nc.getDocumentId() != documentId) {
1236
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1237
		}
1238
		return responseSender.ok(document);
25649 tejbeer 1239
	}
1240
 
25651 tejbeer 1241
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1242
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1243
			throws ProfitMandiBusinessException {
1244
 
1245
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1246
 
1247
		if (nc.getDocumentId() == null) {
1248
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1249
		}
1250
 
1251
		Document document = documentRepository.selectById(nc.getDocumentId());
1252
 
1253
		FileInputStream file = null;
1254
		try {
1255
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1256
		} catch (FileNotFoundException e) {
1257
			LOGGER.error("Retailer Document file not found : ", e);
1258
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1259
		}
1260
		// ByteArrayOutputStream byteArrayOutputStream = new
1261
		// ByteArrayOutputStream();
1262
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1263
 
1264
		final HttpHeaders headers = new HttpHeaders();
1265
		String contentType = "";
1266
		if (document.getContentType() == ContentType.JPEG) {
1267
			contentType = "image/jpeg";
1268
		} else if (document.getContentType() == ContentType.PNG) {
1269
			contentType = "image/png";
1270
		} else if (document.getContentType() == ContentType.PDF) {
1271
			contentType = "application/pdf";
1272
		}
1273
		headers.set("Content-Type", contentType);
1274
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1275
		headers.setContentLength(document.getSize());
1276
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1277
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1278
	}
26460 amit.gupta 1279
 
1280
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1281
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1282
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1283
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1284
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1285
			List<Integer> authIds = l2l1.getValue();
1286
			authIds.add(l2l1.getKey());
1287
 
1288
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1289
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1290
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1291
			if (!leads.isEmpty()) {
1292
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1293
			} else {
1294
				authIdAndleadsCountMap.put(auth.getId(), 0);
1295
			}
26422 tejbeer 1296
		}
26468 amit.gupta 1297
 
26460 amit.gupta 1298
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1299
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1300
				.collect(Collectors.toList());
26433 tejbeer 1301
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1302
 
26460 amit.gupta 1303
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1304
 
26460 amit.gupta 1305
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1306
		for (int authUserId : pp.keySet()) {
1307
			if (L2L1Mapping.keySet().contains(authUserId)) {
1308
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1309
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1310
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1311
						.collect(Collectors.toList());
26927 amit.gupta 1312
				LOGGER.info("authUserId {}, partnerDetails {}" + authUserId, partnerDetails);
26460 amit.gupta 1313
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1314
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1315
			}
1316
		}
26997 amit.gupta 1317
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1318
				.collect(Collectors.toList());
26468 amit.gupta 1319
		PartnerDetailModel partnerDetailModel = partnerStatsService
1320
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1321
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1322
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1323
		return authIdAndallValues;
1324
	}
1325
 
27545 tejbeer 1326
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail() throws Exception {
1327
 
1328
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
1329
		Map<Integer, List<FofoStore>> warehousePartnerMap = fofoStoreRepository.getWarehousePartnerMap();
1330
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1331
 
1332
		for (Entry<Integer, List<FofoStore>> warehouse : warehousePartnerMap.entrySet()) {
1333
			List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x.getId()).collect(Collectors.toList());
1334
			List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1335
					.collect(Collectors.toList());
1336
			LOGGER.info("partnerDetails" + partnerDetails);
1337
 
1338
			PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1339
 
1340
			warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1341
		}
1342
		LOGGER.info("warehouseIdAndallValues" + warehouseIdAndallValues);
27548 tejbeer 1343
		PartnerDetailModel partnerDetailModel = partnerStatsService
1344
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
1345
		warehouseIdAndallValues.put(0, partnerDetailModel);
27545 tejbeer 1346
 
1347
		return warehouseIdAndallValues;
1348
	}
1349
 
21615 kshitij.so 1350
}