Subversion Repositories SmartDukaan

Rev

Rev 27978 | Rev 28015 | 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);
27900 tejbeer 646
 
27884 tejbeer 647
		Map<String, Float> investmentWalletAmount = new HashMap<>();
648
		investmentWalletAmount.put("Wallet", investment.getWalletAmount());
28014 tejbeer 649
		investmentWalletAmount.put("InStocks", investment.getInStockAmount()-investment.getActivatedStockAmount());
27900 tejbeer 650
		investmentWalletAmount.put("Unbilled Order", investment.getUnbilledAmount());
27884 tejbeer 651
		investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
652
		investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());
653
 
27900 tejbeer 654
		if (investment.getShortInvestment() > 0) {
655
			investmentWalletAmount.put("Short Investment", investment.getShortInvestment());
656
		}
657
 
27884 tejbeer 658
		ChartInvestmentModel cm = new ChartInvestmentModel();
659
 
660
		HashSet<String> labels = new HashSet<String>();
661
		labels.addAll(investmentWalletAmount.keySet());
662
 
663
		List<String> labelList = new ArrayList<>(labels);
664
		List<String> backgroundColor = new ArrayList<>();
27900 tejbeer 665
		List<Float> labelsValue = new ArrayList<>();
27884 tejbeer 666
		List<Float> values = new ArrayList<>();
667
		for (String label : labelList) {
668
			values.add(investmentWalletAmount.get(label));
669
			if (label.equals("Wallet")) {
670
				backgroundColor.add("pink");
671
			}
27900 tejbeer 672
			if (label.equals("Short Investment")) {
673
				backgroundColor.add("red");
674
			}
27978 tejbeer 675
			if (label.equals("Ex.Activated Stocks")) {
27900 tejbeer 676
				backgroundColor.add("#9ACD32");
27884 tejbeer 677
			}
27900 tejbeer 678
			if (label.equals("Unbilled Order")) {
679
				backgroundColor.add("blue");
27884 tejbeer 680
			}
681
 
682
			if (label.equals("ReturnInTransit")) {
683
				backgroundColor.add("orange");
684
			}
685
			if (label.equals("GrnPending")) {
686
				backgroundColor.add("yellow");
687
			}
688
 
689
		}
690
 
691
		Data data = new Data();
692
		data.setData(values);
693
		data.setBackgroundColor(backgroundColor);
694
		data.setLabel("DataSet 1");
695
 
696
		PieLables label = new PieLables();
697
		label.setFontColor("White");
698
		label.setFontSize(15);
699
 
700
		Legend legend = new Legend();
701
		legend.setLabels(label);
702
		legend.setPosition("left");
703
 
704
		List<Data> dataList = new ArrayList<>();
705
		dataList.add(data);
706
 
707
		DataInvestmentModel datasets = new DataInvestmentModel();
708
		datasets.setDatasets(dataList);
709
		datasets.setLabels(labels);
710
 
711
		OptionModel om = new OptionModel();
712
		om.setLegend(legend);
713
		cm.setType("pie");
714
		cm.setData(datasets);
715
		cm.setOptions(om);
716
 
717
		return cm;
718
	}
719
 
26055 tejbeer 720
	private ChartModel getBrandChart(int fofoId) {
721
 
722
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
723
 
724
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
725
 
726
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
727
 
27900 tejbeer 728
		Map<String, Double> brandwisesale = fofoOrderItemRepository
26055 tejbeer 729
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 730
 
27900 tejbeer 731
		LOGGER.info("brandwisesale" + brandwisesale);
27884 tejbeer 732
 
26244 tejbeer 733
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
734
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27900 tejbeer 735
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
27978 tejbeer 736
 
27884 tejbeer 737
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
738
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
739
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
27900 tejbeer 740
 
27978 tejbeer 741
		activatedImeisWithSellingPriceMTD.put("Lava", brandwisesale.get("Lava"));
742
 
743
 
744
 
745
 
27884 tejbeer 746
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
747
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
748
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
749
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26244 tejbeer 750
 
26055 tejbeer 751
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
752
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27978 tejbeer 753
		activatedImeisWithSellingPriceLMTD.put("Lava", lmtdBrandWiseSale.get("Lava"));
26055 tejbeer 754
 
26244 tejbeer 755
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
756
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
757
				Optional.of(false));
27884 tejbeer 758
 
759
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
760
 
26055 tejbeer 761
		ChartModel cm = new ChartModel();
762
 
27884 tejbeer 763
		HashSet<String> labels = new HashSet<String>();
27900 tejbeer 764
		labels.addAll(brandwisesale.keySet());
27876 amit.gupta 765
		labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 766
 
27884 tejbeer 767
		List<String> labelList = new ArrayList<>(labels);
768
 
769
		List<Double> mtdActivatedImeisValues = new ArrayList<>();
770
 
771
		List<Double> mtdValues = new ArrayList<>();
772
		List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
773
		List<Double> lmtdActivatedImeisValues = new ArrayList<>();
774
		List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
26055 tejbeer 775
		List<Double> lmtdValues = new ArrayList<>();
