Subversion Repositories SmartDukaan

Rev

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