Subversion Repositories SmartDukaan

Rev

Rev 27882 | Rev 27893 | 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;
27628 tejbeer 6
import java.io.FileOutputStream;
7
import java.io.ObjectInputStream;
8
import java.io.ObjectOutputStream;
24288 amit.gupta 9
import java.time.LocalDate;
24276 amit.gupta 10
import java.time.LocalDateTime;
24880 govind 11
import java.time.LocalTime;
27555 tejbeer 12
import java.time.YearMonth;
25649 tejbeer 13
import java.time.ZoneOffset;
27474 tejbeer 14
import java.time.format.DateTimeFormatter;
24339 amit.gupta 15
import java.util.ArrayList;
26027 amit.gupta 16
import java.util.Arrays;
27701 tejbeer 17
import java.util.Comparator;
26011 amit.gupta 18
import java.util.HashMap;
26090 amit.gupta 19
import java.util.HashSet;
25136 amit.gupta 20
import java.util.LinkedHashMap;
23884 amit.gupta 21
import java.util.List;
24880 govind 22
import java.util.Map;
26055 tejbeer 23
import java.util.Map.Entry;
26071 tejbeer 24
import java.util.Optional;
26090 amit.gupta 25
import java.util.Set;
24880 govind 26
import java.util.stream.Collectors;
23568 govind 27
 
22086 amit.gupta 28
import javax.servlet.http.HttpServletRequest;
25221 amit.gupta 29
import javax.transaction.Transactional;
22086 amit.gupta 30
 
23786 amit.gupta 31
import org.apache.logging.log4j.LogManager;
23568 govind 32
import org.apache.logging.log4j.Logger;
26158 amit.gupta 33
import org.json.JSONObject;
22481 ashik.ali 34
import org.springframework.beans.factory.annotation.Autowired;
23379 ashik.ali 35
import org.springframework.beans.factory.annotation.Value;
25651 tejbeer 36
import org.springframework.core.io.InputStreamResource;
37
import org.springframework.http.HttpHeaders;
38
import org.springframework.http.HttpStatus;
25649 tejbeer 39
import org.springframework.http.ResponseEntity;
21615 kshitij.so 40
import org.springframework.stereotype.Controller;
22073 ashik.ali 41
import org.springframework.ui.Model;
21615 kshitij.so 42
import org.springframework.web.bind.annotation.RequestMapping;
43
import org.springframework.web.bind.annotation.RequestMethod;
25649 tejbeer 44
import org.springframework.web.bind.annotation.RequestParam;
21615 kshitij.so 45
 
25649 tejbeer 46
import com.google.gson.Gson;
25677 amit.gupta 47
import com.mongodb.DBObject;
25651 tejbeer 48
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 49
import com.spice.profitmandi.common.enumuration.MessageType;
26065 amit.gupta 50
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22481 ashik.ali 51
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27636 tejbeer 52
import com.spice.profitmandi.common.model.ActivateItemModel;
27884 tejbeer 53
import com.spice.profitmandi.common.model.Axis;
25677 amit.gupta 54
import com.spice.profitmandi.common.model.BrandStockPrice;
27884 tejbeer 55
import com.spice.profitmandi.common.model.ChartInvestmentModel;
26055 tejbeer 56
import com.spice.profitmandi.common.model.ChartModel;
26005 amit.gupta 57
import com.spice.profitmandi.common.model.CustomRetailer;
27884 tejbeer 58
import com.spice.profitmandi.common.model.Data;
59
import com.spice.profitmandi.common.model.DataInvestmentModel;
26055 tejbeer 60
import com.spice.profitmandi.common.model.DataModel;
61
import com.spice.profitmandi.common.model.DatasetModel;
27884 tejbeer 62
import com.spice.profitmandi.common.model.Legend;
26055 tejbeer 63
import com.spice.profitmandi.common.model.LegendModel;
25649 tejbeer 64
import com.spice.profitmandi.common.model.Notification;
27884 tejbeer 65
import com.spice.profitmandi.common.model.OptionModel;
26055 tejbeer 66
import com.spice.profitmandi.common.model.OptionsModel;
27884 tejbeer 67
import com.spice.profitmandi.common.model.PieLables;
24203 amit.gupta 68
import com.spice.profitmandi.common.model.ProfitMandiConstants;
27884 tejbeer 69
import com.spice.profitmandi.common.model.ScalesModel;
26055 tejbeer 70
import com.spice.profitmandi.common.model.TitleModel;
25651 tejbeer 71
import com.spice.profitmandi.common.web.util.ResponseSender;
25649 tejbeer 72
import com.spice.profitmandi.dao.Interface.Campaign;
26011 amit.gupta 73
import com.spice.profitmandi.dao.entity.auth.AuthUser;
74
import com.spice.profitmandi.dao.entity.auth.Menu;
27355 tejbeer 75
import com.spice.profitmandi.dao.entity.catalog.Item;
27636 tejbeer 76
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26011 amit.gupta 77
import com.spice.profitmandi.dao.entity.cs.Position;
27660 tejbeer 78
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
25651 tejbeer 79
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 80
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
22654 ashik.ali 81
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
27636 tejbeer 82
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24288 amit.gupta 83
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25214 amit.gupta 84
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
25566 tejbeer 85
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
27529 tejbeer 86
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
27586 tejbeer 87
import com.spice.profitmandi.dao.entity.transaction.Order;
26418 tejbeer 88
import com.spice.profitmandi.dao.entity.user.Lead;
26024 amit.gupta 89
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26418 tejbeer 90
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
27628 tejbeer 91
import com.spice.profitmandi.dao.model.BrandWisePartnerSaleModel;
27670 tejbeer 92
import com.spice.profitmandi.dao.model.BrandWiseUnbilledActivateStockModel;
26674 tejbeer 93
import com.spice.profitmandi.dao.model.CreateOfferRequest;
27660 tejbeer 94
import com.spice.profitmandi.dao.model.InStockBrandItemModel;
27640 tejbeer 95
import com.spice.profitmandi.dao.model.InStockBrandModel;
27579 tejbeer 96
import com.spice.profitmandi.dao.model.ItemWiseTertiaryModel;
27474 tejbeer 97
import com.spice.profitmandi.dao.model.MonthSaleModel;
26418 tejbeer 98
import com.spice.profitmandi.dao.model.PartnerDetailModel;
27599 tejbeer 99
import com.spice.profitmandi.dao.model.PartnerPendingIndentItemModel;
25649 tejbeer 100
import com.spice.profitmandi.dao.model.SimpleCampaign;
101
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
27670 tejbeer 102
import com.spice.profitmandi.dao.model.WarehouseBrandItemUnbilledActivatedModel;
27556 tejbeer 103
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemSaleModel;
27628 tejbeer 104
import com.spice.profitmandi.dao.model.WarehouseWiseBrandSaleModel;
27591 tejbeer 105
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
27670 tejbeer 106
import com.spice.profitmandi.dao.model.WarehouseWiseBrandUnbilledActivatedModel;
27509 tejbeer 107
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
108
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
25976 amit.gupta 109
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26011 amit.gupta 110
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
111
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
27355 tejbeer 112
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
26588 tejbeer 113
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
114
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
115
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
27632 tejbeer 116
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26090 amit.gupta 117
import com.spice.profitmandi.dao.repository.cs.CsService;
26418 tejbeer 118
import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;
26011 amit.gupta 119
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
27660 tejbeer 120
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
26011 amit.gupta 121
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
26418 tejbeer 122
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
25651 tejbeer 123
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22481 ashik.ali 124
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26418 tejbeer 125
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
24996 amit.gupta 126
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25649 tejbeer 127
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
128
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
129
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
24203 amit.gupta 130
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24880 govind 131
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
26071 tejbeer 132
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
25649 tejbeer 133
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
26234 amit.gupta 134
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24288 amit.gupta 135
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
25214 amit.gupta 136
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
27474 tejbeer 137
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
25566 tejbeer 138
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
27529 tejbeer 139
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
140
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
27509 tejbeer 141
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
24336 amit.gupta 142
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 143
import com.spice.profitmandi.service.PartnerStatsService;
23844 amit.gupta 144
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 145
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 146
import com.spice.profitmandi.service.offers.OfferService;
27586 tejbeer 147
import com.spice.profitmandi.service.transaction.TransactionService;
26005 amit.gupta 148
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 149
import com.spice.profitmandi.web.model.LoginDetails;
150
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 151
import com.spice.profitmandi.web.util.MVCResponseSender;
22481 ashik.ali 152
 