27884 tejbeer 776
		for (String label : labelList) {
777
			mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
778
					: activatedImeisWithSellingPriceMTD.get(label));
779
			lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
780
					: activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 781
 
27900 tejbeer 782
			mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
783
			if (brandwisesale.get(label) != null) {
27884 tejbeer 784
				mtdUnActivatedImeisValues
27900 tejbeer 785
						.add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
27884 tejbeer 786
								: activatedImeisWithSellingPriceMTD.get(label)));
787
			} else {
788
				mtdUnActivatedImeisValues.add(0.0);
789
			}
790
			if (lmtdBrandWiseSale.get(label) != null) {
791
				lmtdUnActivatedImeisValues
792
						.add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
793
								: activatedImeisWithSellingPriceLMTD.get(label)));
794
			} else {
795
				lmtdUnActivatedImeisValues.add(0.0);
796
			}
26055 tejbeer 797
 
27884 tejbeer 798
			lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
799
		}
800
		DatasetModel dsmtotal = new DatasetModel();
801
		dsmtotal.setLabel("MTD");
802
		dsmtotal.setBackgroundColor("blue");
803
		dsmtotal.setData(mtdValues);
804
		dsmtotal.setStack("stack0");
27900 tejbeer 805
		dsmtotal.setOrder(1);
26055 tejbeer 806
 
27884 tejbeer 807
		DatasetModel dsmUnactivated = new DatasetModel();
808
		dsmUnactivated.setLabel("MTD Unactivated");
809
		dsmUnactivated.setBackgroundColor("red");
810
		dsmUnactivated.setData(mtdUnActivatedImeisValues);
811
		dsmUnactivated.setStack("stack0");
27900 tejbeer 812
		dsmUnactivated.setOrder(1);
27884 tejbeer 813
 
814
		LOGGER.info("mtdValuesMoney" + mtdValues);
815
 
816
		DatasetModel mtdActivatedImeis = new DatasetModel();
817
		mtdActivatedImeis.setLabel("MTD Activation");
818
		mtdActivatedImeis.setData(mtdActivatedImeisValues);
27913 tejbeer 819
		mtdActivatedImeis.setBackgroundColor("#00008b");
27884 tejbeer 820
		mtdActivatedImeis.setStack("stack0");
27900 tejbeer 821
		mtdActivatedImeis.setOrder(1);
27884 tejbeer 822
 
823
		DatasetModel lmtddsmtotal = new DatasetModel();
824
		lmtddsmtotal.setLabel("LMTD");
825
		lmtddsmtotal.setBackgroundColor("blue");
826
		lmtddsmtotal.setData(lmtdValues);
827
		lmtddsmtotal.setStack("stack1");
27900 tejbeer 828
		lmtddsmtotal.setOrder(1);
27884 tejbeer 829
 
830
		DatasetModel lmtdUnActivated = new DatasetModel();
831
		lmtdUnActivated.setLabel("LMTD Unactivation");
832
		lmtdUnActivated.setBackgroundColor("red");
833
		lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
834
		lmtdUnActivated.setStack("stack1");
27900 tejbeer 835
		lmtdUnActivated.setOrder(1);
27884 tejbeer 836
 
837
		DatasetModel LmtdActivatedImeis = new DatasetModel();
838
		LmtdActivatedImeis.setLabel("LMTD Activation");
27910 tejbeer 839
		LmtdActivatedImeis.setBackgroundColor("#87ceeb");
27884 tejbeer 840
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
841
		LmtdActivatedImeis.setStack("stack1");
27900 tejbeer 842
		LmtdActivatedImeis.setOrder(1);
27930 amit.gupta 843
 
27900 tejbeer 844
		DatasetModel linemtdChart = new DatasetModel();
845
		linemtdChart.setLabel("MTD");
27915 tejbeer 846
		linemtdChart.setBackgroundColor("#006400");
27930 amit.gupta 847
 
27900 tejbeer 848
		linemtdChart.setData(mtdValues);
849
		linemtdChart.setType("line");
850
		linemtdChart.setOrder(2);
27910 tejbeer 851
		linemtdChart.setFill("false");
27930 amit.gupta 852
 
27900 tejbeer 853
		DatasetModel lineLmtdChart = new DatasetModel();
854
		lineLmtdChart.setLabel("LMTD");
27978 tejbeer 855
		lineLmtdChart.setBackgroundColor("hotpink");
27900 tejbeer 856
		lineLmtdChart.setData(lmtdValues);
857
		lineLmtdChart.setType("line");
27910 tejbeer 858
		lineLmtdChart.setOrder(3);
859
		lineLmtdChart.setFill("false");
27884 tejbeer 860
 
26055 tejbeer 861
		List<DatasetModel> datasets = new ArrayList<>();
27978 tejbeer 862
		datasets.add(mtdActivatedImeis);
863
		datasets.add(dsmUnactivated);
864
		datasets.add(LmtdActivatedImeis);
27910 tejbeer 865
		datasets.add(lmtdUnActivated);
27900 tejbeer 866
		datasets.add(linemtdChart);
867
		datasets.add(lineLmtdChart);
