Subversion Repositories SmartDukaan

Rev

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