Subversion Repositories SmartDukaan

Rev

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