27884 tejbeer 868
 
26055 tejbeer 869
		DataModel dm = new DataModel();
870
		dm.setDatasets(datasets);
871
		dm.setLabels(labels);
872
 
873
		LegendModel lm = new LegendModel();
27703 amit.gupta 874
		lm.setPosition("top");
26055 tejbeer 875
 
876
		TitleModel tm = new TitleModel();
27703 amit.gupta 877
		tm.setText("Brand Wise Sales");
26055 tejbeer 878
		tm.setDisplay(true);
879
 
27884 tejbeer 880
		List<Axis> xAxes = new ArrayList<>();
881
		Axis xAxis = new Axis();
882
		xAxis.setStacked(true);
883
		xAxes.add(xAxis);
884
 
885
		List<Axis> yAxes = new ArrayList<>();
886
		Axis yAxis = new Axis();
27910 tejbeer 887
		yAxis.setStacked(false);
27884 tejbeer 888
		yAxes.add(yAxis);
889
 
890
		ScalesModel sm = new ScalesModel();
891
		sm.setxAxes(xAxes);
892
 
26055 tejbeer 893
		OptionsModel om = new OptionsModel();
894
		om.setLegend(lm);
895
		om.setTitle(tm);
27884 tejbeer 896
		om.setScales(sm);
26055 tejbeer 897
 
898
		cm.setType("bar");
899
		cm.setData(dm);
900
		cm.setOptions(om);
901
 
27884 tejbeer 902
		LOGGER.info("cm" + cm);
903
 
26055 tejbeer 904
		return cm;
905
 
906
	}
907
 
26418 tejbeer 908
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 909
		List<Menu> menus = null;
26011 amit.gupta 910
		try {
911
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
912
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 913
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 914
			ReporticoCacheTable rctSaholic = null;
915
			ReporticoCacheTable rctPartneStat = null;
916
 
27509 tejbeer 917
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 918
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
919
 
27509 tejbeer 920
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 921
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 922
 
27670 tejbeer 923
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 924
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 925
 
27819 tejbeer 926
			Map<AuthUser, Long> authUserTicketCount = null;
927
 
27539 tejbeer 928
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
929
				wm.put(entry.getKey(), entry.getValue());
930
			}
931
 
932
			wm.put(0, "Total Values");
933
			long stockValue = 0;
934
			long stockQty = 0;
935
			long pendingIndent = 0;
27542 tejbeer 936
			long tertiary = 0;
26418 tejbeer 937
 
27701 tejbeer 938
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 939
 
27701 tejbeer 940
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 941
			if (emails.contains(authUser.getEmailId())) {
942
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
27930 amit.gupta 943
				LOGGER.info("fofoIds" + fofoIds);
27727 tejbeer 944
			}
27556 tejbeer 945
 
27352 tejbeer 946
 
27701 tejbeer 947
			if (fofoIds != null) {
27539 tejbeer 948
 
27701 tejbeer 949
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
950
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
951
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
952
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
953
				// warehouseStock
954
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
955
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
956
 
957
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
958
 
959
				if (!warehouseStockMap.isEmpty()) {
960
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
961
						stockValue += warehouseStock.getValue().getStockValue();
962
						stockQty += warehouseStock.getValue().getStockQty();
963
						pendingIndent += warehouseStock.getValue().getPendingIndent();
964
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 965
					}
27701 tejbeer 966
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
967
					ws.setStockQty(stockQty);
968
					ws.setStockValue(stockValue);
969
					ws.setPendingIndent(pendingIndent);
970
					ws.setTertiary(tertiary);
971
					ws.setWarehouseId(0);
972
					warehouseStockMap.put(0, ws);
27591 tejbeer 973
 
27701 tejbeer 974
				}
27670 tejbeer 975
 
27701 tejbeer 976
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
977
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 978
 
27701 tejbeer 979
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
980
 
981
				// warehouseStock
982
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
983
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
984
 
985
				partnersBrandSaleMap = fofoStoreRepository
986
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
987
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
988
 
989
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
990
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
991
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
992
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
993
					if (bpt != null) {
994
						bpt.setAmtd(un.getUnbilledMtd());
995
						bpt.setUamtdQty(un.getUnbilledMTDQty());
996
					} else {
997
						bpt = new BrandWisePartnerSaleModel();
998
						bpt.setBrand(un.getBrand());
999
						bpt.setAmtd(un.getUnbilledMtd());
1000
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1001
						bpt.setLms(0);
1002
						bpt.setLmtd(0);
1003
						bpt.setMtd(0);
1004
						bpt.setMtdQty(0);
1005
						bpt.setLmtd(0);
1006
						bpt.setLmtdQty(0);
1007
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1008
					}
26418 tejbeer 1009
				}
27701 tejbeer 1010
				accessoriesBrandSales = fofoStoreRepository
1011
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
27933 amit.gupta 1012
				Set<CustomRetailer> positionRetailers = fofoIds.stream().map(x->retailerService.getAllFofoRetailers().get(x)).filter(x->x!=null).collect(Collectors.toSet());
27931 amit.gupta 1013
				model.addAttribute("retailers", gson.toJson(positionRetailers));