21615 kshitij.so 153
@Controller
25222 amit.gupta 154
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 155
public class DashboardController {
23923 amit.gupta 156
 
26460 amit.gupta 157
	private static final double ONE_LAC = 1 * 1000 * 100;
158
	private static final double TWO_LAC = 2 * 1000 * 100;
159
	private static final double FOUR_LAC = 4 * 1000 * 100;
160
 
27727 tejbeer 161
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
27778 tejbeer 162
			"niranjan.kala@smartdukaan.com", "hemant.kaura@smartdukaan.com", "amit.gupta@shop2020.in",
163
			"tejbeer.kaur@shop2020.in");
27727 tejbeer 164
 
23379 ashik.ali 165
	@Value("${web.api.host}")
166
	private String webApiHost;
23923 amit.gupta 167
 
24072 amit.gupta 168
	@Value("${web.api.scheme}")
169
	private String webApiScheme;
24288 amit.gupta 170
 
24078 amit.gupta 171
	@Value("${web.api.root}")
172
	private String webApiRoot;
173
 
23379 ashik.ali 174
	@Value("${web.api.port}")
175
	private int webApiPort;
21615 kshitij.so 176
 
22481 ashik.ali 177
	@Autowired
22927 ashik.ali 178
	private CookiesProcessor cookiesProcessor;
26468 amit.gupta 179
 
26460 amit.gupta 180
	@Autowired
181
	private PartnerStatsService partnerStatsService;
23923 amit.gupta 182
 
23568 govind 183
	@Autowired
26011 amit.gupta 184
	private MenuRepository menuRepository;
26012 amit.gupta 185
 
26011 amit.gupta 186
	@Autowired
187
	private MenuCategoryRepository menuCategoryRepository;
188
 
189
	@Autowired
26090 amit.gupta 190
	private CsService csService;
191
 
192
	@Autowired
25214 amit.gupta 193
	private PartnerTargetRepository partnerTargetRepository;
194
 
195
	@Autowired
25653 amit.gupta 196
	private ResponseSender<?> responseSender;
26012 amit.gupta 197
 
26005 amit.gupta 198
	@Autowired
199
	RetailerService retailerService;
25214 amit.gupta 200
 
201
	@Autowired
23786 amit.gupta 202
	private RoleManager roleManager;
23923 amit.gupta 203
 
23838 ashik.ali 204
	@Autowired
205
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 206
 
207
	@Autowired
24880 govind 208
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
23923 amit.gupta 209
 
23884 amit.gupta 210
	@Autowired
24880 govind 211
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 212
 
23884 amit.gupta 213
	@Autowired
25653 amit.gupta 214
	DocumentRepository documentRepository;
26236 amit.gupta 215
 
26234 amit.gupta 216
	@Autowired
217
	InventoryItemRepository inventoryItemRepository;
25683 tejbeer 218
 
25677 amit.gupta 219
	@Autowired
220
	InventoryService inventoryService;
23923 amit.gupta 221
 
23884 amit.gupta 222
	@Autowired
24203 amit.gupta 223
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
224
 
24880 govind 225
	@Autowired
226
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 227
 
26011 amit.gupta 228
	@Autowired
229
	private TicketCategoryRepository ticketCategoryRepository;
24880 govind 230
 
231
	@Autowired
25566 tejbeer 232
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 233
 
24996 amit.gupta 234
	@Autowired
25649 tejbeer 235
	private HygieneDataRepository hygieneDataRepository;
236
 
237
	@Autowired
238
	private UserCampaignRepository userCampaignRepository;
26012 amit.gupta 239
 
26011 amit.gupta 240
	@Autowired
241
	private PositionRepository positionRepository;
27474 tejbeer 242
	@Autowired
243
	private PartnerTypeChangeRepository partnerTypeChangeRepository;
25649 tejbeer 244
 
245
	@Autowired
26418 tejbeer 246
	private PartnersPositionRepository partnerPositionRepository;
247
 
248
	@Autowired
25649 tejbeer 249
	private UserAccountRepository userAccountRepository;
250
 
251
	@Autowired
252
	private NotificationCampaignRepository notificationCampaignRepository;
253
 
254
	@Autowired
24996 amit.gupta 255
	private Mongo mongoClient;
26012 amit.gupta 256
 
25976 amit.gupta 257
	@Autowired
258
	private AuthRepository authRepository;
24880 govind 259
 
25649 tejbeer 260
	@Autowired
26071 tejbeer 261
	private FofoOrderRepository fofoOrderRepository;
262
 
263
	@Autowired
25649 tejbeer 264
	private Gson gson;
265
 
26418 tejbeer 266
	@Autowired
267
	TicketRepository ticketRepository;
268
 
269
	@Autowired
270
	private LeadRepository leadRepository;
271
 
26588 tejbeer 272
	@Autowired
273
	private OfferRepository offerRepository;
274
 
275
	@Autowired
276
	private OfferPartnerRepository offerPartnerRepository;
277
 
278
	@Autowired
27876 amit.gupta 279
	private OfferService offerService;
280
 
281
	@Autowired
26588 tejbeer 282
	private OfferMarginRepository offerMarginRepository;
27529 tejbeer 283
 
27355 tejbeer 284
	@Autowired
285
	private ItemRepository itemRepository;
26588 tejbeer 286
 
27509 tejbeer 287
	@Autowired
288
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
27529 tejbeer 289
 
290
	@Autowired
291
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
292
 
293
	@Autowired
294
	private MVCResponseSender mvcResponseSender;
295
 
296
	@Autowired
297
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
298
 
27586 tejbeer 299
	@Autowired
300
	private TransactionService transactionService;
301
 
27632 tejbeer 302
	@Autowired
303
	private TagListingRepository tagListingRepository;
304
 
27660 tejbeer 305
	@Autowired
306
	private TicketAssignedRepository ticketAssignedRepository;
307
 
23568 govind 308
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 309
 
25136 amit.gupta 310
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 311
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 312
		boolean isAdmin = false;
313
		model.addAttribute("isAdmin", isAdmin);
314
 
315
		model.addAttribute("webApiHost", webApiHost);
316
		model.addAttribute("webApiPort", webApiPort);
317
		model.addAttribute("webApiScheme", webApiScheme);
318
		model.addAttribute("webApiRoot", webApiRoot);
319
		if (isAdmin) {
320
			return "dashboard1";
26236 amit.gupta 321
		}
322
 
323
		FofoStore fofoStore = null;
26234 amit.gupta 324
		try {
325
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
326
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
327
			if (!fofoStore.isActive()) {
328
				return "redirect:/login";
329
			}
25740 amit.gupta 330
 
26234 amit.gupta 331
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
332
			model.addAttribute("partnerType", partnerType);
333
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
334
			model.addAttribute("fofoStore", customRetailer);
335
			model.addAttribute("partnerType", partnerType);
336
			model.addAttribute("hasGift", hasGift(fofoId));
337
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 338
 
27884 tejbeer 339
			model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26234 amit.gupta 340
			model.addAttribute("salesMap", this.getSales(fofoId));
341
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
342
			// this.setInvestments
343
			//
344
			model.addAttribute("investments", this.getInvestments(fofoId));
345
			model.addAttribute("isInvestmentOk",
346
					partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
347
		} catch (ProfitMandiBusinessException e) {
348
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 349
 
350
		}
351
 
352
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
353
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
26012 amit.gupta 354
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)
355
				/ 2;
