Subversion Repositories SmartDukaan

Rev

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