Subversion Repositories SmartDukaan

Rev

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