Subversion Repositories SmartDukaan

Rev

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