1014
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1015
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
26418 tejbeer 1016
			}
1017
 
27819 tejbeer 1018
			if (positions.size() > 0) {
1019
				if (positions.stream()
1020
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1021
								|| x.getEscalationType().equals(EscalationType.L4)
1022
								|| x.getEscalationType().equals(EscalationType.L5))
1023
						.count() > 0) {
1024
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1025
				}
1026
			}
1027
 
27415 tejbeer 1028
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
27701 tejbeer 1029
					.contains(email))
1030
 
1031
			{
26029 amit.gupta 1032
				menus = menuRepository.selectAll();
1033
			} else if (positions.size() > 0) {
27108 amit.gupta 1034
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1035
					menus = menuRepository.selectAll();
27893 tejbeer 1036
				} else {
1037
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1038
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1039
					if (menuIds.size() > 0) {
1040
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1041
					}
26022 amit.gupta 1042
				}
27930 amit.gupta 1043
			}
1044
				/*List<Position> salesPositions = positions.stream()
26090 amit.gupta 1045
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1046
						.collect(Collectors.toList());
1047
				if (salesPositions.size() > 0) {
1048
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 1049
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 1050
						positionRetailers.addAll(customRetailers);
1051
					});
27930 amit.gupta 1052
				}*/
27931 amit.gupta 1053
				if(fofoIds == null) {
27930 amit.gupta 1054
					List<Position> warehousePositions = positions.stream()
1055
							.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1056
							.collect(Collectors.toList());
1057
					if (warehousePositions.size() > 0) {
1058
						Set<CustomRetailer> positionRetailers = new HashSet<>();
1059
						csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
1060
							positionRetailers.addAll(customRetailers);
1061
						});
1062
						model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1063
						model.addAttribute("retailers", gson.toJson(positionRetailers));
1064
						model.addAttribute("warehouses", getWarehouses(positionRetailers));
1065
					}
26090 amit.gupta 1066
				}
26142 amit.gupta 1067
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1068
 
27628 tejbeer 1069
			model.addAttribute("rctPartneStat", rctPartneStat);
1070
 
1071
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1072
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1073
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1074
 
1075
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1076
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1077
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1078
 
27594 tejbeer 1079
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1080
 
26012 amit.gupta 1081
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1082
		}
26028 amit.gupta 1083
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1084
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1085
		model.addAttribute("menu", menuList);
26012 amit.gupta 1086
		return "admin";
1087
	}
1088
 
26468 amit.gupta 1089
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1090
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1091
			throws Exception {
1092
 
1093
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1094
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1095
 
26468 amit.gupta 1096
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1097
		if (authId != 0) {
1098
			List<Integer> fofoIds = pp.get(authId);
1099
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1100
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1101
		} else {
26418 tejbeer 1102
		}
1103
 
1104
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1105
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1106
 
1107
		return "auth_user_partner_detail";
26468 amit.gupta 1108
	}
26418 tejbeer 1109
 
27545 tejbeer 1110
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1111
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1112
			throws Exception {
27701 tejbeer 1113
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1114
		String email = loginDetails.getEmailId();
1115
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1116
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1117
 
27701 tejbeer 1118
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1119
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1120
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1121
 
27545 tejbeer 1122
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1123
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1124
		if (warehouseId != 0) {
27701 tejbeer 1125
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1126
			/*
1127
			 * List<Integer> fofoIds =
1128
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1129
			 * .map(x -> x.getId()).collect(Collectors.toList());
1130
			 */
27545 tejbeer 1131
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1132
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1133
		} else {
27701 tejbeer 1134
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1135
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1136
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1137
		}
1138
 
1139
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1140
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1141
 
1142
		return "auth_user_partner_detail";
1143
	}
1144
 
27509 tejbeer 1145
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1146
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1147
			@RequestParam List<Integer> warehouseId) throws Exception {
1148
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1149
		String email = loginDetails.getEmailId();
1150
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1151
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1152
 
27701 tejbeer 1153
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1154
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1155
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1156
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1157
		if (!warehouseId.contains(0)) {
1158
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1159
		} else {
1160
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1161
			warehouseWiseBrandStock = saholicInventoryCISRepository
1162
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1163
 
1164
		}
27542 tejbeer 1165
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1166
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1167
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1168
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1169
 
27509 tejbeer 1170
		return "warehouse_brand_stock";
1171
	}
1172
 
27529 tejbeer 1173
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1174
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1175
		inventoryService.getItemAvailabilityAndIndent();
1176
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1177
		return "response";
1178
	}
1179
 
27701 tejbeer 1180
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1181
			throws Exception {
27628 tejbeer 1182
 
1183
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1184
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1185
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1186
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1187
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1188
		if (partnerStats != null) {
27701 tejbeer 1189
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1190
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1191
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1192
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1193
						.collect(Collectors.toList());
27634 tejbeer 1194
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1195
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1196
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1197
				}
27628 tejbeer 1198
 
1199
			}
27701 tejbeer 1200
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1201
					.collect(Collectors.toList());
1202
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1203
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1204
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1205
			warehouseIdAndallValues.put(0, partnerDetailModel);