356
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
357
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
25740 amit.gupta 358
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
359
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
360
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
361
 
26012 amit.gupta 362
		long hygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, true, currentMonthStart, currentMonthEnd);
363
 
364
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,
25740 amit.gupta 365
				currentMonthEnd);
366
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
367
			invalidHygieneCount = 1;
368
		}
369
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
26460 amit.gupta 370
 
25740 amit.gupta 371
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
372
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
373
		return "12dashboard34";
25136 amit.gupta 374
	}
375
 
376
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
377
		Map<String, Object> investments = new LinkedHashMap<>();
26233 amit.gupta 378
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
25649 tejbeer 379
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
25136 amit.gupta 380
		LocalDate yesterDate = LocalDate.now().minusDays(1);
381
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
382
		if (yesterdayInvestment == null) {
383
			yesterdayInvestment = new PartnerDailyInvestment();
384
		}
385
 
386
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
387
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
388
 
25140 amit.gupta 389
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
25136 amit.gupta 390
				.collect(Collectors.counting());
25140 amit.gupta 391
		investments.put("today", investment.getTotalInvestment());
392
		investments.put("investment", investment);
393
		investments.put("inStock", investment.getInStockAmount());
25182 amit.gupta 394
		investments.put("minimum", investment.getMinInvestmentString());
25140 amit.gupta 395
		investments.put("short", investment.getShortPercentage());
26267 amit.gupta 396
		investments.put("activated_stock", investment.getActivatedStockAmount());
25649 tejbeer 397
		investments.put("okDays", okInvestmentDays);
25136 amit.gupta 398
		return investments;
399
	}
400
 
25221 amit.gupta 401
	private Map<String, Object> getSales(int fofoId) {
25653 amit.gupta 402
 
25221 amit.gupta 403
		Map<String, Object> salesMap = new LinkedHashMap<>();
25140 amit.gupta 404
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
25214 amit.gupta 405
		int monthLength = LocalDate.now().lengthOfMonth();
26012 amit.gupta 406
		Double todaySale = fofoOrderItemRepository
27084 amit.gupta 407
				.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
26012 amit.gupta 408
		Double mtdSale = fofoOrderItemRepository
27084 amit.gupta 409
				.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false)
26012 amit.gupta 410
				.get(fofoId);
27352 tejbeer 411
		Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
412
				curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);
25214 amit.gupta 413
 
414
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
415
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 416
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 417
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 418
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 419
		}
25214 amit.gupta 420
 
25653 amit.gupta 421
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 422
 
25664 amit.gupta 423
		int currentRate = (int) (mtdSale / curDate.getDayOfMonth());
25653 amit.gupta 424
 
425
		salesMap.put("requiredType", partnerType.next());
426
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
427
		int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
27859 tejbeer 428
		if (partnerType.equals(PartnerType.PLATINUM) && requiredRate < currentRate) {
429
			requiredRate = currentRate;
430
		}
25653 amit.gupta 431
		salesMap.put("requiredRate", requiredRate);
432
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
433
 
25858 amit.gupta 434
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
435
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 436
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 437
 
27352 tejbeer 438
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
25653 amit.gupta 439
		salesMap.put("currentRate", currentRate);
440
		salesMap.put("currentType", currentType);
441
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 442
		return salesMap;
443
	}
444
 
27474 tejbeer 445
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
446
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
447
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
448
		int fofoId = loginDetails.getFofoId();
449
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
450
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
451
		int dayOfMonth = curDate.getDayOfMonth();
452
		for (int i = 1; i <= 6; i++) {
453
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
27555 tejbeer 454
			int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
27474 tejbeer 455
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
456
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
457
 
27574 tejbeer 458
			double mtdSales = fofoOrderItemRepository
459
					.selectSumMopGroupByRetailer(startOfMonth,
460
							startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
461
					.get(fofoId);
27474 tejbeer 462
 
463
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
464
 
465
			MonthSaleModel ms = new MonthSaleModel();
466
			ms.setMtdSales(this.format((long) mtdSales));
467
			ms.setMonthlySales(this.format(((long) monthSales)));
468
			ms.setPartnerType(partnerType);
27476 tejbeer 469
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
27474 tejbeer 470
			monthSaleMap.put(i, ms);
471
 
472
		}
473
		model.addAttribute("monthSales", monthSaleMap);
474
		return "monthSales";
475
	}
476
 
477
	private String format(long value) {
478
		String finalval = null;
479
 
480
		if (value >= 100000 && value < 10000000) {
481
			long reminder = value / 100000;
482
			long quitonent = value % 100000;
483
			finalval = reminder + "." + quitonent;
484
			String secondval = String.valueOf(quitonent);
485
			if (secondval.length() >= 2) {
486
				secondval = secondval.substring(0, 2);
487
				finalval = reminder + "." + secondval;
488
			}
489
			return String.valueOf(finalval) + " Lacs";
490
		} else if (value >= 1000 && value < 100000) {
491
			long reminder = value / 1000;
492
			long quitonent = value % 1000;
493
			finalval = reminder + "." + quitonent;
494
			String secondval = String.valueOf(quitonent);
495
			if (secondval.length() >= 2) {
496
				secondval = secondval.substring(0, 2);
497
				finalval = reminder + "." + secondval;
498
			}
499
			return String.valueOf(finalval) + " K";
500
		} else if (value >= 10000000 && value < 1000000000) {
501
			long reminder = value / 10000000;
502
			long quitonent = value % 10000000;
503
			finalval = reminder + "." + quitonent;
504
			String secondval = String.valueOf(quitonent);
505
			if (secondval.length() >= 2) {
506
				secondval = secondval.substring(0, 2);
507
				finalval = reminder + "." + secondval;
508
			}
509
			return String.valueOf(finalval) + " Cr";
510
		}
511
		return String.valueOf(finalval);
512
 
513
	}
514
 
27702 tejbeer 515
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
516
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 517
 
27702 tejbeer 518
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
519
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
520
 
521
		mobileBrands.stream().forEach(x -> {
522
			String brand = (String) x.get("name");
523
			if (brandStockPricesMap.containsKey(brand)) {
524
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
525
				brandStockPrice.setBrandUrl((String) x.get("url"));
526
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
527
				brandStockPrices.add(brandStockPrice);
528
			}
529
		});
530
 
531
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
532
				.collect(Collectors.toList());
533
	}
534
 
21615 kshitij.so 535
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 536
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 537
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 538
		String email = loginDetails.getEmailId();
25180 amit.gupta 539
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
540
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 541
 
25274 amit.gupta 542
		model.addAttribute("webApiHost", webApiHost);
543
		model.addAttribute("webApiPort", webApiPort);
544
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 545
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 546
		if (isAdmin) {
26011 amit.gupta 547
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 548
		} else {
25740 amit.gupta 549
			FofoStore fofoStore = null;
25180 amit.gupta 550
			try {
551
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 552
				if (!fofoStore.isActive()) {
553
					return "redirect:/login";
554
				}
25649 tejbeer 555
 
25740 amit.gupta 556
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 557
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 558
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 559
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 560
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 561
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
562
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 563
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 564
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 565
				model.addAttribute("activatedImeis",
566
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
26071 tejbeer 567
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
568
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
569
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
570
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27701 tejbeer 571
 
26071 tejbeer 572
				Double accesoriesStock = currentInventorySnapshotRepository
573
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
574
								Optional.of(false))
575
						.get(loginDetails.getFofoId());
25180 amit.gupta 576
 
26071 tejbeer 577
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
27702 tejbeer 578
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 579
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 580
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
581
 
582
				LOGGER.info("chartMap" + gson.toJson(cm));
583
				model.addAttribute("chartMap", gson.toJson(cm));
27701 tejbeer 584
 
27876 amit.gupta 585
				List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
586
						YearMonth.from(LocalDateTime.now()));
587
				model.addAttribute("publishedOffers", publishedOffers);
25180 amit.gupta 588
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 589
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
590
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 591
 
25180 amit.gupta 592
			} catch (ProfitMandiBusinessException e) {
593
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
594
 
595
			}
