Subversion Repositories SmartDukaan

Rev

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