1206
		}
1207
		return warehouseIdAndallValues;
1208
	}
1209
 
1210
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1211
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1212
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1213
		ObjectOutputStream oos = null;
1214
		FileOutputStream fout = null;
1215
		try {
1216
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1217
			oos = new ObjectOutputStream(fout);
1218
			oos.writeObject(partnerStats);
1219
 
1220
		} catch (Exception ex) {
1221
			ex.printStackTrace();
1222
		} finally {
1223
			if (oos != null) {
1224
				oos.close();
1225
			}
1226
		}
1227
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1228
		if (rct == null) {
1229
			rct = new ReporticoCacheTable();
1230
			rct.setTableName("partnerStat");
1231
 
1232
		}
1233
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1234
		reporticoCacheTableRepository.persist(rct);
1235
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1236
		return "response";
1237
	}
1238
 
1239
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1240
		ObjectInputStream objectinputstream = null;
1241
		Map<Integer, PartnerDetailModel> partnerStat = null;
1242
		try {
1243
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1244
			objectinputstream = new ObjectInputStream(streamIn);
1245
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1246
 
1247
			LOGGER.info("partnerStat" + partnerStat);
1248
			objectinputstream.close();
1249
 
1250
		} catch (Exception e) {
1251
			LOGGER.info("exceptionddd" + e);
1252
 
1253
			e.printStackTrace();
1254
 
1255
		} finally {
1256
			if (objectinputstream != null) {
1257
				objectinputstream.close();
1258
				LOGGER.info("clofddd" + partnerStat);
1259
 
1260
			}
1261
		}
1262
		return partnerStat;
1263
 
1264
	}
1265
 
27539 tejbeer 1266
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1267
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1268
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1269
			throws Exception {
27509 tejbeer 1270
 
1271
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1272
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1273
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1274
 
27509 tejbeer 1275
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1276
		model.addAttribute("brands", listbrands);
27538 tejbeer 1277
		model.addAttribute("listCategory", listCategory);
1278
 
27529 tejbeer 1279
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1280
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1281
		model.addAttribute("selectedCategory", category);
1282
 
27509 tejbeer 1283
		return "warehouse_brand_item_stock";
1284
	}
1285
 
27538 tejbeer 1286
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1287
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1288
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1289
			throws Exception {
27539 tejbeer 1290
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1291
		if (warehouseId.contains(0)) {
1292
			warehouseId.addAll(warehouseMap.keySet());
1293
		}
27538 tejbeer 1294
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1295
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1296
 
27538 tejbeer 1297
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1298
		model.addAttribute("warehouseMap", warehouseMap);
1299
		return "warehouse_item_details";
1300
	}
1301
 
26114 amit.gupta 1302
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1303
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1304
		positionRetailers.stream().forEach(x -> {
1305
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1306
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1307
			}
1308
		});
26114 amit.gupta 1309
		return gson.toJson(warehouses);
1310
 
1311
	}
1312
 
27556 tejbeer 1313
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1314
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1315
			throws Exception {
27701 tejbeer 1316
 
1317
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1318
		String email = loginDetails.getEmailId();
1319
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1320
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1321
 
27670 tejbeer 1322
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1323
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1324
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1325
 
1326
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1327
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1328
 
1329
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1330
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1331
			if (bpt != null) {
1332
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1333
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1334
			} else {
1335
				bpt = new WarehouseWiseBrandSaleModel();
1336
				bpt.setWarehouseId(un.getWarehouseId());
1337
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1338
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1339
				bpt.setLms(0);
1340
				bpt.setLmtd(0);
1341
				bpt.setMtd(0);
1342
				bpt.setMtdQty(0);
1343
				bpt.setLmtd(0);
1344
				bpt.setLmtdQty(0);
1345
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1346
			}
1347
		}
27556 tejbeer 1348
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1349
 
1350
		Set<String> brands = inventoryService.getAllTagListingBrands();
1351
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1352
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1353
		model.addAttribute("brands", brands);
1354
		model.addAttribute("selectedbrand", brand);
1355
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1356
	}
1357
 
27594 tejbeer 1358
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1359
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1360
			@RequestParam String brand) throws Exception {
27701 tejbeer 1361
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1362
		String email = loginDetails.getEmailId();
1363
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1364
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1365
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1366
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1367
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1368
 
1369
		Set<String> brands = inventoryService.getAllTagListingBrands();
1370
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1371
		model.addAttribute("warehouseMap", warehouseMap);
1372
		model.addAttribute("brands", brands);
1373
		model.addAttribute("selectedbrand", brand);
1374
		return "warehousewise_accessoriesbrand_sale";
1375
	}
1376
 
27556 tejbeer 1377
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1378
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1379
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1380
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1381
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1382
		String email = loginDetails.getEmailId();
1383
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1384
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 1385
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1386
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1387
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1388
 
1389
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1390
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1391
 