22481 ashik.ali 596
		}
25649 tejbeer 597
 
598
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 599
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 600
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
601
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 602
				currentMonthEnd) / 2;
25747 amit.gupta 603
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
604
				currentMonthStart) / 2;
605
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 606
				currentMonthEnd) / 2;
607
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
608
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
609
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 610
 
25653 amit.gupta 611
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
612
				currentMonthEnd);
25651 tejbeer 613
 
25653 amit.gupta 614
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
615
				currentMonthStart, currentMonthEnd);
616
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
617
			invalidHygieneCount = 1;
618
		}
619
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 620
 
25197 amit.gupta 621
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
622
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27884 tejbeer 623
		/*
624
		 * if (loginDetails.isReadOnly()) { return "dashboard-readonly"; } else { }
625
		 */
27882 amit.gupta 626
		return "dashboard1";
21615 kshitij.so 627
	}
23923 amit.gupta 628
 
27884 tejbeer 629
	@RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
630
	public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
631
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
632
		int fofoId = loginDetails.getFofoId();
633
		ChartInvestmentModel cm = this.getInvestmentChart(fofoId);
634
		model.addAttribute("chartPieMap", gson.toJson(cm));
635
 
636
		LOGGER.info("InvestmentChart" + gson.toJson(cm));
637
		LOGGER.info("InvestmentChart" + cm);
638
		return "investmentdetails";
639
	}
640
 
641
	private ChartInvestmentModel getInvestmentChart(int fofoId) throws ProfitMandiBusinessException {
642
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
643
		Map<String, Float> investmentWalletAmount = new HashMap<>();
644
		investmentWalletAmount.put("Wallet", investment.getWalletAmount());
645
 
646
		investmentWalletAmount.put("InStock", investment.getInStockAmount());
647
		investmentWalletAmount.put("Unbilled", investment.getUnbilledAmount());
648
		investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
649
		investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());
650
 
651
		ChartInvestmentModel cm = new ChartInvestmentModel();
652
 
653
		HashSet<String> labels = new HashSet<String>();
654
		labels.addAll(investmentWalletAmount.keySet());
655
 
656
		List<String> labelList = new ArrayList<>(labels);
657
		List<String> backgroundColor = new ArrayList<>();
658
 
659
		List<Float> values = new ArrayList<>();
660
		for (String label : labelList) {
661
			values.add(investmentWalletAmount.get(label));
662
			if (label.equals("Wallet")) {
663
				backgroundColor.add("pink");
664
			}
665
 
666
			if (label.equals("InStock")) {
667
				backgroundColor.add("limegreen");
668
			}
669
			if (label.equals("Unbilled")) {
670
				backgroundColor.add("red");
671
			}
672
 
673
			if (label.equals("ReturnInTransit")) {
674
				backgroundColor.add("orange");
675
			}
676
			if (label.equals("GrnPending")) {
677
				backgroundColor.add("yellow");
678
			}
679
 
680
		}
681
 
682
		Data data = new Data();
683
		data.setData(values);
684
		data.setBackgroundColor(backgroundColor);
685
		data.setLabel("DataSet 1");
686
 
687
		PieLables label = new PieLables();
688
		label.setFontColor("White");
689
		label.setFontSize(15);
690
 
691
		Legend legend = new Legend();
692
		legend.setLabels(label);
693
		legend.setPosition("left");
694
 
695
		List<Data> dataList = new ArrayList<>();
696
		dataList.add(data);
697
 
698
		DataInvestmentModel datasets = new DataInvestmentModel();
699
		datasets.setDatasets(dataList);
700
		datasets.setLabels(labels);
701
 
702
		OptionModel om = new OptionModel();
703
		om.setLegend(legend);
704
		cm.setType("pie");
705
		cm.setData(datasets);
706
		cm.setOptions(om);
707
 
708
		return cm;
709
	}
710
 
26055 tejbeer 711
	private ChartModel getBrandChart(int fofoId) {
712
 
713
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
714
 
715
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
716
 
717
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
718
 
719
		Map<String, Double> brandwisesale = fofoOrderItemRepository
720
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 721
 
27884 tejbeer 722
		LOGGER.info("brandwisesale" + brandwisesale);
723
 
26244 tejbeer 724
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
725
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27884 tejbeer 726
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
727
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
728
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
729
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26244 tejbeer 730
 
27884 tejbeer 731
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
732
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
733
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
734
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26244 tejbeer 735
 
26055 tejbeer 736
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
737
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
738
 
26244 tejbeer 739
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
740
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
741
				Optional.of(false));
27884 tejbeer 742
 
743
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
744
 
26055 tejbeer 745
		ChartModel cm = new ChartModel();
746
 
27884 tejbeer 747
		HashSet<String> labels = new HashSet<String>();
26055 tejbeer 748
		labels.addAll(brandwisesale.keySet());
27876 amit.gupta 749
		labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 750
 
27884 tejbeer 751
		List<String> labelList = new ArrayList<>(labels);
752
 
753
		List<Double> mtdActivatedImeisValues = new ArrayList<>();
754
 
755
		List<Double> mtdValues = new ArrayList<>();
756
		List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
757
		List<Double> lmtdActivatedImeisValues = new ArrayList<>();
758
		List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
26055 tejbeer 759
		List<Double> lmtdValues = new ArrayList<>();
27884 tejbeer 760
		for (String label : labelList) {
761
			mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
762
					: activatedImeisWithSellingPriceMTD.get(label));
763
			lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
764
					: activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 765
 
27884 tejbeer 766
			mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
767
			if (brandwisesale.get(label) != null) {
768
				mtdUnActivatedImeisValues
769
						.add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
770
								: activatedImeisWithSellingPriceMTD.get(label)));
771
			} else {
772
				mtdUnActivatedImeisValues.add(0.0);
773
			}
774
			if (lmtdBrandWiseSale.get(label) != null) {
775
				lmtdUnActivatedImeisValues
776
						.add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
777
								: activatedImeisWithSellingPriceLMTD.get(label)));
778
			} else {
779
				lmtdUnActivatedImeisValues.add(0.0);
780
			}
26055 tejbeer 781
 
27884 tejbeer 782
			lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
783
		}
784
		DatasetModel dsmtotal = new DatasetModel();
785
		dsmtotal.setLabel("MTD");
786
		dsmtotal.setBackgroundColor("blue");
787
		dsmtotal.setData(mtdValues);
788
		dsmtotal.setStack("stack0");
26055 tejbeer 789
 
27884 tejbeer 790
		DatasetModel dsmUnactivated = new DatasetModel();
791
		dsmUnactivated.setLabel("MTD Unactivated");
792
		dsmUnactivated.setBackgroundColor("red");
793
		dsmUnactivated.setData(mtdUnActivatedImeisValues);
794
		dsmUnactivated.setStack("stack0");
795
 
796
		LOGGER.info("mtdValuesMoney" + mtdValues);
797
 
798
		DatasetModel mtdActivatedImeis = new DatasetModel();
799
		mtdActivatedImeis.setLabel("MTD Activation");
800
		mtdActivatedImeis.setData(mtdActivatedImeisValues);
801
		mtdActivatedImeis.setBackgroundColor("blue");
802
		mtdActivatedImeis.setStack("stack0");
803
 
804
		DatasetModel lmtddsmtotal = new DatasetModel();
805
		lmtddsmtotal.setLabel("LMTD");
806
		lmtddsmtotal.setBackgroundColor("blue");
