Subversion Repositories SmartDukaan

Rev

Rev 27538 | Rev 27540 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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