1392
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1393
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1394
			if (bpt != null) {
1395
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1396
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1397
			} else {
1398
				bpt = new WarehouseBrandWiseItemSaleModel();
1399
				bpt.setWarehouseId(un.getWarehouseId());
1400
				bpt.setItemId(un.getItemId());
1401
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1402
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1403
				bpt.setBrand(un.getBrand());
1404
				bpt.setModelName(un.getModelName());
1405
				bpt.setModelNumber(un.getModelNumber());
1406
				bpt.setColor(un.getColor());
1407
				bpt.setLms(0);
1408
				bpt.setLmtd(0);
1409
				bpt.setMtd(0);
1410
				bpt.setMtdQty(0);
1411
				bpt.setLmtd(0);
1412
				bpt.setLmtdQty(0);
1413
				branditemSalesMap.put(un.getItemId(), bpt);
1414
			}
1415
		}
1416
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1417
		model.addAttribute("warehouseMap", warehouseMap);
1418
		return "warehouse_partner_itemwise_sale";
1419
	}
1420
 
27594 tejbeer 1421
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1422
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1423
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1424
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1425
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1426
		String email = loginDetails.getEmailId();
1427
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1428
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1429
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1430
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1431
		model.addAttribute("branditemSales", branditemSales);
1432
		model.addAttribute("warehouseMap", warehouseMap);
1433
		return "warehouse_accessories_itemwsie_sale";
1434
	}
1435
 
26012 amit.gupta 1436
	private List<Menu> prepareMenu(List<Menu> menus) {
1437
		List<Menu> returnMenu = new ArrayList<>();
1438
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1439
		for (Menu menu : menus) {
1440
			if (menu.get_parent() == null) {
26014 amit.gupta 1441
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1442
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1443
				}
1444
			} else {
26012 amit.gupta 1445
				Menu parentMenu = menu.get_parent();
1446
				if (!subMenuMap.containsKey(parentMenu)) {
1447
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1448
				}
26012 amit.gupta 1449
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1450
			}
1451
		}
26012 amit.gupta 1452
		subMenuMap.entrySet().stream().forEach(entry -> {
1453
			entry.getKey().setSubMenus(entry.getValue());
1454
			returnMenu.add(entry.getKey());
1455
		});
1456
		return returnMenu;
26005 amit.gupta 1457
	}
1458
 
24288 amit.gupta 1459
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1460
	private boolean hasGift(int fofoId) {
1461
		try {
24288 amit.gupta 1462
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1463
					.getAvailability() > 0;
24203 amit.gupta 1464
		} catch (ProfitMandiBusinessException e) {
1465
			return false;
1466
		}
1467
	}
24288 amit.gupta 1468
 
22354 ashik.ali 1469
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1470
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1471
		model.addAttribute("appContextPath", request.getContextPath());
1472
		return "contact-us";
1473
	}
23923 amit.gupta 1474
 
25649 tejbeer 1475
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1476
	public String getNotificationsWithType(HttpServletRequest request,
1477
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1478
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1479
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1480
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1481
		int userId = 0;
1482
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1483
		if (isAdmin) {
1484
			userId = loginDetails.getFofoId();
1485
		} else {
1486
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1487
		}
25683 tejbeer 1488
		List<Notification> notifications = null;
1489
 
26086 tejbeer 1490
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1491
				userId, offset, limit);
1492
		LOGGER.info("messageType" + messageType);
1493
		notifications = getNotifications(notificationCampaigns, messageType);
1494
 
25683 tejbeer 1495
		model.addAttribute("notifications", notifications);
1496
 
1497
		LOGGER.info("notifications" + notifications);
1498
		return "notification-template";
1499
	}
1500
 
1501
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1502
			throws ProfitMandiBusinessException {
1503
		List<Notification> notifications = new ArrayList<>();
1504
		Document document = null;
1505
		if (messageType != null) {
1506
			for (NotificationCampaign notificationCampaign : nc) {
1507
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1508
					Notification ns = new Notification();
1509
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1510
							SimpleCampaignParams.class);
1511
					Campaign campaign = new SimpleCampaign(scp);
1512
					LocalDateTime expire = campaign.getExpireTimestamp();
1513
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1514
					ns.setType(campaign.getType());
1515
					ns.setMessage(campaign.getMessage());
1516
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1517
					if (notificationCampaign.getDocumentId() != null) {
1518
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1519
						ns.setDocumentName(document.getDisplayName());
1520
					}
25683 tejbeer 1521
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1522
					ns.setShowImage(campaign.getShowImage());
1523
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1524
					ns.setDocumentId(notificationCampaign.getDocumentId());
1525
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1526
					ns.setCreated(
1527
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1528
									* 1000);
1529
					if (LocalDateTime.now().isAfter(expire)) {
1530
						ns.setExpired(true);
1531
					} else {
1532
						ns.setExpired(false);
1533
					}
1534
					notifications.add(ns);
1535
				}
1536
			}
