Subversion Repositories SmartDukaan

Rev

Rev 27633 | Rev 27636 | 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);
27634 tejbeer 1075
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1076
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1077
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1078
				}
27628 tejbeer 1079
 
1080
			}
1081
			LOGGER.info("warehouseIdAndallValues" + warehouseIdAndallValues);
1082
			PartnerDetailModel partnerDetailModel = partnerStatsService
1083
					.getAggregateStats(new ArrayList<>(partnerStats.values()));
1084
			warehouseIdAndallValues.put(0, partnerDetailModel);
1085
		}
1086
		return warehouseIdAndallValues;
1087
	}
1088
 
1089
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1090
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1091
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1092
		ObjectOutputStream oos = null;
1093
		FileOutputStream fout = null;
1094
		try {
1095
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1096
			oos = new ObjectOutputStream(fout);
1097
			oos.writeObject(partnerStats);
1098
 
1099
		} catch (Exception ex) {
1100
			ex.printStackTrace();
1101
		} finally {
1102
			if (oos != null) {
1103
				oos.close();
1104
			}
1105
		}
1106
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1107
		if (rct == null) {
1108
			rct = new ReporticoCacheTable();
1109
			rct.setTableName("partnerStat");
1110
 
1111
		}
1112
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1113
		reporticoCacheTableRepository.persist(rct);
1114
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1115
		return "response";
1116
	}
1117
 
1118
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1119
		ObjectInputStream objectinputstream = null;
1120
		Map<Integer, PartnerDetailModel> partnerStat = null;
1121
		try {
1122
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1123
			objectinputstream = new ObjectInputStream(streamIn);
1124
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1125
 
1126
			LOGGER.info("partnerStat" + partnerStat);
1127
			objectinputstream.close();
1128
 
1129
		} catch (Exception e) {
1130
			LOGGER.info("exceptionddd" + e);
1131
 
1132
			e.printStackTrace();
1133
 
1134
		} finally {
1135
			if (objectinputstream != null) {
1136
				objectinputstream.close();
1137
				LOGGER.info("clofddd" + partnerStat);
1138
 
1139
			}
1140
		}
1141
		return partnerStat;
1142
 
1143
	}
1144
 
27539 tejbeer 1145
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1146
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1147
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1148
			throws Exception {
27509 tejbeer 1149
 
1150
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1151
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1152
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1153
 
27509 tejbeer 1154
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1155
		model.addAttribute("brands", listbrands);
27538 tejbeer 1156
		model.addAttribute("listCategory", listCategory);
1157
 
27529 tejbeer 1158
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1159
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1160
		model.addAttribute("selectedCategory", category);
1161
 
27509 tejbeer 1162
		return "warehouse_brand_item_stock";
1163
	}
1164
 
27538 tejbeer 1165
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1166
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1167
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1168
			throws Exception {
27539 tejbeer 1169
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1170
		if (warehouseId.contains(0)) {
1171
			warehouseId.addAll(warehouseMap.keySet());
1172
		}
27538 tejbeer 1173
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1174
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1175
 
27538 tejbeer 1176
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1177
		model.addAttribute("warehouseMap", warehouseMap);
1178
 
1179
		LOGGER.info("warehouseWiseItemStock" + warehouseWiseItemStock);
1180
		return "warehouse_item_details";
1181
	}
1182
 
26114 amit.gupta 1183
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1184
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1185
		positionRetailers.stream().forEach(x -> {
1186
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1187
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1188
			}
1189
		});
26114 amit.gupta 1190
		return gson.toJson(warehouses);
1191
 
1192
	}
1193
 
27556 tejbeer 1194
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1195
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1196
			throws Exception {
1197
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
1198
				.selectGroupByWarehouseBrandWisePartnerSale(brand);
27556 tejbeer 1199
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1200
 
1201
		Set<String> brands = inventoryService.getAllTagListingBrands();
1202
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1203
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1204
		model.addAttribute("brands", brands);
1205
		model.addAttribute("selectedbrand", brand);
1206
 
1207
		LOGGER.info("warehouseWiseBrandPartnerSales" + warehouseWiseBrandPartnerSales);
1208
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1209
	}
1210
 
27594 tejbeer 1211
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1212
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1213
			@RequestParam String brand) throws Exception {
1214
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
1215
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand);
1216
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1217
 
1218
		Set<String> brands = inventoryService.getAllTagListingBrands();
1219
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1220
		model.addAttribute("warehouseMap", warehouseMap);
1221
		model.addAttribute("brands", brands);
1222
		model.addAttribute("selectedbrand", brand);
1223
 
1224
		LOGGER.info("warehouseWiseBrandPartnerSales" + warehouseWiseBrandPartnerSales);
1225
		return "warehousewise_accessoriesbrand_sale";
