Subversion Repositories SmartDukaan

Rev

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