25683 tejbeer 1537
		} else {
1538
			for (NotificationCampaign notificationCampaign : nc) {
1539
 
1540
				Notification ns = new Notification();
1541
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1542
						SimpleCampaignParams.class);
1543
				Campaign campaign = new SimpleCampaign(scp);
1544
				LocalDateTime expire = campaign.getExpireTimestamp();
1545
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1546
				ns.setType(campaign.getType());
1547
				ns.setMessage(campaign.getMessage());
1548
				ns.setTitle(campaign.getTitle());
1549
				if (notificationCampaign.getDocumentId() != null) {
1550
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1551
					ns.setDocumentName(document.getDisplayName());
1552
				}
1553
				ns.setUrl(campaign.getUrl());
1554
				ns.setShowImage(campaign.getShowImage());
1555
				ns.setImageUrl(campaign.getImageUrl());
1556
				ns.setDocumentId(notificationCampaign.getDocumentId());
1557
				ns.setMessageType(notificationCampaign.getMessageType());
1558
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1559
						* 1000);
1560
				if (LocalDateTime.now().isAfter(expire)) {
1561
					ns.setExpired(true);
1562
				} else {
1563
					ns.setExpired(false);
1564
				}
1565
				notifications.add(ns);
1566
			}
1567
 
25649 tejbeer 1568
		}
25683 tejbeer 1569
		return notifications;
25651 tejbeer 1570
 
1571
	}
25649 tejbeer 1572
 
25651 tejbeer 1573
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1574
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1575
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1576
			throws ProfitMandiBusinessException {
1577
		Document document = documentRepository.selectById(documentId);
1578
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1579
		if (nc.getDocumentId() == null) {
1580
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1581
		}
1582
		if (nc.getDocumentId() != documentId) {
1583
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1584
		}
1585
		return responseSender.ok(document);
25649 tejbeer 1586
	}
1587
 
25651 tejbeer 1588
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1589
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1590
			throws ProfitMandiBusinessException {
1591
 
1592
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1593
 
1594
		if (nc.getDocumentId() == null) {
1595
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1596
		}
1597
 
1598
		Document document = documentRepository.selectById(nc.getDocumentId());
1599
 
1600
		FileInputStream file = null;
1601
		try {
1602
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1603
		} catch (FileNotFoundException e) {
1604
			LOGGER.error("Retailer Document file not found : ", e);
1605
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1606
		}
1607
		// ByteArrayOutputStream byteArrayOutputStream = new
1608
		// ByteArrayOutputStream();
1609
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1610
 
1611
		final HttpHeaders headers = new HttpHeaders();
1612
		String contentType = "";
1613
		if (document.getContentType() == ContentType.JPEG) {
1614
			contentType = "image/jpeg";
1615
		} else if (document.getContentType() == ContentType.PNG) {
1616
			contentType = "image/png";
1617
		} else if (document.getContentType() == ContentType.PDF) {
1618
			contentType = "application/pdf";
1619
		}
1620
		headers.set("Content-Type", contentType);
1621
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1622
		headers.setContentLength(document.getSize());
1623
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1624
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1625
	}
26460 amit.gupta 1626
 
1627
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1628
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1629
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1630
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1631
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1632
			List<Integer> authIds = l2l1.getValue();
1633
			authIds.add(l2l1.getKey());
1634
 
1635
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1636
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1637
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1638
			if (!leads.isEmpty()) {
1639
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1640
			} else {
1641
				authIdAndleadsCountMap.put(auth.getId(), 0);
1642
			}
26422 tejbeer 1643
		}
26468 amit.gupta 1644
 
26460 amit.gupta 1645
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1646
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1647
				.collect(Collectors.toList());
26433 tejbeer 1648
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1649
 
26460 amit.gupta 1650
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1651
 
26460 amit.gupta 1652
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1653
		for (int authUserId : pp.keySet()) {
1654
			if (L2L1Mapping.keySet().contains(authUserId)) {
1655
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1656
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1657
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1658
						.collect(Collectors.toList());
27632 tejbeer 1659
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1660
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1661
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1662
			}
1663
		}
26997 amit.gupta 1664
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1665
				.collect(Collectors.toList());
26468 amit.gupta 1666
		PartnerDetailModel partnerDetailModel = partnerStatsService
1667
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1668
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1669
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1670
		return authIdAndallValues;
1671
	}
1672
 