1226
	}
1227
 
27556 tejbeer 1228
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1229
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1230
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1231
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1232
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
1233
				.selectWarehouseBrandItemSale(warehouseId, brand);
1234
		model.addAttribute("branditemSales", branditemSales);
1235
		model.addAttribute("warehouseMap", warehouseMap);
1236
		return "warehouse_partner_itemwise_sale";
1237
	}
1238
 
27594 tejbeer 1239
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1240
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1241
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1242
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1243
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
1244
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand);
1245
		model.addAttribute("branditemSales", branditemSales);
1246
		model.addAttribute("warehouseMap", warehouseMap);
1247
		return "warehouse_accessories_itemwsie_sale";
1248
	}
1249
 
26012 amit.gupta 1250
	private List<Menu> prepareMenu(List<Menu> menus) {
1251
		List<Menu> returnMenu = new ArrayList<>();
1252
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1253
		for (Menu menu : menus) {
1254
			if (menu.get_parent() == null) {
26014 amit.gupta 1255
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1256
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1257
				}
1258
			} else {
26012 amit.gupta 1259
				Menu parentMenu = menu.get_parent();
1260
				if (!subMenuMap.containsKey(parentMenu)) {
1261
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1262
				}
26012 amit.gupta 1263
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1264
			}
1265
		}
26012 amit.gupta 1266
		subMenuMap.entrySet().stream().forEach(entry -> {
1267
			entry.getKey().setSubMenus(entry.getValue());
1268
			returnMenu.add(entry.getKey());
1269
		});
1270
		return returnMenu;
26005 amit.gupta 1271
	}
1272
 
24288 amit.gupta 1273
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1274
	private boolean hasGift(int fofoId) {
1275
		try {
24288 amit.gupta 1276
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1277
					.getAvailability() > 0;
24203 amit.gupta 1278
		} catch (ProfitMandiBusinessException e) {
1279
			return false;
1280
		}
1281
	}
24288 amit.gupta 1282
 
22354 ashik.ali 1283
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1284
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1285
		model.addAttribute("appContextPath", request.getContextPath());
1286
		return "contact-us";
1287
	}
23923 amit.gupta 1288
 
25649 tejbeer 1289
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1290
	public String getNotificationsWithType(HttpServletRequest request,
1291
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1292
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1293
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1294
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1295
		int userId = 0;
1296
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1297
		if (isAdmin) {
1298
			userId = loginDetails.getFofoId();
1299
		} else {
1300
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1301
		}
25683 tejbeer 1302
		List<Notification> notifications = null;
1303
 
26086 tejbeer 1304
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1305
				userId, offset, limit);
1306
		LOGGER.info("messageType" + messageType);
1307
		notifications = getNotifications(notificationCampaigns, messageType);
1308
 
25683 tejbeer 1309
		model.addAttribute("notifications", notifications);
1310
 
1311
		LOGGER.info("notifications" + notifications);
1312
		return "notification-template";
1313
	}
1314
 
1315
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1316
			throws ProfitMandiBusinessException {
1317
		List<Notification> notifications = new ArrayList<>();
1318
		Document document = null;
1319
		if (messageType != null) {
1320
			for (NotificationCampaign notificationCampaign : nc) {
1321
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1322
					Notification ns = new Notification();
1323
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1324
							SimpleCampaignParams.class);
1325
					Campaign campaign = new SimpleCampaign(scp);
1326
					LocalDateTime expire = campaign.getExpireTimestamp();
1327
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1328
					ns.setType(campaign.getType());
1329
					ns.setMessage(campaign.getMessage());
1330
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1331
					if (notificationCampaign.getDocumentId() != null) {
1332
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1333
						ns.setDocumentName(document.getDisplayName());
1334
					}
25683 tejbeer 1335
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1336
					ns.setShowImage(campaign.getShowImage());
1337
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1338
					ns.setDocumentId(notificationCampaign.getDocumentId());
1339
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1340
					ns.setCreated(
1341
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1342
									* 1000);
1343
					if (LocalDateTime.now().isAfter(expire)) {
1344
						ns.setExpired(true);
1345
					} else {
1346
						ns.setExpired(false);
1347
					}
1348
					notifications.add(ns);
1349
				}
1350
			}
