Subversion Repositories SmartDukaan

Rev

Rev 26090 | Rev 26114 | 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;
25649 tejbeer 9
import java.time.ZoneOffset;
24339 amit.gupta 10
import java.util.ArrayList;
26027 amit.gupta 11
import java.util.Arrays;
26011 amit.gupta 12
import java.util.HashMap;
26090 amit.gupta 13
import java.util.HashSet;
25136 amit.gupta 14
import java.util.LinkedHashMap;
23884 amit.gupta 15
import java.util.List;
24880 govind 16
import java.util.Map;
26055 tejbeer 17
import java.util.Map.Entry;
26071 tejbeer 18
import java.util.Optional;
26090 amit.gupta 19
import java.util.Set;
24880 govind 20
import java.util.stream.Collectors;
23568 govind 21
 
22086 amit.gupta 22
import javax.servlet.http.HttpServletRequest;
25221 amit.gupta 23
import javax.transaction.Transactional;
22086 amit.gupta 24
 
23786 amit.gupta 25
import org.apache.logging.log4j.LogManager;
23568 govind 26
import org.apache.logging.log4j.Logger;
22481 ashik.ali 27
import org.springframework.beans.factory.annotation.Autowired;
23379 ashik.ali 28
import org.springframework.beans.factory.annotation.Value;
25651 tejbeer 29
import org.springframework.core.io.InputStreamResource;
30
import org.springframework.http.HttpHeaders;
31
import org.springframework.http.HttpStatus;
25649 tejbeer 32
import org.springframework.http.ResponseEntity;
21615 kshitij.so 33
import org.springframework.stereotype.Controller;
22073 ashik.ali 34
import org.springframework.ui.Model;
21615 kshitij.so 35
import org.springframework.web.bind.annotation.RequestMapping;
36
import org.springframework.web.bind.annotation.RequestMethod;
25649 tejbeer 37
import org.springframework.web.bind.annotation.RequestParam;
21615 kshitij.so 38
 
25649 tejbeer 39
import com.google.gson.Gson;
25677 amit.gupta 40
import com.mongodb.DBObject;
25651 tejbeer 41
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 42
import com.spice.profitmandi.common.enumuration.MessageType;
26065 amit.gupta 43
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22481 ashik.ali 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25677 amit.gupta 45
import com.spice.profitmandi.common.model.BrandStockPrice;
26055 tejbeer 46
import com.spice.profitmandi.common.model.ChartModel;
26005 amit.gupta 47
import com.spice.profitmandi.common.model.CustomRetailer;
26055 tejbeer 48
import com.spice.profitmandi.common.model.DataModel;
49
import com.spice.profitmandi.common.model.DatasetModel;
50
import com.spice.profitmandi.common.model.LegendModel;
25649 tejbeer 51
import com.spice.profitmandi.common.model.Notification;
26055 tejbeer 52
import com.spice.profitmandi.common.model.OptionsModel;
24203 amit.gupta 53
import com.spice.profitmandi.common.model.ProfitMandiConstants;
26055 tejbeer 54
import com.spice.profitmandi.common.model.TitleModel;
25651 tejbeer 55
import com.spice.profitmandi.common.web.util.ResponseSender;
25649 tejbeer 56
import com.spice.profitmandi.dao.Interface.Campaign;
26011 amit.gupta 57
import com.spice.profitmandi.dao.entity.auth.AuthUser;
58
import com.spice.profitmandi.dao.entity.auth.Menu;
59
import com.spice.profitmandi.dao.entity.cs.Position;
25651 tejbeer 60
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 61
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
62
import com.spice.profitmandi.dao.entity.dtr.UserCampaign;
22654 ashik.ali 63
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24288 amit.gupta 64
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25214 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
25566 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
26024 amit.gupta 67
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
25649 tejbeer 68
import com.spice.profitmandi.dao.model.SimpleCampaign;
69
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
25976 amit.gupta 70
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26011 amit.gupta 71
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
72
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
26090 amit.gupta 73
import com.spice.profitmandi.dao.repository.cs.CsService;
26011 amit.gupta 74
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
75
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
25651 tejbeer 76
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22481 ashik.ali 77
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24996 amit.gupta 78
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25649 tejbeer 79
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
80
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
81
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
24203 amit.gupta 82
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24880 govind 83
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
26071 tejbeer 84
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
25649 tejbeer 85
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
24288 amit.gupta 86
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
25214 amit.gupta 87
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
25566 tejbeer 88
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
26090 amit.gupta 89
import com.spice.profitmandi.service.AuthService;
24336 amit.gupta 90
import com.spice.profitmandi.service.PartnerInvestmentService;
23844 amit.gupta 91
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 92
import com.spice.profitmandi.service.inventory.InventoryService;
26005 amit.gupta 93
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 94
import com.spice.profitmandi.web.model.LoginDetails;
95
import com.spice.profitmandi.web.util.CookiesProcessor;
96
 