807
		lmtddsmtotal.setData(lmtdValues);
808
		lmtddsmtotal.setStack("stack1");
809
 
810
		DatasetModel lmtdUnActivated = new DatasetModel();
811
		lmtdUnActivated.setLabel("LMTD Unactivation");
812
		lmtdUnActivated.setBackgroundColor("red");
813
		lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
814
		lmtdUnActivated.setStack("stack1");
815
 
816
		DatasetModel LmtdActivatedImeis = new DatasetModel();
817
		LmtdActivatedImeis.setLabel("LMTD Activation");
818
		LmtdActivatedImeis.setBackgroundColor("blue");
819
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
820
		LmtdActivatedImeis.setStack("stack1");
821
 
26055 tejbeer 822
		List<DatasetModel> datasets = new ArrayList<>();
823
 
27884 tejbeer 824
		datasets.add(dsmUnactivated);
825
		datasets.add(mtdActivatedImeis);
826
 
827
		datasets.add(lmtdUnActivated);
828
		datasets.add(LmtdActivatedImeis);
829
 
26055 tejbeer 830
		DataModel dm = new DataModel();
831
		dm.setDatasets(datasets);
832
		dm.setLabels(labels);
833
 
834
		LegendModel lm = new LegendModel();
27703 amit.gupta 835
		lm.setPosition("top");
26055 tejbeer 836
 
837
		TitleModel tm = new TitleModel();
27703 amit.gupta 838
		tm.setText("Brand Wise Sales");
26055 tejbeer 839
		tm.setDisplay(true);
840
 
27884 tejbeer 841
		List<Axis> xAxes = new ArrayList<>();
842
		Axis xAxis = new Axis();
843
		xAxis.setStacked(true);
844
		xAxes.add(xAxis);
845
 
846
		List<Axis> yAxes = new ArrayList<>();
847
		Axis yAxis = new Axis();
848
		yAxis.setStacked(true);
849
		yAxes.add(yAxis);
850
 
851
		ScalesModel sm = new ScalesModel();
852
		sm.setxAxes(xAxes);
853
		sm.setyAxes(yAxes);
854
 
26055 tejbeer 855
		OptionsModel om = new OptionsModel();
856
		om.setLegend(lm);
857
		om.setTitle(tm);
27884 tejbeer 858
		om.setScales(sm);
26055 tejbeer 859
 
860
		cm.setType("bar");
861
		cm.setData(dm);
862
		cm.setOptions(om);
863
 
27884 tejbeer 864
		LOGGER.info("cm" + cm);
865
 
26055 tejbeer 866
		return cm;
867
 
868
	}
869
 
26418 tejbeer 870
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 871
		List<Menu> menus = null;
26011 amit.gupta 872
		try {
873
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
874
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 875
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 876
			ReporticoCacheTable rctSaholic = null;
877
			ReporticoCacheTable rctPartneStat = null;
878
 
27509 tejbeer 879
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 880
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
881
 
27509 tejbeer 882
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 883
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 884
 
27670 tejbeer 885
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 886
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 887
 
27819 tejbeer 888
			Map<AuthUser, Long> authUserTicketCount = null;
889
 
27539 tejbeer 890
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
891
				wm.put(entry.getKey(), entry.getValue());
892
			}
893
 
894
			wm.put(0, "Total Values");
895
			long stockValue = 0;
896
			long stockQty = 0;
897
			long pendingIndent = 0;
27542 tejbeer 898
			long tertiary = 0;
26418 tejbeer 899
 
27701 tejbeer 900
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 901
 
27701 tejbeer 902
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 903
			if (emails.contains(authUser.getEmailId())) {
904
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
905
			}
27556 tejbeer 906
 
27701 tejbeer 907
			LOGGER.info("fofoIds" + fofoIds);
27352 tejbeer 908
 
27701 tejbeer 909
			if (fofoIds != null) {
27539 tejbeer 910
 
27701 tejbeer 911
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
912
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
913
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
914
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
915
				// warehouseStock
916
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
917
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
918
 
919
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
920
 
921
				if (!warehouseStockMap.isEmpty()) {
922
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
923
						stockValue += warehouseStock.getValue().getStockValue();
924
						stockQty += warehouseStock.getValue().getStockQty();
925
						pendingIndent += warehouseStock.getValue().getPendingIndent();
926
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 927
					}
27701 tejbeer 928
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
929
					ws.setStockQty(stockQty);
930
					ws.setStockValue(stockValue);
931
					ws.setPendingIndent(pendingIndent);
932
					ws.setTertiary(tertiary);
933
					ws.setWarehouseId(0);
934
					warehouseStockMap.put(0, ws);
27591 tejbeer 935
 
27701 tejbeer 936
				}
27670 tejbeer 937
 
27701 tejbeer 938
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
939
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 940
 
27701 tejbeer 941
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
942
 
943
				// warehouseStock
944
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
945
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
946
 
947
				partnersBrandSaleMap = fofoStoreRepository
948
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
949
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
950
 
951
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
952
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
953
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
954
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
955
					if (bpt != null) {
956
						bpt.setAmtd(un.getUnbilledMtd());
957
						bpt.setUamtdQty(un.getUnbilledMTDQty());
958
					} else {
959
						bpt = new BrandWisePartnerSaleModel();
960
						bpt.setBrand(un.getBrand());
961
						bpt.setAmtd(un.getUnbilledMtd());
962
						bpt.setUamtdQty(un.getUnbilledMTDQty());
963
						bpt.setLms(0);
964
						bpt.setLmtd(0);
965
						bpt.setMtd(0);
966
						bpt.setMtdQty(0);
967
						bpt.setLmtd(0);
968
						bpt.setLmtdQty(0);
969
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 970
					}
26418 tejbeer 971
				}
27701 tejbeer 972
				accessoriesBrandSales = fofoStoreRepository
973
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
974
 
26418 tejbeer 975
			}
976
 
27819 tejbeer 977
			if (positions.size() > 0) {
978
				if (positions.stream()
979
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
980
								|| x.getEscalationType().equals(EscalationType.L4)
981
								|| x.getEscalationType().equals(EscalationType.L5))
982
						.count() > 0) {
983
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
984
				}
985
			}
986
 
27415 tejbeer 987
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
27701 tejbeer 988
					.contains(email))
989
 
990
			{
26029 amit.gupta 991
				menus = menuRepository.selectAll();
992
			} else if (positions.size() > 0) {
27108 amit.gupta 993
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 994
					menus = menuRepository.selectAll();
27876 amit.gupta 995
				} else if (positions.size() > 0) {
996
					if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
997
						menus = menuRepository.selectAll();
998
					} else {
999
						List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1000
								.map(x -> x.getMenuId()).collect(Collectors.toList());
1001
						if (menuIds.size() > 0) {
1002
							menus = menuRepository.selectAllByIds(menuIds);
1003
						}
26028 amit.gupta 1004
					}
27876 amit.gupta 1005
					List<Position> salesPositions = positions.stream()
1006
							.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1007
							.collect(Collectors.toList());
1008
					if (salesPositions.size() > 0) {
1009
						Set<CustomRetailer> positionRetailers = new HashSet<>();
1010
						csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
1011
							positionRetailers.addAll(customRetailers);
1012
						});
1013
						model.addAttribute("retailers", gson.toJson(positionRetailers));
1014
						model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1015
						model.addAttribute("warehouses", getWarehouses(positionRetailers));
1016
					}
1017
					List<Position> warehousePositions = positions.stream()
1018
							.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1019
							.collect(Collectors.toList());
1020
					if (warehousePositions.size() > 0) {
1021
						Set<CustomRetailer> positionRetailers = new HashSet<>();
1022
						csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
1023
							positionRetailers.addAll(customRetailers);
1024
						});
1025
						model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1026
						model.addAttribute("retailers", gson.toJson(positionRetailers));