25683 tejbeer 1351
		} else {
1352
			for (NotificationCampaign notificationCampaign : nc) {
1353
 
1354
				Notification ns = new Notification();
1355
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1356
						SimpleCampaignParams.class);
1357
				Campaign campaign = new SimpleCampaign(scp);
1358
				LocalDateTime expire = campaign.getExpireTimestamp();
1359
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1360
				ns.setType(campaign.getType());
1361
				ns.setMessage(campaign.getMessage());
1362
				ns.setTitle(campaign.getTitle());
1363
				if (notificationCampaign.getDocumentId() != null) {
1364
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1365
					ns.setDocumentName(document.getDisplayName());
1366
				}
1367
				ns.setUrl(campaign.getUrl());
1368
				ns.setShowImage(campaign.getShowImage());
1369
				ns.setImageUrl(campaign.getImageUrl());
1370
				ns.setDocumentId(notificationCampaign.getDocumentId());
1371
				ns.setMessageType(notificationCampaign.getMessageType());
1372
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1373
						* 1000);
1374
				if (LocalDateTime.now().isAfter(expire)) {
1375
					ns.setExpired(true);
1376
				} else {
1377
					ns.setExpired(false);
1378
				}
1379
				notifications.add(ns);
1380
			}
1381
 
25649 tejbeer 1382
		}
25683 tejbeer 1383
		return notifications;
25651 tejbeer 1384
 
1385
	}
25649 tejbeer 1386
 
25651 tejbeer 1387
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1388
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1389
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1390
			throws ProfitMandiBusinessException {
1391
		Document document = documentRepository.selectById(documentId);
1392
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1393
		if (nc.getDocumentId() == null) {
1394
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1395
		}
1396
		if (nc.getDocumentId() != documentId) {
1397
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1398
		}
1399
		return responseSender.ok(document);
25649 tejbeer 1400
	}
1401
 
25651 tejbeer 1402
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1403
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1404
			throws ProfitMandiBusinessException {
1405
 
1406
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1407
 
1408
		if (nc.getDocumentId() == null) {
1409
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1410
		}
1411
 
1412
		Document document = documentRepository.selectById(nc.getDocumentId());
1413
 
1414
		FileInputStream file = null;
1415
		try {
1416
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1417
		} catch (FileNotFoundException e) {
1418
			LOGGER.error("Retailer Document file not found : ", e);
1419
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1420
		}
1421
		// ByteArrayOutputStream byteArrayOutputStream = new
1422
		// ByteArrayOutputStream();
1423
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1424
 
1425
		final HttpHeaders headers = new HttpHeaders();
1426
		String contentType = "";
1427
		if (document.getContentType() == ContentType.JPEG) {
1428
			contentType = "image/jpeg";
1429
		} else if (document.getContentType() == ContentType.PNG) {
1430
			contentType = "image/png";
1431
		} else if (document.getContentType() == ContentType.PDF) {
1432
			contentType = "application/pdf";
1433
		}
1434
		headers.set("Content-Type", contentType);
1435
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1436
		headers.setContentLength(document.getSize());
1437
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1438
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1439
	}
26460 amit.gupta 1440
 
1441
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1442
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1443
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1444
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1445
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1446
			List<Integer> authIds = l2l1.getValue();
1447
			authIds.add(l2l1.getKey());
1448
 
1449
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1450
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1451
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1452
			if (!leads.isEmpty()) {
1453
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1454
			} else {
1455
				authIdAndleadsCountMap.put(auth.getId(), 0);
1456
			}
26422 tejbeer 1457
		}
26468 amit.gupta 1458
 
26460 amit.gupta 1459
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1460
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1461
				.collect(Collectors.toList());
26433 tejbeer 1462
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1463
 
26460 amit.gupta 1464
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1465
 
26460 amit.gupta 1466
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1467
		for (int authUserId : pp.keySet()) {
1468
			if (L2L1Mapping.keySet().contains(authUserId)) {
1469
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1470
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1471
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1472
						.collect(Collectors.toList());
27632 tejbeer 1473
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1474
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1475
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1476
			}
1477
		}
26997 amit.gupta 1478
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1479
				.collect(Collectors.toList());
26468 amit.gupta 1480
		PartnerDetailModel partnerDetailModel = partnerStatsService
1481
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1482
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1483
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1484
		return authIdAndallValues;
1485
	}
1486
 
27579 tejbeer 1487
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1488
	public String getItemWiseTertiary(HttpServletRequest request,
1489
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1490
			throws ProfitMandiBusinessException {
1491
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1492
 
1493
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1494
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1495
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1496
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1497
		return "item-wise-tertiary";
1498
	}
1499
 
27586 tejbeer 1500
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1501
	public String getItemWiseIndent(HttpServletRequest request,
1502
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1503
			throws ProfitMandiBusinessException {
1504
 
1505
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1506
		model.addAttribute("unbilledOrders", unbilledOrders);
1507
 
1508
		return "item-wise-indent";
1509
	}
1510
 
27599 tejbeer 1511
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1512
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1513
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1514
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1515
				.selectPartnerPendingIndentItem(itemId, warehouseId);
1516
 
1517
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1518
		return "partner-pending-indent-item";
1519
	}
1520
 
21615 kshitij.so 1521
}