21615 kshitij.so 97
@Controller
25222 amit.gupta 98
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 99
public class DashboardController {
23923 amit.gupta 100
 
23379 ashik.ali 101
	@Value("${web.api.host}")
102
	private String webApiHost;
23923 amit.gupta 103
 
24072 amit.gupta 104
	@Value("${web.api.scheme}")
105
	private String webApiScheme;
24288 amit.gupta 106
 
24078 amit.gupta 107
	@Value("${web.api.root}")
108
	private String webApiRoot;
109
 
23379 ashik.ali 110
	@Value("${web.api.port}")
111
	private int webApiPort;
21615 kshitij.so 112
 
22481 ashik.ali 113
	@Autowired
22927 ashik.ali 114
	private CookiesProcessor cookiesProcessor;
23923 amit.gupta 115
 
23568 govind 116
	@Autowired
26011 amit.gupta 117
	private MenuRepository menuRepository;
26012 amit.gupta 118
 
26011 amit.gupta 119
	@Autowired
120
	private MenuCategoryRepository menuCategoryRepository;
121
 
122
	@Autowired
26090 amit.gupta 123
	private CsService csService;
124
 
125
	@Autowired
25214 amit.gupta 126
	private PartnerTargetRepository partnerTargetRepository;
127
 
128
	@Autowired
25653 amit.gupta 129
	private ResponseSender<?> responseSender;
26012 amit.gupta 130
 
26005 amit.gupta 131
	@Autowired
132
	RetailerService retailerService;
25214 amit.gupta 133
 
134
	@Autowired
23786 amit.gupta 135
	private RoleManager roleManager;
23923 amit.gupta 136
 
23838 ashik.ali 137
	@Autowired
138
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 139
 
140
	@Autowired
24880 govind 141
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
23923 amit.gupta 142
 
23884 amit.gupta 143
	@Autowired
24880 govind 144
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 145
 
23884 amit.gupta 146
	@Autowired
25653 amit.gupta 147
	DocumentRepository documentRepository;
25683 tejbeer 148
 
25677 amit.gupta 149
	@Autowired
150
	InventoryService inventoryService;
23923 amit.gupta 151
 
23884 amit.gupta 152
	@Autowired
24203 amit.gupta 153
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
154
 
24880 govind 155
	@Autowired
156
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 157
 
26011 amit.gupta 158
	@Autowired
159
	private TicketCategoryRepository ticketCategoryRepository;
24880 govind 160
 
161
	@Autowired
25566 tejbeer 162
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 163
 
24996 amit.gupta 164
	@Autowired
25649 tejbeer 165
	private HygieneDataRepository hygieneDataRepository;
166
 
167
	@Autowired
168
	private UserCampaignRepository userCampaignRepository;
26012 amit.gupta 169
 
26011 amit.gupta 170
	@Autowired
171
	private PositionRepository positionRepository;
25649 tejbeer 172
 
173
	@Autowired
174
	private UserAccountRepository userAccountRepository;
175
 
176
	@Autowired
177
	private NotificationCampaignRepository notificationCampaignRepository;
178
 
179
	@Autowired
24996 amit.gupta 180
	private Mongo mongoClient;
26012 amit.gupta 181
 
25976 amit.gupta 182
	@Autowired
183
	private AuthRepository authRepository;
24880 govind 184
 
25649 tejbeer 185
	@Autowired
26071 tejbeer 186
	private FofoOrderRepository fofoOrderRepository;
187
 
188
	@Autowired
25649 tejbeer 189
	private Gson gson;
190
 
23568 govind 191
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 192
 
25136 amit.gupta 193
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 194
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 195
		boolean isAdmin = false;
196
		model.addAttribute("isAdmin", isAdmin);
197
 
198
		model.addAttribute("webApiHost", webApiHost);
199
		model.addAttribute("webApiPort", webApiPort);
200
		model.addAttribute("webApiScheme", webApiScheme);
201
		model.addAttribute("webApiRoot", webApiRoot);
202
		if (isAdmin) {
203
			return "dashboard1";
204
		} else {
205
			FofoStore fofoStore = null;
206
			try {
26005 amit.gupta 207
				CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
25740 amit.gupta 208
				fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
209
				if (!fofoStore.isActive()) {
210
					return "redirect:/login";
211
				}
212
 
213
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
214
				model.addAttribute("partnerType", partnerType);
215
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
26005 amit.gupta 216
				model.addAttribute("fofoStore", customRetailer);
25740 amit.gupta 217
				model.addAttribute("partnerType", partnerType);
218
				model.addAttribute("hasGift", hasGift(fofoId));
219
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
220
 
221
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
222
				model.addAttribute("salesMap", this.getSales(fofoId));
223
				// this.setInvestments
224
				//
225
				model.addAttribute("investments", this.getInvestments(fofoId));
26012 amit.gupta 226
				model.addAttribute("isInvestmentOk",
227
						partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
25740 amit.gupta 228
			} catch (ProfitMandiBusinessException e) {
229
				LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
230
 
231
			}
232
		}
233
 
234
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
235
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
26012 amit.gupta 236
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)
237
				/ 2;
238
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
239
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
25740 amit.gupta 240
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
241
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
242
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
243
 
26012 amit.gupta 244
		long hygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, true, currentMonthStart, currentMonthEnd);
