Subversion Repositories SmartDukaan

Rev

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