27579 tejbeer 1673
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1674
	public String getItemWiseTertiary(HttpServletRequest request,
1675
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1676
			throws ProfitMandiBusinessException {
1677
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1678
 
1679
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1680
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1681
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1682
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1683
		return "item-wise-tertiary";
1684
	}
1685
 
27586 tejbeer 1686
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1687
	public String getItemWiseIndent(HttpServletRequest request,
1688
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1689
			throws ProfitMandiBusinessException {
1690
 
1691
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1692
		model.addAttribute("unbilledOrders", unbilledOrders);
1693
 
1694
		return "item-wise-indent";
1695
	}
1696
 
27636 tejbeer 1697
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1698
	public String getPartnerInvestment(HttpServletRequest request,
1699
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1700
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
1701
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1702
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1703
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1704
		model.addAttribute("customRetailer", customRetailer);
1705
		return "partner-investment";
1706
	}
27727 tejbeer 1707
 
27704 amit.gupta 1708
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1709
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1710
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1711
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1712
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1713
 
27704 amit.gupta 1714
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1715
		return "partner-pending-indent-item";
1716
	}
1717
 
27636 tejbeer 1718
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1719
	public String getPartnerActivateStockItem(HttpServletRequest request,
1720
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1721
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1722
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1723
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1724
 
1725
		for (InventoryItem inventoryItem : inventoryItems) {
1726
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1727
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1728
			ActivateItemModel aim = new ActivateItemModel();
1729
			aim.setFofoId(inventoryItem.getFofoId());
1730
			aim.setQuantity(inventoryItem.getGoodQuantity());
1731
			aim.setAmount(tagListing.getSellingPrice());
1732
			aim.setItemDescription(item.getItemDescription());
1733
			aim.setItemId(inventoryItem.getItemId());
1734
			activateStocks.add(aim);
1735
		}
1736
 
1737
		model.addAttribute("activateStocks", activateStocks);
1738
		model.addAttribute("customRetailer", customRetailer);
1739
		return "partner-activate-stock";
1740
	}
1741
 
1742
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1743
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
1744
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1745
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1746
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1747
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1748
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 1749
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1750
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 1751
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1752
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 1753
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1754
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1755
 
27636 tejbeer 1756
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1757
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 1758
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 1759
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 1760
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1761
 
27636 tejbeer 1762
		model.addAttribute("customRetailer", customRetailer);
1763
		return "partner-brand-mtd-sale";
1764
	}
1765
 
27637 tejbeer 1766
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1767
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
1768
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1769
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1770
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1771
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1772
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 1773
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1774
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 1775
 
1776
		Double accesorieslmtdsale = fofoOrderRepository
1777
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1778
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1779
				.get(fofoId);
27638 tejbeer 1780
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1781
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1782
				Optional.of(false)).get(fofoId);
1783
 
27637 tejbeer 1784
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 1785
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1786
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 1787
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1788
		model.addAttribute("customRetailer", customRetailer);
1789
		return "partner-brand-lmtd-sale";
1790
	}
1791
 
27660 tejbeer 1792
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1793
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
1794
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1795
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1796
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1797
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1798
 
1799
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 1800
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1801
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 1802
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1803
 
27893 tejbeer 1804
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1805
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 1806
		Long accesorieslmsqty = fofoOrderRepository
1807
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 1808
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 1809
				.get(fofoId);
1810
 
1811
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1812
		model.addAttribute("brandLmsQty", brandLmsQty);
1813
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1814
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1815
		model.addAttribute("customRetailer", customRetailer);
1816
		return "partner-brand-lms-sale";
1817
	}
1818
 
27640 tejbeer 1819
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1820
	public String getPatnerInStock(HttpServletRequest request,
1821
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1822
 
1823
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1824
 
27660 tejbeer 1825
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 1826
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 1827
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 1828
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1829
 
27660 tejbeer 1830
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1831
				.selectInStockItemsByBrand(fofoId);
1832
 
1833
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1834
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1835
 
1836
		model.addAttribute("stockItemMap", stockItemMap);
1837
		model.addAttribute("mobileStock", mobileStocks);
1838
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 1839
		model.addAttribute("customRetailer", customRetailer);
1840
		return "partner-instock-item";
1841
	}
1842
 
27660 tejbeer 1843
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1844
	public String getOpenTicketByFofoId(HttpServletRequest request,
1845
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1846
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1847
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1848
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1849
				.collect(Collectors.toList());
1850
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1851
 
1852
		for (TicketAssigned ticketAssign : ticketAssigns) {
1853
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1854
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1855
		}
1856
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1857
		model.addAttribute("ticketAssigns", ticketAssigns);
1858
		model.addAttribute("customRetailer", customRetailer);
1859
		return "open-ticket";
1860
	}
1861
 
27893 tejbeer 1862
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1863
	public String getPartnerSecondarySale(HttpServletRequest request,
1864
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
1865
			throws Exception {
1866
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1867
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1868
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1869
		LocalDateTime startDate = null;
1870
		LocalDateTime endDate = null;
1871
		List<InStockBrandModel> secondarySale = null;
1872
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1873
 
1874
		if (timeValue.equals("mtd")) {
1875
			startDate = curDate.withDayOfMonth(1);
1876
			endDate = curDate.with(LocalTime.MAX);
1877
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1878
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1879
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1880
			LOGGER.info("secondarySalemtd" + secondarySale);
1881
		} else if (timeValue.equals("lmtd")) {
1882
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1883
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1884
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1885
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1886
 
1887
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1888
			LOGGER.info("secondarySalelmtd" + secondarySale);
1889
 
1890
		} else {
1891
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1892
			endDate = curDate.withDayOfMonth(1);
1893
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1894
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1895
 
1896
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1897
			LOGGER.info("secondarySalelms" + secondarySale);
1898
 
1899
		}
1900
 
1901
		LOGGER.info("secondarySale" + secondarySale);
1902
		model.addAttribute("secondarySale", secondarySale);
1903
		model.addAttribute("secondaryItemSale", secondaryItemSale);
1904
		model.addAttribute("customRetailer", customRetailer);
1905
 
1906
		return "partner-secondary-order";
1907
	}
1908
 
21615 kshitij.so 1909
}