Subversion Repositories SmartDukaan

Rev

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