1027
						model.addAttribute("warehouses", getWarehouses(positionRetailers));
1028
					}
1029
					model.addAttribute("authId", authUser.getId());
1030
 
26022 amit.gupta 1031
				}
26090 amit.gupta 1032
				List<Position> salesPositions = positions.stream()
1033
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1034
						.collect(Collectors.toList());
1035
				if (salesPositions.size() > 0) {
1036
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 1037
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 1038
						positionRetailers.addAll(customRetailers);
1039
					});
1040
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1041
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 1042
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 1043
				}
26114 amit.gupta 1044
				List<Position> warehousePositions = positions.stream()
1045
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1046
						.collect(Collectors.toList());
1047
				if (warehousePositions.size() > 0) {
1048
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 1049
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 1050
						positionRetailers.addAll(customRetailers);
1051
					});
1052
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1053
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 1054
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 1055
				}
26142 amit.gupta 1056
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1057
 
26022 amit.gupta 1058
			}
27628 tejbeer 1059
			model.addAttribute("rctPartneStat", rctPartneStat);
1060
 
1061
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1062
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1063
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1064
 
1065
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1066
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1067
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1068
 
27594 tejbeer 1069
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1070
 
26012 amit.gupta 1071
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1072
		}
26028 amit.gupta 1073
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1074
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1075
		model.addAttribute("menu", menuList);
26012 amit.gupta 1076
		return "admin";
1077
	}
1078
 
26468 amit.gupta 1079
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1080
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1081
			throws Exception {
1082
 
1083
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1084
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1085
 
26468 amit.gupta 1086
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1087
		if (authId != 0) {
1088
			List<Integer> fofoIds = pp.get(authId);
1089
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1090
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1091
		} else {
26418 tejbeer 1092
		}
1093
 
1094
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1095
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1096
 
1097
		return "auth_user_partner_detail";
26468 amit.gupta 1098
	}
26418 tejbeer 1099
 
27545 tejbeer 1100
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1101
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1102
			throws Exception {
27701 tejbeer 1103
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1104
		String email = loginDetails.getEmailId();
1105
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1106
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1107
 
27701 tejbeer 1108
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1109
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1110
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1111
 
27545 tejbeer 1112
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1113
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1114
		if (warehouseId != 0) {
27701 tejbeer 1115
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1116
			/*
1117
			 * List<Integer> fofoIds =
1118
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1119
			 * .map(x -> x.getId()).collect(Collectors.toList());
1120
			 */
27545 tejbeer 1121
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1122
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1123
		} else {
27701 tejbeer 1124
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1125
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1126
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1127
		}
1128
 
1129
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1130
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1131
 
1132
		return "auth_user_partner_detail";
1133
	}
1134
 
27509 tejbeer 1135
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1136
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1137
			@RequestParam List<Integer> warehouseId) throws Exception {
1138
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1139
		String email = loginDetails.getEmailId();
1140
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1141
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1142
 
27701 tejbeer 1143
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1144
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1145
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1146
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1147
		if (!warehouseId.contains(0)) {
1148
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1149
		} else {
1150
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1151
			warehouseWiseBrandStock = saholicInventoryCISRepository
1152
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1153
 
1154
		}
27542 tejbeer 1155
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1156
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1157
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1158
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1159
 
27509 tejbeer 1160
		return "warehouse_brand_stock";
1161
	}
1162
 
27529 tejbeer 1163
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1164
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1165
		inventoryService.getItemAvailabilityAndIndent();
1166
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1167
		return "response";
1168
	}
1169
 
27701 tejbeer 1170
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1171
			throws Exception {
27628 tejbeer 1172
 
1173
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1174
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1175
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1176
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1177
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1178
		if (partnerStats != null) {
27701 tejbeer 1179
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1180
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1181
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1182
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1183
						.collect(Collectors.toList());
27634 tejbeer 1184
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1185
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1186
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1187
				}
27628 tejbeer 1188
 
1189
			}
27701 tejbeer 1190
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1191
					.collect(Collectors.toList());
1192
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1193
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1194
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1195
			warehouseIdAndallValues.put(0, partnerDetailModel);
1196
		}
1197
		return warehouseIdAndallValues;
1198
	}
1199
 
1200
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1201
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1202
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1203
		ObjectOutputStream oos = null;
1204
		FileOutputStream fout = null;
1205
		try {
1206
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1207
			oos = new ObjectOutputStream(fout);
1208
			oos.writeObject(partnerStats);
1209
 
1210
		} catch (Exception ex) {
1211
			ex.printStackTrace();
1212
		} finally {
1213
			if (oos != null) {
1214
				oos.close();
1215
			}
1216
		}
1217
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1218
		if (rct == null) {
1219
			rct = new ReporticoCacheTable();
1220
			rct.setTableName("partnerStat");
1221
 
1222
		}
1223
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1224
		reporticoCacheTableRepository.persist(rct);
1225
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1226
		return "response";
1227
	}
1228
 
1229
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1230
		ObjectInputStream objectinputstream = null;
1231
		Map<Integer, PartnerDetailModel> partnerStat = null;
1232
		try {
1233
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1234
			objectinputstream = new ObjectInputStream(streamIn);
1235
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1236
 
1237
			LOGGER.info("partnerStat" + partnerStat);
1238
			objectinputstream.close();
1239
 
1240
		} catch (Exception e) {
1241
			LOGGER.info("exceptionddd" + e);
1242
 
1243
			e.printStackTrace();
1244
 
1245
		} finally {
1246
			if (objectinputstream != null) {
1247
				objectinputstream.close();
1248
				LOGGER.info("clofddd" + partnerStat);
1249
 
1250
			}
1251
		}
1252
		return partnerStat;
1253
 
1254
	}
1255
 
27539 tejbeer 1256
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1257
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1258
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1259
			throws Exception {
27509 tejbeer 1260
 
1261
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1262
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1263
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1264
 
27509 tejbeer 1265
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1266
		model.addAttribute("brands", listbrands);
27538 tejbeer 1267
		model.addAttribute("listCategory", listCategory);
1268
 
27529 tejbeer 1269
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1270
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1271
		model.addAttribute("selectedCategory", category);
1272
 
27509 tejbeer 1273
		return "warehouse_brand_item_stock";
1274
	}
1275
 
27538 tejbeer 1276
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1277
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1278
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1279
			throws Exception {
27539 tejbeer 1280
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1281
		if (warehouseId.contains(0)) {
1282
			warehouseId.addAll(warehouseMap.keySet());
1283
		}
27538 tejbeer 1284
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1285
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1286
 
27538 tejbeer 1287
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1288
		model.addAttribute("warehouseMap", warehouseMap);
1289
		return "warehouse_item_details";
1290
	}
1291
 
26114 amit.gupta 1292
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1293
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1294
		positionRetailers.stream().forEach(x -> {
1295
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1296
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1297
			}
1298
		});
26114 amit.gupta 1299
		return gson.toJson(warehouses);
1300
 
1301
	}
1302
 
27556 tejbeer 1303
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1304
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1305
			throws Exception {
27701 tejbeer 1306
 
1307
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1308
		String email = loginDetails.getEmailId();
1309
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1310
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1311
 
27670 tejbeer 1312
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1313
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1314
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1315
 
1316
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1317
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1318
 
1319
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1320
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1321
			if (bpt != null) {
1322
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1323
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1324
			} else {
1325
				bpt = new WarehouseWiseBrandSaleModel();
1326
				bpt.setWarehouseId(un.getWarehouseId());
1327
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1328
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1329
				bpt.setLms(0);
1330
				bpt.setLmtd(0);
1331
				bpt.setMtd(0);
1332
				bpt.setMtdQty(0);
1333
				bpt.setLmtd(0);
1334
				bpt.setLmtdQty(0);
1335
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1336
			}
1337
		}
27556 tejbeer 1338
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1339
 
1340
		Set<String> brands = inventoryService.getAllTagListingBrands();
