Subversion Repositories SmartDukaan

Rev

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