245
 
246
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,
25740 amit.gupta 247
				currentMonthEnd);
248
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
249
			invalidHygieneCount = 1;
250
		}
251
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
252
 
253
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
254
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
255
		return "12dashboard34";
25136 amit.gupta 256
	}
257
 
258
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
259
		Map<String, Object> investments = new LinkedHashMap<>();
260
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 1);
25649 tejbeer 261
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
25136 amit.gupta 262
		LocalDate yesterDate = LocalDate.now().minusDays(1);
263
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
264
		if (yesterdayInvestment == null) {
265
			yesterdayInvestment = new PartnerDailyInvestment();
266
		}
267
 
268
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
269
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
270
 
25140 amit.gupta 271
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
25136 amit.gupta 272
				.collect(Collectors.counting());
25140 amit.gupta 273
		investments.put("today", investment.getTotalInvestment());
274
		investments.put("investment", investment);
275
		investments.put("inStock", investment.getInStockAmount());
25182 amit.gupta 276
		investments.put("minimum", investment.getMinInvestmentString());
25140 amit.gupta 277
		investments.put("short", investment.getShortPercentage());
25649 tejbeer 278
		investments.put("okDays", okInvestmentDays);
25136 amit.gupta 279
		return investments;
280
	}
281
 
25221 amit.gupta 282
	private Map<String, Object> getSales(int fofoId) {
25653 amit.gupta 283
 
25221 amit.gupta 284
		Map<String, Object> salesMap = new LinkedHashMap<>();
25140 amit.gupta 285
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
25214 amit.gupta 286
		int monthLength = LocalDate.now().lengthOfMonth();
26012 amit.gupta 287
		Double todaySale = fofoOrderItemRepository
288
				.selectSumAmountGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
289
		Double mtdSale = fofoOrderItemRepository
290
				.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false)
291
				.get(fofoId);
292
		Double lmtdSale = fofoOrderItemRepository
293
				.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
294
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false)
295
				.get(fofoId);
25214 amit.gupta 296
 
297
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
298
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 299
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 300
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 301
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 302
		}
25214 amit.gupta 303
 
25653 amit.gupta 304
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 305
 
25664 amit.gupta 306
		int currentRate = (int) (mtdSale / curDate.getDayOfMonth());
25653 amit.gupta 307
 
308
		salesMap.put("requiredType", partnerType.next());
309
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
310
		int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
311
		salesMap.put("requiredRate", requiredRate);
312
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
313
 
25858 amit.gupta 314
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
315
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 316
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 317
 
25653 amit.gupta 318
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
319
		salesMap.put("currentRate", currentRate);
320
		salesMap.put("currentType", currentType);
321
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 322
		return salesMap;
323
	}
324
 
25677 amit.gupta 325
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
326
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 327
 
25677 amit.gupta 328
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
329
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
330
 
331
		mobileBrands.stream().forEach(x -> {
332
			String brand = (String) x.get("name");
333
			if (brandStockPricesMap.containsKey(brand)) {
334
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
335
				brandStockPrice.setBrandUrl((String) x.get("url"));
336
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
337
				brandStockPrices.add(brandStockPrice);
338
			}
339
		});