1341
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1342
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1343
		model.addAttribute("brands", brands);
1344
		model.addAttribute("selectedbrand", brand);
1345
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1346
	}
1347
 
27594 tejbeer 1348
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1349
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1350
			@RequestParam String brand) throws Exception {
27701 tejbeer 1351
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1352
		String email = loginDetails.getEmailId();
1353
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1354
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1355
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1356
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1357
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1358
 
1359
		Set<String> brands = inventoryService.getAllTagListingBrands();
1360
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1361
		model.addAttribute("warehouseMap", warehouseMap);
1362
		model.addAttribute("brands", brands);
1363
		model.addAttribute("selectedbrand", brand);
1364
		return "warehousewise_accessoriesbrand_sale";
1365
	}
1366
 
27556 tejbeer 1367
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1368
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1369
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1370
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1371
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1372
		String email = loginDetails.getEmailId();
1373
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1374
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 1375
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1376
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1377
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1378
 
1379
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1380
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1381
 
1382
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1383
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1384
			if (bpt != null) {
1385
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1386
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1387
			} else {
1388
				bpt = new WarehouseBrandWiseItemSaleModel();
1389
				bpt.setWarehouseId(un.getWarehouseId());
1390
				bpt.setItemId(un.getItemId());
1391
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1392
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1393
				bpt.setBrand(un.getBrand());
1394
				bpt.setModelName(un.getModelName());
1395
				bpt.setModelNumber(un.getModelNumber());
1396
				bpt.setColor(un.getColor());
1397
				bpt.setLms(0);
1398
				bpt.setLmtd(0);
1399
				bpt.setMtd(0);
1400
				bpt.setMtdQty(0);
1401
				bpt.setLmtd(0);
1402
				bpt.setLmtdQty(0);
1403
				branditemSalesMap.put(un.getItemId(), bpt);
1404
			}
1405
		}
1406
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1407
		model.addAttribute("warehouseMap", warehouseMap);
1408
		return "warehouse_partner_itemwise_sale";
1409
	}
1410
 
27594 tejbeer 1411
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1412
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1413
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1414
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1415
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1416
		String email = loginDetails.getEmailId();
1417
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1418
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1419
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1420
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1421
		model.addAttribute("branditemSales", branditemSales);
1422
		model.addAttribute("warehouseMap", warehouseMap);
1423
		return "warehouse_accessories_itemwsie_sale";
1424
	}
1425
 
26012 amit.gupta 1426
	private List<Menu> prepareMenu(List<Menu> menus) {
1427
		List<Menu> returnMenu = new ArrayList<>();
1428
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1429
		for (Menu menu : menus) {
1430
			if (menu.get_parent() == null) {
26014 amit.gupta 1431
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1432
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1433
				}
1434
			} else {
26012 amit.gupta 1435
				Menu parentMenu = menu.get_parent();
1436
				if (!subMenuMap.containsKey(parentMenu)) {
1437
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1438
				}
26012 amit.gupta 1439
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1440
			}
1441
		}
26012 amit.gupta 1442
		subMenuMap.entrySet().stream().forEach(entry -> {
1443
			entry.getKey().setSubMenus(entry.getValue());
1444
			returnMenu.add(entry.getKey());
1445
		});
1446
		return returnMenu;
26005 amit.gupta 1447
	}
1448
 
24288 amit.gupta 1449
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1450
	private boolean hasGift(int fofoId) {
1451
		try {
24288 amit.gupta 1452
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1453
					.getAvailability() > 0;
24203 amit.gupta 1454
		} catch (ProfitMandiBusinessException e) {
1455
			return false;
1456
		}
1457
	}
24288 amit.gupta 1458
 
22354 ashik.ali 1459
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1460
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1461
		model.addAttribute("appContextPath", request.getContextPath());
1462
		return "contact-us";
1463
	}
23923 amit.gupta 1464
 
25649 tejbeer 1465
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1466
	public String getNotificationsWithType(HttpServletRequest request,
1467
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1468
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1469
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1470
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1471
		int userId = 0;
1472
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1473
		if (isAdmin) {
1474
			userId = loginDetails.getFofoId();
1475
		} else {
1476
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1477
		}
25683 tejbeer 1478
		List<Notification> notifications = null;
1479
 
26086 tejbeer 1480
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1481
				userId, offset, limit);
1482
		LOGGER.info("messageType" + messageType);
1483
		notifications = getNotifications(notificationCampaigns, messageType);
1484
 
25683 tejbeer 1485
		model.addAttribute("notifications", notifications);
1486
 
1487
		LOGGER.info("notifications" + notifications);
1488
		return "notification-template";
1489
	}
1490
 
1491
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1492
			throws ProfitMandiBusinessException {
1493
		List<Notification> notifications = new ArrayList<>();
1494
		Document document = null;
1495
		if (messageType != null) {
1496
			for (NotificationCampaign notificationCampaign : nc) {
1497
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1498
					Notification ns = new Notification();
1499
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1500
							SimpleCampaignParams.class);
1501
					Campaign campaign = new SimpleCampaign(scp);
1502
					LocalDateTime expire = campaign.getExpireTimestamp();
1503
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1504
					ns.setType(campaign.getType());
1505
					ns.setMessage(campaign.getMessage());
1506
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1507
					if (notificationCampaign.getDocumentId() != null) {
1508
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1509
						ns.setDocumentName(document.getDisplayName());
1510
					}
25683 tejbeer 1511
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1512
					ns.setShowImage(campaign.getShowImage());
1513
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1514
					ns.setDocumentId(notificationCampaign.getDocumentId());
1515
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1516
					ns.setCreated(
1517
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1518
									* 1000);
1519
					if (LocalDateTime.now().isAfter(expire)) {
1520
						ns.setExpired(true);
1521
					} else {
1522
						ns.setExpired(false);
1523
					}
1524
					notifications.add(ns);
1525
				}
1526
			}
25683 tejbeer 1527
		} else {
1528
			for (NotificationCampaign notificationCampaign : nc) {
1529
 
1530
				Notification ns = new Notification();
1531
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1532
						SimpleCampaignParams.class);
1533
				Campaign campaign = new SimpleCampaign(scp);
1534
				LocalDateTime expire = campaign.getExpireTimestamp();
1535
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1536
				ns.setType(campaign.getType());
1537
				ns.setMessage(campaign.getMessage());
1538
				ns.setTitle(campaign.getTitle());
1539
				if (notificationCampaign.getDocumentId() != null) {
1540
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1541
					ns.setDocumentName(document.getDisplayName());
1542
				}
1543
				ns.setUrl(campaign.getUrl());
1544
				ns.setShowImage(campaign.getShowImage());
1545
				ns.setImageUrl(campaign.getImageUrl());
1546
				ns.setDocumentId(notificationCampaign.getDocumentId());
1547
				ns.setMessageType(notificationCampaign.getMessageType());
1548
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1549
						* 1000);
1550
				if (LocalDateTime.now().isAfter(expire)) {
1551
					ns.setExpired(true);
1552
				} else {
1553
					ns.setExpired(false);
1554
				}
1555
				notifications.add(ns);
1556
			}
1557
 
25649 tejbeer 1558
		}
25683 tejbeer 1559
		return notifications;
25651 tejbeer 1560
 
1561
	}
25649 tejbeer 1562
 
25651 tejbeer 1563
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1564
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1565
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1566
			throws ProfitMandiBusinessException {
1567
		Document document = documentRepository.selectById(documentId);
1568
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1569
		if (nc.getDocumentId() == null) {
1570
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1571
		}
1572
		if (nc.getDocumentId() != documentId) {
1573
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1574
		}
1575
		return responseSender.ok(document);
25649 tejbeer 1576
	}
1577
 
