Subversion Repositories SmartDukaan

Rev

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