340
 
341
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
342
				.collect(Collectors.toList());
343
	}
344
 
21615 kshitij.so 345
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 346
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 347
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 348
		String email = loginDetails.getEmailId();
25180 amit.gupta 349
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
350
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 351
 
25274 amit.gupta 352
		model.addAttribute("webApiHost", webApiHost);
353
		model.addAttribute("webApiPort", webApiPort);
354
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 355
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 356
		if (isAdmin) {
26011 amit.gupta 357
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 358
		} else {
25740 amit.gupta 359
			FofoStore fofoStore = null;
25180 amit.gupta 360
			try {
361
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 362
				if (!fofoStore.isActive()) {
363
					return "redirect:/login";
364
				}
25649 tejbeer 365
 
25740 amit.gupta 366
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 367
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 368
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 369
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 370
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 371
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
372
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26071 tejbeer 373
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
374
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
375
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
376
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
377
				LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
378
				Double accesoriesStock = currentInventorySnapshotRepository
379
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
380
								Optional.of(false))
381
						.get(loginDetails.getFofoId());
25180 amit.gupta 382
 
26071 tejbeer 383
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
26065 amit.gupta 384
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 385
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 386
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
387
 
388
				LOGGER.info("chartMap" + gson.toJson(cm));
389
				model.addAttribute("chartMap", gson.toJson(cm));
25544 amit.gupta 390
				// this.setInvestments
391
				//
25180 amit.gupta 392
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 393
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
394
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
25180 amit.gupta 395
			} catch (ProfitMandiBusinessException e) {
396
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
397
 
398
			}
22481 ashik.ali 399
		}
25649 tejbeer 400
 
401
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 402
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 403
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
404
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 405
				currentMonthEnd) / 2;
25747 amit.gupta 406
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
407
				currentMonthStart) / 2;
408
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 409
				currentMonthEnd) / 2;
410
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
411
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
412
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 413
 
25653 amit.gupta 414
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
415
				currentMonthEnd);
25651 tejbeer 416
 
25653 amit.gupta 417
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
418
				currentMonthStart, currentMonthEnd);
419
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
420
			invalidHygieneCount = 1;
421
		}
422
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 423
 
25197 amit.gupta 424
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
425
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
25140 amit.gupta 426
		return "dashboard1";
21615 kshitij.so 427
	}
23923 amit.gupta 428
 
26055 tejbeer 429
	private ChartModel getBrandChart(int fofoId) {
430
 
431
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
432
 
433
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
434
 
435
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
436
 
437
		Map<String, Double> brandwisesale = fofoOrderItemRepository
438
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
439
		LOGGER.info("brandwisesale" + brandwisesale);
440
 
441
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
442
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
443
 
444
		ChartModel cm = new ChartModel();
445
 
446
		List<String> labels = new ArrayList<>();
447
		labels.addAll(brandwisesale.keySet());
448
		List<Double> values = new ArrayList<>();
449
		values.addAll(brandwisesale.values());
450
 
451
		List<Double> lmtdValues = new ArrayList<>();
452
		lmtdValues.addAll(lmtdBrandWiseSale.values());
453
 
454
		DatasetModel dsm = new DatasetModel();
455
		dsm.setLabel("mtd sales");
456
 
457
		List<String> backgroundColor = new ArrayList<>();
458
		for (Entry<String, Double> bs : brandwisesale.entrySet()) {
459
			backgroundColor.add("#3e95cd");
460
		}
461
 
462
		dsm.setBackgroundColor(backgroundColor);
463
		dsm.setData(values);
464
 
465
		DatasetModel lmtddsm = new DatasetModel();
466
		lmtddsm.setLabel("lmtd sales");
467
 
468
		List<String> background = new ArrayList<>();
469
		for (Entry<String, Double> bs : lmtdBrandWiseSale.entrySet()) {
470
			background.add("#8e5ea2");
471
		}
472
 
473
		lmtddsm.setBackgroundColor(background);
474
		lmtddsm.setData(lmtdValues);
475
 
476
		List<DatasetModel> datasets = new ArrayList<>();
477
		datasets.add(dsm);
478
		datasets.add(lmtddsm);
479
 
480
		DataModel dm = new DataModel();
481
		dm.setDatasets(datasets);
482
		dm.setLabels(labels);
483
 
484
		LegendModel lm = new LegendModel();
485
		lm.setDisplay(true);
486
 
487
		TitleModel tm = new TitleModel();
488
		tm.setText("Brand Wise Sale Graph");
489
		tm.setDisplay(true);
490
 
491
		OptionsModel om = new OptionsModel();
492
		om.setLegend(lm);
493
		om.setTitle(tm);
494
 
495
		cm.setType("bar");
496
		cm.setData(dm);
497
		cm.setOptions(om);
498
 
499
		return cm;
500
 
501
	}