25651 tejbeer 1578
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1579
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1580
			throws ProfitMandiBusinessException {
1581
 
1582
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1583
 
1584
		if (nc.getDocumentId() == null) {
1585
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1586
		}
1587
 
1588
		Document document = documentRepository.selectById(nc.getDocumentId());
1589
 
1590
		FileInputStream file = null;
1591
		try {
1592
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1593
		} catch (FileNotFoundException e) {
1594
			LOGGER.error("Retailer Document file not found : ", e);
1595
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1596
		}
1597
		// ByteArrayOutputStream byteArrayOutputStream = new
1598
		// ByteArrayOutputStream();
1599
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1600
 
1601
		final HttpHeaders headers = new HttpHeaders();
1602
		String contentType = "";
1603
		if (document.getContentType() == ContentType.JPEG) {
1604
			contentType = "image/jpeg";
1605
		} else if (document.getContentType() == ContentType.PNG) {
1606
			contentType = "image/png";
1607
		} else if (document.getContentType() == ContentType.PDF) {
1608
			contentType = "application/pdf";
1609
		}
1610
		headers.set("Content-Type", contentType);
1611
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1612
		headers.setContentLength(document.getSize());
1613
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1614
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1615
	}
26460 amit.gupta 1616
 
1617
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1618
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1619
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1620
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1621
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1622
			List<Integer> authIds = l2l1.getValue();
1623
			authIds.add(l2l1.getKey());
1624
 
1625
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1626
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1627
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1628
			if (!leads.isEmpty()) {
1629
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1630
			} else {
1631
				authIdAndleadsCountMap.put(auth.getId(), 0);
1632
			}
26422 tejbeer 1633
		}
26468 amit.gupta 1634
 
26460 amit.gupta 1635
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1636
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1637
				.collect(Collectors.toList());
26433 tejbeer 1638
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1639
 
26460 amit.gupta 1640
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1641
 
26460 amit.gupta 1642
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1643
		for (int authUserId : pp.keySet()) {
1644
			if (L2L1Mapping.keySet().contains(authUserId)) {
1645
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1646
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1647
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1648
						.collect(Collectors.toList());
27632 tejbeer 1649
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1650
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1651
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1652
			}
1653
		}
26997 amit.gupta 1654
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1655
				.collect(Collectors.toList());
26468 amit.gupta 1656
		PartnerDetailModel partnerDetailModel = partnerStatsService
1657
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1658
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1659
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1660
		return authIdAndallValues;
1661
	}
1662
 
27579 tejbeer 1663
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1664
	public String getItemWiseTertiary(HttpServletRequest request,
1665
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1666
			throws ProfitMandiBusinessException {
1667
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1668
 
1669
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1670
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1671
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1672
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1673
		return "item-wise-tertiary";
1674
	}
1675
 
27586 tejbeer 1676
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1677
	public String getItemWiseIndent(HttpServletRequest request,
1678
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1679
			throws ProfitMandiBusinessException {
1680
 
1681
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1682
		model.addAttribute("unbilledOrders", unbilledOrders);
1683
 
1684
		return "item-wise-indent";
1685
	}
1686
 
27636 tejbeer 1687
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1688
	public String getPartnerInvestment(HttpServletRequest request,
1689
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1690
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
1691
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1692
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1693
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1694
		model.addAttribute("customRetailer", customRetailer);
1695
		return "partner-investment";
1696
	}
27727 tejbeer 1697
 
27704 amit.gupta 1698
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1699
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1700
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1701
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1702
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1703
 
27704 amit.gupta 1704
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1705
		return "partner-pending-indent-item";
1706
	}
1707
 
27636 tejbeer 1708
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1709
	public String getPartnerActivateStockItem(HttpServletRequest request,
1710
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1711
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1712
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1713
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1714
 
1715
		for (InventoryItem inventoryItem : inventoryItems) {
1716
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1717
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1718
			ActivateItemModel aim = new ActivateItemModel();
1719
			aim.setFofoId(inventoryItem.getFofoId());
1720
			aim.setQuantity(inventoryItem.getGoodQuantity());
1721
			aim.setAmount(tagListing.getSellingPrice());
1722
			aim.setItemDescription(item.getItemDescription());
1723
			aim.setItemId(inventoryItem.getItemId());
1724
			activateStocks.add(aim);
1725
		}
1726
 
1727
		model.addAttribute("activateStocks", activateStocks);
1728
		model.addAttribute("customRetailer", customRetailer);
1729
		return "partner-activate-stock";
1730
	}
1731
 
1732
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1733
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
1734
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1735
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1736
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1737
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1738
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 1739
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1740
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 1741
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1742
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 1743
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1744
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1745
 
27636 tejbeer 1746
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1747
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 1748
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 1749
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 1750
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1751
 
27636 tejbeer 1752
		model.addAttribute("customRetailer", customRetailer);
1753
		return "partner-brand-mtd-sale";
1754
	}
1755
 
27637 tejbeer 1756
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1757
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
1758
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1759
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1760
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1761
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1762
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 1763
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1764
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 1765
 
1766
		Double accesorieslmtdsale = fofoOrderRepository
1767
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1768
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1769
				.get(fofoId);
27638 tejbeer 1770
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1771
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1772
				Optional.of(false)).get(fofoId);
1773
 
27637 tejbeer 1774
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 1775
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1776
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 1777
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1778
		model.addAttribute("customRetailer", customRetailer);
1779
		return "partner-brand-lmtd-sale";
1780
	}
1781
 
27660 tejbeer 1782
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1783
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
1784
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1785
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1786
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1787
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1788
 
1789
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1790
				curDate.withDayOfMonth(1).minusMonths(1),
1791
				curDate.with(LocalTime.MAX).minusMonths(1).withDayOfMonth(lengthOfMonth), fofoId);
1792
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1793
				curDate.withDayOfMonth(1).minusMonths(1),
1794
				curDate.with(LocalTime.MAX).minusMonths(1).withDayOfMonth(lengthOfMonth), fofoId);
1795
 
1796
		Double accesorieslmssale = fofoOrderRepository
1797
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1798
						curDate.with(LocalTime.MAX).minusMonths(1).withDayOfMonth(lengthOfMonth), Optional.of(false))
1799
				.get(fofoId);
1800
		Long accesorieslmsqty = fofoOrderRepository
1801
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1802
						curDate.withDayOfMonth(1).minusMonths(1),
1803
						curDate.with(LocalTime.MAX).minusMonths(1).withDayOfMonth(lengthOfMonth), Optional.of(false))
1804
				.get(fofoId);
1805
 
1806
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1807
		model.addAttribute("brandLmsQty", brandLmsQty);
1808
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1809
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1810
		model.addAttribute("customRetailer", customRetailer);
1811
		return "partner-brand-lms-sale";
1812
	}
1813
 
27640 tejbeer 1814
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1815
	public String getPatnerInStock(HttpServletRequest request,
1816
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1817
 
1818
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1819
 
27660 tejbeer 1820
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 1821
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 1822
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 1823
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1824
 
27660 tejbeer 1825
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1826
				.selectInStockItemsByBrand(fofoId);
1827
 
1828
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1829
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1830
 
1831
		model.addAttribute("stockItemMap", stockItemMap);
1832
		model.addAttribute("mobileStock", mobileStocks);
1833
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 1834
		model.addAttribute("customRetailer", customRetailer);
1835
		return "partner-instock-item";
1836
	}
1837
 
27660 tejbeer 1838
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1839
	public String getOpenTicketByFofoId(HttpServletRequest request,
1840
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1841
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1842
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1843
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1844
				.collect(Collectors.toList());
1845
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1846
 
1847
		for (TicketAssigned ticketAssign : ticketAssigns) {
1848
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1849
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1850
		}
1851
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1852
		model.addAttribute("ticketAssigns", ticketAssigns);
1853
		model.addAttribute("customRetailer", customRetailer);
1854
		return "open-ticket";
1855
	}
1856
 
21615 kshitij.so 1857
}