Subversion Repositories SmartDukaan

Rev

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