502
 
26011 amit.gupta 503
	private String adminPanel(int fofoId, String email, Model model) throws ProfitMandiBusinessException {
26022 amit.gupta 504
		List<Menu> menus = null;
26011 amit.gupta 505
		try {
506
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
507
			List<Position> positions = positionRepository.selectAll(authUser.getId());
26090 amit.gupta 508
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in").contains(email)) {
26029 amit.gupta 509
				menus = menuRepository.selectAll();
510
			} else if (positions.size() > 0) {
511
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L4)).count() > 0) {
26028 amit.gupta 512
					menus = menuRepository.selectAll();
513
				} else {
514
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
515
							.map(x -> x.getMenuId()).collect(Collectors.toList());
516
					LOGGER.info("Menu Ids are {}", menuIds);
517
					if (menuIds.size() > 0) {
518
						menus = menuRepository.selectAllByIds(menuIds);
519
					}
26022 amit.gupta 520
				}
26090 amit.gupta 521
				List<Position> salesPositions = positions.stream()
522
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
523
						.collect(Collectors.toList());
524
				if (salesPositions.size() > 0) {
525
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 526
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 527
						positionRetailers.addAll(customRetailers);
528
					});
529
					model.addAttribute("retailers", gson.toJson(positionRetailers));
530
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
531
				}
26028 amit.gupta 532
 
26022 amit.gupta 533
			}
26012 amit.gupta 534
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 535
		}
26028 amit.gupta 536
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26012 amit.gupta 537
 
26022 amit.gupta 538
		model.addAttribute("menu", menuList);
26012 amit.gupta 539
		return "admin";
540
	}
541
 
542
	private List<Menu> prepareMenu(List<Menu> menus) {
543
		List<Menu> returnMenu = new ArrayList<>();
544
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
545
		for (Menu menu : menus) {
546
			if (menu.get_parent() == null) {
26014 amit.gupta 547
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 548
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 549
				}
550
			} else {
26012 amit.gupta 551
				Menu parentMenu = menu.get_parent();
552
				if (!subMenuMap.containsKey(parentMenu)) {
553
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 554
				}
26012 amit.gupta 555
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 556
			}
557
		}
26012 amit.gupta 558
		subMenuMap.entrySet().stream().forEach(entry -> {
559
			entry.getKey().setSubMenus(entry.getValue());
560
			returnMenu.add(entry.getKey());
561
		});
562
		return returnMenu;
26005 amit.gupta 563
	}
564
 
24288 amit.gupta 565
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 566
	private boolean hasGift(int fofoId) {
567
		try {
24288 amit.gupta 568
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
569
					.getAvailability() > 0;
24203 amit.gupta 570
		} catch (ProfitMandiBusinessException e) {
571
			return false;
572
		}
573
	}
24288 amit.gupta 574
 
22354 ashik.ali 575
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 576
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 577
		model.addAttribute("appContextPath", request.getContextPath());
578
		return "contact-us";
579
	}
23923 amit.gupta 580
 
25649 tejbeer 581
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 582
	public String getNotificationsWithType(HttpServletRequest request,
583
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 584
			@RequestParam(name = "offset", defaultValue = "0") int offset,
585
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
586
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 587
		int userId = 0;
588
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
589
		if (isAdmin) {
590
			userId = loginDetails.getFofoId();
591
		} else {
592
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
593
		}
25683 tejbeer 594
		List<Notification> notifications = null;
595
 
26086 tejbeer 596
		if (messageType == null) {
597
			messageType = MessageType.notification;
25683 tejbeer 598
		}
599
 
26086 tejbeer 600
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
601
				userId, offset, limit);
602
		LOGGER.info("messageType" + messageType);
603
		notifications = getNotifications(notificationCampaigns, messageType);
604
 
25683 tejbeer 605
		model.addAttribute("notifications", notifications);
606
 
607
		LOGGER.info("notifications" + notifications);
608
		return "notification-template";
609
	}
610
 
