Subversion Repositories SmartDukaan

Rev

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