611
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
612
			throws ProfitMandiBusinessException {
613
		List<Notification> notifications = new ArrayList<>();
614
		Document document = null;
615
		if (messageType != null) {
616
			for (NotificationCampaign notificationCampaign : nc) {
617
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 618
					Notification ns = new Notification();
619
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
620
							SimpleCampaignParams.class);
621
					Campaign campaign = new SimpleCampaign(scp);
622
					LocalDateTime expire = campaign.getExpireTimestamp();
623
					ns.setCid(Integer.toString(notificationCampaign.getId()));
624
					ns.setType(campaign.getType());
625
					ns.setMessage(campaign.getMessage());
626
					ns.setTitle(campaign.getTitle());
25651 tejbeer 627
					if (notificationCampaign.getDocumentId() != null) {
628
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
629
						ns.setDocumentName(document.getDisplayName());
630
					}
25683 tejbeer 631
					ns.setUrl(campaign.getUrl());
25649 tejbeer 632
					ns.setShowImage(campaign.getShowImage());
633
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 634
					ns.setDocumentId(notificationCampaign.getDocumentId());
635
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 636
					ns.setCreated(
637
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
638
									* 1000);
639
					if (LocalDateTime.now().isAfter(expire)) {
640
						ns.setExpired(true);
641
					} else {
642
						ns.setExpired(false);
643
					}
644
					notifications.add(ns);
645
				}
646
			}
25683 tejbeer 647
		} else {
648
			for (NotificationCampaign notificationCampaign : nc) {
649
 
650
				Notification ns = new Notification();
651
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
652
						SimpleCampaignParams.class);
653
				Campaign campaign = new SimpleCampaign(scp);
654
				LocalDateTime expire = campaign.getExpireTimestamp();
655
				ns.setCid(Integer.toString(notificationCampaign.getId()));
656
				ns.setType(campaign.getType());
657
				ns.setMessage(campaign.getMessage());
658
				ns.setTitle(campaign.getTitle());
659
				if (notificationCampaign.getDocumentId() != null) {
660
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
661
					ns.setDocumentName(document.getDisplayName());
662
				}
663
				ns.setUrl(campaign.getUrl());
664
				ns.setShowImage(campaign.getShowImage());
665
				ns.setImageUrl(campaign.getImageUrl());
666
				ns.setDocumentId(notificationCampaign.getDocumentId());
667
				ns.setMessageType(notificationCampaign.getMessageType());
668
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
669
						* 1000);
670
				if (LocalDateTime.now().isAfter(expire)) {
671
					ns.setExpired(true);
672
				} else {
673
					ns.setExpired(false);
674
				}
675
				notifications.add(ns);
676
			}
677
 
25649 tejbeer 678
		}
25683 tejbeer 679
		return notifications;
25651 tejbeer 680
 
681
	}
25649 tejbeer 682
 
25651 tejbeer 683
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
684
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
685
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
686
			throws ProfitMandiBusinessException {
687
		Document document = documentRepository.selectById(documentId);
688
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
689
		if (nc.getDocumentId() == null) {
690
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
691
		}
692
		if (nc.getDocumentId() != documentId) {
693
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
694
		}
695
		return responseSender.ok(document);
25649 tejbeer 696
	}
697
 
25651 tejbeer 698
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
699
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
700
			throws ProfitMandiBusinessException {
701
 
702
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
703
 
704
		if (nc.getDocumentId() == null) {
705
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
706
		}
707
 
708
		Document document = documentRepository.selectById(nc.getDocumentId());
709
 
710
		FileInputStream file = null;
711
		try {
712
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
713
		} catch (FileNotFoundException e) {
714
			LOGGER.error("Retailer Document file not found : ", e);
715
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
716
		}
717
		// ByteArrayOutputStream byteArrayOutputStream = new
718
		// ByteArrayOutputStream();
719
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
720
 
721
		final HttpHeaders headers = new HttpHeaders();
722
		String contentType = "";
723
		if (document.getContentType() == ContentType.JPEG) {
724
			contentType = "image/jpeg";
725
		} else if (document.getContentType() == ContentType.PNG) {
726
			contentType = "image/png";
727
		} else if (document.getContentType() == ContentType.PDF) {
728
			contentType = "application/pdf";
729
		}
730
		headers.set("Content-Type", contentType);
731
		headers.set("Content-disposition", "inline; filename=" + document.getName());
732
		headers.setContentLength(document.getSize());
733
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
734
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
735
	}
736
 
21615 kshitij.so 737
}